text
stringlengths 10
2.72M
|
|---|
package com.jpa.entity;
import javax.persistence.*;
import java.util.Set;
/**
* Created by Дарья on 04.03.2015.
*/
@Entity
@Table(name = "station")
@NamedQueries({
@NamedQuery(name = "Station.getAll", query = "SELECT c from Station c"),
@NamedQuery(name="Station.findByName", query="SELECT c FROM Station c WHERE c.name = :name") })
public class Station {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long idStation;
@Column(name = "Name", length = 100)
private String name;
public Station(String name) {
this.name = name;
}
public Station() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return idStation;
}
@Override
public String toString() {
return "Station{" +
"id=" + idStation +
", name='" + name +
'}';
}
// @ManyToMany
// @JoinTable(name="stopstation")
// private Set<Train> trains;
//
// public Set<Train> getTrain() {
// return trains;
// }
//
// public void setTrain(Set<Train> trains) {
// this.trains = trains;
// }
@OneToMany(fetch = FetchType.EAGER, mappedBy = "stationFrom")
private Set<Schedule> stationFrom;
public Set<Schedule> getScheduleFrom() {
return stationFrom;
}
public void setScheduleFrom(Set<Schedule> stopStation) {
this.stationFrom = stopStation;
}
public void addScheduleFrom(Schedule schedule) {
stationFrom.add(schedule);
}
@OneToMany(fetch = FetchType.EAGER, mappedBy = "stationTo")
private Set<Schedule> stationTo;
public Set<Schedule> getScheduleTo() {
return stationTo;
}
public void setScheduleTo(Set<Schedule> stopStation) {
this.stationTo = stopStation;
}
public void addScheduleTo(Schedule schedule) {
stationTo.add(schedule);
}
}
|
package com.shashi.customer.service;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.shashi.customer.model.Customer;
import com.shashi.customer.model.CustomerDB;
/*This Utils Call we are using for Serializtion, we have defined two method to Serialize the objects
and also DeSerialize objects.*/
public class SerializeUtils {
/*
* this the file location where the POJO Objects are being saved in file in
* binary format by using Serializtion.
*/
private final static String FILE_LOC = "C:\\develop\\config\\Customer.ser";
// This is a simple Constructor no-argument for the Class
private SerializeUtils() {
}
// this is the Serializtion Code Logic, we are using CustomerDB Class which our in-memory DataBase is.
public static void serialize(CustomerDB customerDb) {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(FILE_LOC))) {
out.writeObject(customerDb);
} catch (Exception e) {
e.printStackTrace();
}
}
// this is the De-serializtion Code Logic, we are using CustomerDB Class which our in-memory DataBase is.
public static CustomerDB deserialize() {
CustomerDB result = new CustomerDB();
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE_LOC))) {
result = (CustomerDB) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// This is just the main method to run the code within same Class instead of creating new Class/Layer to run code
public static void main(String[] args) {
CustomerDB customers = new CustomerDB();
// Customer customer = new Customer(customers.nextId(), "James", "Norman");
Customer customer = Customer.builder().firstName("James").lastName("Norman").build();
customers.getCustomers().put(customer.getId(), customer);
SerializeUtils.serialize(customers);
customers = SerializeUtils.deserialize();
System.out.println(customers.getCustomers());
}
}
|
package com.sunrj.application.System.model;
import java.util.List;
public class TestModel {
private String id;
private String ccode;
private String cname;
private String cpar_code;
private String cpar_name;
private String test1;
private String test2;
public String getTest1() {
return test1;
}
public void setTest1(String test1) {
this.test1 = test1;
}
@Override
public String toString() {
return "TestModel [test1=" + test1 + ", test2=" + test2 + "]";
}
public String getTest2() {
return test2;
}
public void setTest2(String test2) {
this.test2 = test2;
}
private List<TestModel> children;
public List<TestModel> getChildren() {
return children;
}
public void setChildren(List<TestModel> children) {
this.children = children;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCcode() {
return ccode;
}
public void setCcode(String ccode) {
this.ccode = ccode;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCpar_code() {
return cpar_code;
}
public void setCpar_code(String cpar_code) {
this.cpar_code = cpar_code;
}
public String getCpar_name() {
return cpar_name;
}
public void setCpar_name(String cpar_name) {
this.cpar_name = cpar_name;
}
}
|
import java.util.*;
public class BlockTheBlockPuzzle {
private final int INF = 250 * 250;
private int[][] graph;
private int source;
private int sink;
public int minimumHoles(String[] board) {
int goalRow = -1;
int goalColumn = -1;
for(int i = 0; i < board.length; ++i) {
for(int j = 0; j < board[i].length(); ++j) {
if(board[i].charAt(j) == '$') {
goalRow = i;
goalColumn = j;
}
}
}
graph = new int[2000][2000];
for(int i = 0; i < graph.length; ++i) {
for(int j = 0; j < graph[i].length; ++j) {
graph[i][j] = -1;
}
}
int[][] map = new int[board.length][board[0].length()];
for(int i = 0; i < map.length; ++i) {
for(int j = 0; j < map[i].length; ++j) {
map[i][j] = -1;
}
}
source = 0;
sink = 1;
int current = 2;
for(int i = goalRow%3; i < board.length; i += 3) {
for(int j = goalColumn%3; j < board[i].length(); j += 3) {
if(board[i].charAt(j) == '.') {
graph[current][current + 1] = 1;
map[i][j] = current;
current += 2;
} else if(board[i].charAt(j) == 'b') {
graph[current][current + 1] = INF;
graph[current + 1][sink] = INF;
map[i][j] = current;
current += 2;
} else if(board[i].charAt(j) == '$') {
graph[source][current] = INF;
graph[current][current + 1] = INF;
map[i][j] = current;
current += 2;
}
if(board[i].charAt(j) != 'H') {
int thisVertex = map[i][j];
if(3 <= i) {
int other = map[i - 3][j];
if(other != -1) {
int cost = 0;
for(int k = i - 2; k < i; ++k) {
if(board[k].charAt(j) == '.') {
++cost;
} else if(board[k].charAt(j) == 'b') {
cost += INF;
}
}
cost = Math.min(cost, INF);
if(cost != 0) {
graph[other + 1][thisVertex] = cost;
graph[thisVertex + 1][other] = cost;
}
}
}
if(3 <= j) {
int other = map[i][j - 3];
if(other != -1) {
int cost = 0;
for(int k = j - 2; k < j; ++k) {
if(board[i].charAt(k) == '.') {
++cost;
} else if(board[i].charAt(k) == 'b') {
cost += INF;
}
}
cost = Math.min(cost, INF);
if(cost != 0) {
graph[other + 1][thisVertex] = cost;
graph[thisVertex + 1][other] = cost;
}
}
}
}
}
}
int maxFlow = maxFlow();
if(INF <= maxFlow) {
return -1;
}
return maxFlow;
}
private int maxFlow() {
boolean done = false;
int maxFlow = 0;
int[][] usedFlow = new int[graph.length][graph[0].length];
while(!done) {
int pathCapacity = 0;
int[] parents = new int[graph.length];
int[] capacityTable = new int[graph.length];
for(int i = 0; i < parents.length; ++i) {
parents[i] = -1;
}
parents[source] = -2;
capacityTable[source] = Integer.MAX_VALUE;
ArrayList<Integer> queue = new ArrayList<>();
queue.add(source);
for(int i = 0; i < queue.size() && !done; ++i) {
int current = queue.get(i);
for(int j = 0; j < graph[current].length && !done; ++j) {
if(graph[current][j] != -1) {
if(0 < graph[current][j] - usedFlow[current][j] && parents[j] == -1) {
parents[j] = current;
capacityTable[j] = Math.min(capacityTable[current], graph[current][j] - usedFlow[current][j]);
if(j != sink) {
queue.add(j);
} else {
done = true;
pathCapacity = capacityTable[j];
}
}
} else if(graph[j][current] != -1) {
if(0 < 0 - usedFlow[current][j] && parents[j] == -1) {
parents[j] = current;
capacityTable[j] = Math.min(capacityTable[current], 0 - usedFlow[current][j]);
if(j != sink) {
queue.add(j);
} else {
done = true;
pathCapacity = capacityTable[j];
}
}
}
}
}
done = false;
if(pathCapacity == 0) {
done = true;
} else {
maxFlow += pathCapacity;
int current = sink;
while(current != source) {
int next = parents[current];
usedFlow[next][current] = usedFlow[next][current] + pathCapacity;
usedFlow[current][next] = usedFlow[current][next] - pathCapacity;
current = next;
}
}
}
return maxFlow;
}
}
|
package com.questionanswer.questionanswer.model;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.context.WebApplicationContext;
@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Session {
private int id = 0;
private String username;
private boolean isAdmin;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package controllers;
public interface ControllerVisitor {
void visit(StartController controller);
void visit(ProposeController controller);
void visit(ResumeController controller);
}
|
package com.cht.training.Lab13;
public class Employee {
static {
counter = 200;
}
private static int counter;
public Employee(){
counter++;
}
public static int getCounter() {//若可以宣告為staic的函數或變數盡量宣告為staic,因為會被直接放入固定記憶體,存取較快速
return counter;
}
public static void main(String[] args) {
for(int i=0; i<10;i ++){
Employee e1 =new Employee();
System.out.println(Employee.getCounter());
}
}
}
|
package com.bofsoft.laio.customerservice.DataClass.index;
import com.bofsoft.laio.data.BaseData;
/**
* 产品服务协议
*
* @author admin
*/
public class ProductRuleUrlData extends BaseData {
// 请求参数
// ProType Integer 产品类型,0招生类产品,1培训类产品;
private String Url; // String 规则连接
public String getUrl() {
return Url;
}
public void setUrl(String url) {
Url = url;
}
}
|
package classes.facade;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import classes.core.IDAO;
import classes.core.IFacade;
import classes.core.IStrategy;
import classes.core.DAO.EventoDAO;
import classes.core.DAO.EventosParticipanteDAO;
import classes.core.DAO.FornecedorDAO;
import classes.core.DAO.ItemProdutoDAO;
import classes.core.DAO.LocacaoDAO;
import classes.core.DAO.ParticipanteDAO;
import classes.core.DAO.ParticipanteEventoDAO;
import classes.core.DAO.ProdutoDAO;
import classes.core.DAO.RateioDAO;
import classes.core.DAO.RateioProdutoDAO;
import classes.core.DAO.RelatorioDAO;
import classes.core.DAO.UsuarioDAO;
import classes.strategy.ValidarDados;
import classes.strategy.ValidarDadosParticipante;
import classes.strategy.ValidarDadosProduto;
import classes.strategy.ValidarDadosUsuario;
import classes.strategy.ValidarEndereco;
import classes.strategy.ValidarExistencia;
import classes.strategy.ValidarExistenciaEvento;
import classes.strategy.ValidarExistenciaParticipanteEvento;
import classes.util.Resultado;
import dominio.endereco.Locacao;
import dominio.evento.Evento;
import dominio.evento.IDominio;
import dominio.evento.ListaEventosParticipante;
import dominio.evento.Rateio;
import dominio.evento.RateioProduto;
import dominio.participantes.Administrador;
import dominio.participantes.Participante;
import dominio.produto.Fornecedor;
import dominio.produto.ItemProduto;
import dominio.produto.Produto;
import dominio.relatorios.Relatorio;
import dominio.viewmodels.ParticipanteEventoVM;
public class Facade implements IFacade{
private Resultado resultado;
private Map<String, Map<String, List<IStrategy>>> rns;
// mapa para os DAOS
private Map<String, IDAO> daos;
// construtor
public Facade() {
/* Intanciando o Map de DAOS */
daos = new HashMap<String, IDAO>();
/* Intanciando o Map de Regras de Negocio */
rns = new HashMap<String, Map<String, List<IStrategy>>>();
EventoDAO evtDAO = new EventoDAO();
ParticipanteDAO ptcDAO = new ParticipanteDAO();
UsuarioDAO usrDAO = new UsuarioDAO();
ProdutoDAO pdtDAO = new ProdutoDAO();
ItemProdutoDAO itemDAO = new ItemProdutoDAO();
FornecedorDAO fncDAO = new FornecedorDAO();
LocacaoDAO locDAO = new LocacaoDAO();
ParticipanteEventoDAO peDAO = new ParticipanteEventoDAO();
RateioDAO ratDAO = new RateioDAO();
EventosParticipanteDAO evpDAO = new EventosParticipanteDAO();
RelatorioDAO rDAO = new RelatorioDAO();
RateioProdutoDAO rpDAO = new RateioProdutoDAO();
daos.put(Evento.class.getName(), evtDAO);
daos.put(Participante.class.getName(), ptcDAO);
daos.put(Administrador.class.getName(), usrDAO);
daos.put(Produto.class.getName(), pdtDAO);
daos.put(ItemProduto.class.getName(), itemDAO);
daos.put(Fornecedor.class.getName(), fncDAO);
daos.put(Locacao.class.getName(), locDAO);
daos.put(ParticipanteEventoVM.class.getName(), peDAO);
daos.put(Rateio.class.getName(), ratDAO);
daos.put(RateioProduto.class.getName(), rpDAO);
daos.put(ListaEventosParticipante.class.getName(), evpDAO);
daos.put(Relatorio.class.getName(), rDAO);
// Instanciando strategies Evento
ValidarDados vDados = new ValidarDados();
//ValidarExistenciaEvento veEvento = new ValidarExistenciaEvento();
// Instanciando strategies Participante
ValidarExistencia vExistencia = new ValidarExistencia();
ValidarDadosParticipante vDadosParticipante = new ValidarDadosParticipante();
ValidarEndereco vEndereco = new ValidarEndereco();
// Instanciando strategies Usuário
ValidarDadosUsuario vDadosUsuario = new ValidarDadosUsuario();
// Instanciando strategies Produto
ValidarDadosProduto vDadosProduto = new ValidarDadosProduto();
// Instanciando strategies dos participantes do evento
ValidarExistenciaParticipanteEvento vParticipanteEvento = new ValidarExistenciaParticipanteEvento();
// Listas de strategies para as operações do evento
List<IStrategy> rnsSalvarEvento = new ArrayList<IStrategy>();
List<IStrategy> rnsAlterarEvento = new ArrayList<IStrategy>();
List<IStrategy> rnsConsultarEvento = new ArrayList<IStrategy>();
List<IStrategy> rnsExcluirEvento = new ArrayList<IStrategy>();
// Listas de strategies para as operações de participante
List<IStrategy> rnsSalvarParticipante = new ArrayList<IStrategy>();
List<IStrategy> rnsAlterarParticipante = new ArrayList<IStrategy>();
List<IStrategy> rnsConsultarParticipante = new ArrayList<IStrategy>();
List<IStrategy> rnsExcluirParticipante = new ArrayList<IStrategy>();
// Lista de strategies para as operações de usuario
List<IStrategy> rnsSalvarUsuario = new ArrayList<IStrategy>();
List<IStrategy> rnsAlterarUsuario = new ArrayList<IStrategy>();
List<IStrategy> rnsConsultarUsuario = new ArrayList<IStrategy>();
List<IStrategy> rnsExcluirUsuario = new ArrayList<IStrategy>();
// Lista de strategies para as operações de Produto
List<IStrategy> rnsSalvarProduto = new ArrayList<IStrategy>();
List<IStrategy> rnsAlterarProduto = new ArrayList<IStrategy>();
// Lista de strategies para as operações do Participante do evento
List<IStrategy> rnsSalvarPtcEvento = new ArrayList<IStrategy>();
// Regras de negócio sendo inseridas para o evento
rnsSalvarEvento.add(vDados);
//rnsSalvarEvento.add(veEvento);
rnsAlterarEvento.add(vDados);
// Regras de negócio sendo inseridas para o participante
rnsSalvarParticipante.add(vExistencia);
rnsSalvarParticipante.add(vDadosParticipante);
rnsSalvarParticipante.add(vEndereco);
rnsAlterarParticipante.add(vDadosParticipante);
rnsAlterarParticipante.add(vEndereco);
// Regras de negócio sendo inseridas para o usuario
rnsConsultarUsuario.add(vDadosUsuario);
// Regras de negócio sendo inseridas para o produto
rnsSalvarProduto.add(vDadosProduto);
rnsAlterarProduto.add(vDadosProduto);
// Regras de negócio sendo inseridas para o participante do evento
rnsSalvarPtcEvento.add(vParticipanteEvento);
// Mapa para armazenar todas as operações do evento
Map<String, List<IStrategy>> rnsEvento = new HashMap<String, List<IStrategy>>();
rnsEvento.put("SALVAR", rnsSalvarEvento);
rnsEvento.put("ALTERAR", rnsAlterarEvento);
rnsEvento.put("CONSULTAR", rnsConsultarEvento);
rnsEvento.put("EXCLUIR", rnsExcluirEvento);
// Mapa para armazenar todas as operações do participante
Map<String, List<IStrategy>> rnsParticipante = new HashMap<String, List<IStrategy>>();
rnsParticipante.put("SALVAR", rnsSalvarParticipante);
rnsParticipante.put("ALTERAR", rnsAlterarParticipante);
rnsParticipante.put("CONSULTAR", rnsConsultarParticipante);
rnsParticipante.put("EXCLUIR", rnsExcluirParticipante);
// Mapa para armazenar todas as operações do usuário
Map<String, List<IStrategy>> rnsUsuario = new HashMap<String, List<IStrategy>>();
rnsUsuario.put("CONSULTAR", rnsConsultarUsuario);
// Mapa para armazenar todas as operações do produto
Map<String, List<IStrategy>> rnsProduto = new HashMap<String, List<IStrategy>>();
rnsProduto.put("SALVAR", rnsSalvarProduto);
rnsProduto.put("ALTERAR", rnsAlterarProduto);
Map<String, List<IStrategy>> rnsPtcEvento = new HashMap<String, List<IStrategy>>();
rnsPtcEvento.put("SALVAR", rnsSalvarPtcEvento);
// Mapa para todas as regras de negócio de um determinado domínio
rns.put(Evento.class.getName(), rnsEvento);
rns.put(Participante.class.getName(), rnsParticipante);
rns.put(Administrador.class.getName(), rnsUsuario);
rns.put(Produto.class.getName(), rnsProduto);
rns.put(ParticipanteEventoVM.class.getName(), rnsPtcEvento);
}
@Override
public Resultado salvar(IDominio entidade) {
resultado = new Resultado();
String nmClasse = entidade.getClass().getName();
String msg = executarRegras(entidade, "SALVAR");
if(msg == null ) {
IDAO dao = daos.get(nmClasse);
try {
dao.salvar(entidade);
List<IDominio> entidades = new ArrayList<IDominio>();
entidades.add(entidade);
resultado.setEntidades(entidades);
} catch(SQLException e) {
e.printStackTrace();
System.out.println("Fachada: Não foi possível realizar o registro!");
resultado.setMensagem("Não foi possível realizar o registro!");
}
} else {
resultado.setMensagem(msg);
}
return resultado;
}
@Override
public Resultado consultar(IDominio entidade) {
resultado = new Resultado();
String nmClasse = entidade.getClass().getName();
System.out.println("NOME NA FACHADA: " + nmClasse);
IDAO dao = daos.get(nmClasse);
try {
List<IDominio> lista = dao.consultar(entidade);
resultado.setEntidades(lista);
} catch(SQLException e) {
e.printStackTrace();
System.out.println("Fachada: Não foi possível consultar o registro!");
resultado.setMensagem("Não foi possível consultar o registro!");
}
return resultado;
}
@Override
public Resultado alterar(IDominio entidade) {
resultado = new Resultado();
String nmClasse = entidade.getClass().getName();
String msg = executarRegras(entidade, "ALTERAR");
if(msg == null ) {
IDAO dao = daos.get(nmClasse);
try {
dao.alterar(entidade);
List<IDominio> entidades = new ArrayList<IDominio>();
entidades.add(entidade);
resultado.setEntidades(entidades);
System.out.println("obj alterado!");
} catch(SQLException e) {
e.printStackTrace();
System.out.println("Fachada: Não foi possível atualizar o registro!");
resultado.setMensagem("Não foi possível atualizar o registro!");
}
} else {
resultado.setMensagem(msg);
}
return resultado;
}
@Override
public Resultado excluir(IDominio entidade) {
resultado = new Resultado();
String nmClasse = entidade.getClass().getName();
String msg = executarRegras(entidade, "EXCLUIR");
if(msg == null ) {
IDAO dao = daos.get(nmClasse);
try {
dao.excluir(entidade);
List<IDominio> entidades = new ArrayList<IDominio>();
entidades.add(entidade);
resultado.setEntidades(entidades);
System.out.println("obj excluído!");
} catch(SQLException e) {
e.printStackTrace();
System.out.println("Fachada: Não foi possível excluir o registro!");
resultado.setMensagem("Não foi possível excluir o registro!");
}
} else {
resultado.setMensagem(msg);
}
return resultado;
}
private String executarRegras(IDominio entidade, String operacao) {
String nmClasse = entidade.getClass().getName();
StringBuilder msg = new StringBuilder();
Map<String, List<IStrategy>> regrasOperacao = rns.get(nmClasse);
if(regrasOperacao != null) {
List<IStrategy> regras = regrasOperacao.get(operacao);
if(regras != null) {
for(IStrategy s : regras) {
String m = s.processar(entidade);
if(m != null) {
msg.append(m);
msg.append("\n");
}
}
}
}
if(msg.length() > 0) {
return msg.toString();
} else {
return null;
}
}
}
|
package com.barclaycard.currency.validator;
import com.barclaycard.currency.model.CurrencyDetails;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Component
public class CurrencyValidator implements Validator {
public boolean supports(Class<?> paramClass) {
return CurrencyDetails.class.equals(paramClass);
}
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "amount", "valid.amount");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "currency", "valid.currency");
}
}
|
package pl.com.dropbox;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class MainClass {
public static void main(String[] args) throws IOException {
BlockingQueue<Message> myQueue = new ArrayBlockingQueue<>(30);
Client p = new Client("Pedro", "C:\\Locally\\Pedroo", myQueue);
Thread t_p = new Thread(p);
t_p.start();
Client p2 = new Client("Staszek", "C:\\Locally\\Staszek", myQueue);
Thread t_p2 = new Thread(p2);
t_p2.start();
MyExecutor e = new MyExecutor(myQueue);
Thread t_e = new Thread(e);
t_e.start();
//Server s = new Server("C:\\Servers", "testowyplik", "psob", "S1");
//Thread s1 = new Thread(s);
//s1.start();
}
}
|
package a50;
/**
* @author 方康华
* @title SearchInRotatedSortedArray
* @projectName leetcode
* @description No.33 Medium
*/
public class SearchInRotatedSortedArray {
public int search(int[] nums, int target) {
return find(nums, 0, nums.length - 1, target);
}
public int find(int[] nums, int left, int right, int target) {
if(left > right || (left == right && nums[left] != target)) return -1;
int mid = (left + right) / 2;
if(nums[mid] == target) return mid;
if(nums[left] < nums[mid]) {
if(nums[left] <= target && target <= nums[mid - 1])
return find(nums, left, mid - 1, target);
else
return find(nums, mid + 1, right, target);
}
else {
if(nums[mid + 1] <= target && target <= nums[right])
return find(nums, mid + 1, right, target);
else
return find(nums, left, mid - 1, target);
}
}
public static void main(String[] args) {
SearchInRotatedSortedArray ex = new SearchInRotatedSortedArray();
System.out.println(ex.search(new int[]{4,5,6,7,8,1,2,3}, 8));
}
}
|
package com.example.app_ex3;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View main_screen = inflater.inflate(R.layout.fragment_main, container, false);
Button rick = (Button) main_screen.findViewById(R.id.rick);
Button morty = (Button) main_screen.findViewById(R.id.morty);
rick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), Rick_or_morty_activity.class);
intent.putExtra("fragmetToLoad", "rick");
startActivity(intent);
}
});
morty.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), Rick_or_morty_activity.class);
intent.putExtra("fragmetToLoad", "morty");
startActivity(intent);
}
});
return main_screen;
}
}
|
package com.shinjinhun.jsonparserexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private long backBtnTime = 0;
private TextView tv;
private String str =
"[{'name':'배트맨','age':43,'address':'고담'},"+
"{'name':'슈퍼맨','age':36,'address':'뉴욕'},"+
"{'name':'앤트맨','age':25,'address':'LA'}]";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tvResult1);
Button b = (Button)findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
doJSONParser();
}
});
Button btn_next = (Button)findViewById(R.id.btn_next);
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SubActivity.class);
intent.putExtra("str",str);
startActivity(intent);
finish(); // MainActivity 종료
}
});
}
@Override
public void onBackPressed() {
long curTime = System.currentTimeMillis();
long gatTime = curTime - backBtnTime;
if(0 <= gatTime && 2000 >= gatTime) { // 2초안에 백버튼 2번 연속 클릭시 앱 종료 실행
super.onBackPressed();
} else {
backBtnTime = curTime;
Toast.makeText(this,"한번 더 누르면 종료됩니다.",Toast.LENGTH_SHORT).show();
}
}
private void doJSONParser() {
StringBuffer sb = new StringBuffer();
try {
JSONArray jarray = new JSONArray(str); // JSONArray 생성
for(int i=0; i < jarray.length(); i++){
JSONObject jObject = jarray.getJSONObject(i); // JSONObject 추출
String address = jObject.getString("address");
String name = jObject.getString("name");
int age = jObject.getInt("age");
sb.append(
"이름:" + name +
", 주소:" + address +
", 나이:" + age + "\n"
);
}
tv.setText(sb.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
|
package com.developworks.jvmcode;
/**
* <p>Title: isub</p>
* <p>Description: int数值相减</p>
* <p>Author: ouyp </p>
* <p>Date: 2018-05-20 14:30</p>
*/
public class isub {
public void isub(int i, int i2) {
int ii = i - i2;
}
}
/**
* public void isub(int, int);
* Code:
* 0: iload_1
* 1: iload_2
* 2: isub
* 3: istore_3
* 4: return
*/
|
package Lec_04_NestedConditionalStatements;
import java.util.Scanner;
public class Pro_04_08_HotelRoom {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Въведете име на месец: ");
String month = scanner.nextLine();
System.out.print("Въведете брой нощувки: ");
int numDays = Integer.parseInt(scanner.nextLine());
double studioPrice = 0.0;
double aparttmentPrice = 0.0;
if ("May".equalsIgnoreCase(month) || "October".equalsIgnoreCase(month)){
if (numDays > 14){
studioPrice = (50.00 * numDays) * 0.70;
aparttmentPrice = (65.00 * numDays) * 0.90;
} else if (numDays > 7){
studioPrice = (50.00 * numDays) * 0.95;
aparttmentPrice = 65.00 * numDays;
} else if (numDays > 0){
studioPrice = 50.00 * numDays;
aparttmentPrice = 65.00 * numDays;
}
} else if ("June".equalsIgnoreCase(month) || "September".equalsIgnoreCase(month)){
if (numDays > 14){
studioPrice = (75.20 * numDays) * 0.80;
aparttmentPrice = (68.70 * numDays) * 0.90;
} else if (numDays >0){
studioPrice = 75.20 * numDays;
aparttmentPrice = 68.70 * numDays;
}
} else if ("July".equalsIgnoreCase(month) || "August".equalsIgnoreCase(month)){
studioPrice = 76.00 * numDays;
if (numDays > 14){
aparttmentPrice = (77.00 * numDays) * 0.90;
} else if(numDays > 0){
aparttmentPrice = 77.00 * numDays;
}
}
System.out.printf("Apartment: %.2f lv.%nStudio: %.2f lv.", aparttmentPrice, studioPrice);
}
}
|
package com.example.demo;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Value;
public class AttemptWriter implements ItemWriter<Attempt> {
private static final Logger logger = LoggerFactory.getLogger(AttemptWriter.class);
@Value("${processed-directory}")
private String processedDirectory;
@Value("${failed-directory}")
private String failedDirectory;
@Override
public void write(List<? extends Attempt> attempts) throws Exception {
for (Attempt attempt : attempts) {
if(attempt.isSuccess()){
}
moveFile(attempt);
}
}
private void moveFile(Attempt attempt) {
if(!attempt.hasSystemError()){
File processedDateDirectory = new File(processedDirectory
+ System.getProperty("file.separator")
+ new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis()));
File failedDateDirectory = new File(failedDirectory
+ System.getProperty("file.separator")
+ new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis()));
if(attempt.isSuccess() && !processedDateDirectory.exists()){
logger.info("Creating processed date directory {}", processedDateDirectory.getName());
processedDateDirectory.mkdir();
}
if(!attempt.isSuccess() && !failedDateDirectory.exists()){
logger.info("Creating failed date directory {}", failedDateDirectory.getName());
failedDateDirectory.mkdir();
}
logger.info("Moving {} document: {}.", attempt.isSuccess() ? "processed" : "failed",
attempt.getFile().getName());
String directory = attempt.isSuccess() ? processedDateDirectory.getAbsolutePath()
: failedDateDirectory.getAbsolutePath();
attempt.getFile().renameTo(new File(directory + System.getProperty("file.separator")+attempt.getFile().getName()));
}
}
}
|
package de.ndn.game.platformer.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import de.ndn.game.platformer.gameobjects.MainCamera;
import de.ndn.game.platformer.gameobjects.Meeple;
/**
* Created by nickn on 22.02.2018.
*/
public class InputHandling extends InputListener {
private MainCamera camera;
private Meeple meeple;
public InputHandling(MainCamera camera, Meeple meeple) {
super();
this.camera = camera;
this.meeple = meeple;
}
public void handleInput() {
if(!(Gdx.input.isKeyPressed(Input.Keys.RIGHT)
&& Gdx.input.isKeyPressed(Input.Keys.LEFT))) {
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) meeple.walkRight();
else if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) meeple.walkLeft();
else meeple.standStill();
}
if(Gdx.input.isKeyJustPressed(Input.Keys.UP)) {
meeple.jump();
}
if(Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
meeple.duck();
}
//Debugging
if(!(Gdx.input.isKeyPressed(Input.Keys.NUMPAD_8)
&& Gdx.input.isKeyPressed(Input.Keys.NUMPAD_2))) {
if(Gdx.input.isKeyPressed(Input.Keys.NUMPAD_8)) camera.moveUp();
if(Gdx.input.isKeyPressed(Input.Keys.NUMPAD_2)) camera.moveDown();
}
if(!(Gdx.input.isKeyPressed(Input.Keys.NUMPAD_6)
&& Gdx.input.isKeyPressed(Input.Keys.NUMPAD_4))) {
if(Gdx.input.isKeyPressed(Input.Keys.NUMPAD_6)) camera.moveRight();
if(Gdx.input.isKeyPressed(Input.Keys.NUMPAD_4)) camera.moveLeft();
}
if(!(Gdx.input.isKeyPressed(Input.Keys.NUMPAD_9)
&& Gdx.input.isKeyPressed(Input.Keys.NUMPAD_3))) {
if(Gdx.input.isKeyPressed(Input.Keys.NUMPAD_9)) camera.zoomIn();
if(Gdx.input.isKeyPressed(Input.Keys.NUMPAD_3)) camera.zoomOut();
}
}
}
|
package tw.org.iiijava;
public class zora19 {
public static void main(String[] args) {
int p1,p2,p3,p4,p5,p6;
p1=p2=p3=p4=p5=p6=0;
for(int i=0;i<100;i++){
int point = (int) (Math.random()*6+1);//1-6
switch(point){
case 1:p1++;break;
case 2:p2++;break;
case 3:p3++;break;
case 4:p4++;break;
case 5:p5++;break;
case 6:p6++;break;
}
}
System.out.println("1點出現"+p1+"次");
System.out.println("2點出現"+p2+"次");
System.out.println("3點出現"+p3+"次");
System.out.println("4點出現"+p4+"次");
System.out.println("5點出現"+p5+"次");
System.out.println("6點出現"+p6+"次");
}
}
|
package com.example.hotel.model.rooms;
public enum AvailableStatus {
AVAILABLE,
NOT_AVAILABLE
}
|
import java.util.Arrays;
/**
* 编辑距离 https://leetcode-cn.com/problems/edit-distance/
*/
public class 编辑距离 {
public static void main(String[] args) {
编辑距离 t=new 编辑距离();
System.out.println(t.minDistance("intention","execution"));
System.out.println(t.minDistance2("intention","execution"));
}
public int minDistance2(String word1, String word2) {//空间优化
int[] cur=new int[word2.length()+1];
for(int j=1;j<cur.length;j++) cur[j]=j;
int temp=0;
for(int i=1;i<word1.length()+1;i++) {
cur[0]=i;
int last=i-1;
for (int j=1;j<cur.length;j++) {
temp=cur[j];
if(word1.charAt(i-1)==word2.charAt(j-1)){
cur[j]=last;
}else {
cur[j]=Math.min(cur[j-1],Math.min(cur[j],last))+1;
}
last=temp;
}
}
return cur[cur.length-1];
}
public int minDistance(String word1, String word2) {
int[][] dp=new int[word1.length()+1][word2.length()+1];
for(int i=1;i<dp.length;i++) dp[i][0]=i;
for(int j=1;j<dp[0].length;j++) dp[0][j]=j;
for(int i=1;i<dp.length;i++){
for(int j=1;j<dp[0].length;j++){
//从2个单词末尾开始比较,分相同和不相同的情况讨论,然后采用递归,即自顶向下的思维去推导出状态转移方程
//但是实际写程序的时候使用自底向上的方式,即loop,使得程序性能更高
if(word1.charAt(i-1)==word2.charAt(j-1)){
dp[i][j]=dp[i-1][j-1];
}else {
dp[i][j]=Math.min(dp[i][j-1],Math.min(dp[i-1][j],dp[i-1][j-1]))+1;
}
}
}
return dp[word1.length()][word2.length()];
}
}
|
package textanalysis.wikipediaindex;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashSet;
import textanalysis.dbutils.DBUtils;
public class IndexInfoDBWriter {
private final static String WIKIPEDIA_DUMP_APTH = "resources/ar-wikipedia/ar-wiki-dump";
private DBUtils dbUtils;
public IndexInfoDBWriter() {
dbUtils = new DBUtils();
}
private BufferedReader dumpReader;
public void writeToDB() throws IOException, SQLException {
dumpReader = new BufferedReader(new FileReader(WIKIPEDIA_DUMP_APTH));
int counter = 0;
Article article;
HashSet<String> distinctName = new HashSet<String>();
while ((article = nextArticle()) != null) {
if (distinctName.contains(article.name))
continue;
distinctName.add(article.name);
article.indexId = counter;
dbUtils.addWikipediaConcept(article);
System.out.println(counter++);
}
System.out.println(distinctName.size());
}
/**
*
* @return null if no more articles
* @throws IOException
*/
private Article nextArticle() throws IOException {
String line;
if ((line = dumpReader.readLine()) == null)
return null;
StringBuilder contentBuilder = new StringBuilder("");
Article article = new Article();
article.name = line;
article.url = dumpReader.readLine();
article.tags = dumpReader.readLine().split(",");
do {
line = dumpReader.readLine();
if (line.equals(ARTICLE_TERMINATION)) {
article.content = contentBuilder.toString();
return article;
}
contentBuilder.append(line);
} while (true);
}
private final static String ARTICLE_TERMINATION = "=================*==============END=================*==============";
public static void main(String[] args) throws IOException, SQLException {
new IndexInfoDBWriter().writeToDB();
}
}
|
package com.cambi.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.testng.Assert;
import com.cambi.selenium.framework.BasePage;
import com.graphbuilder.curve.Point;
import io.appium.java_client.PerformsTouchActions;
import io.appium.java_client.TouchAction;
public class HistoryPage extends BasePage{
public HistoryPage(WebDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
}
@FindBy(xpath = "//android.widget.TextView[@text='Transactions']")
public WebElement transactionsTital;
@FindBy(id = "io.cambi:id/toolbar_title")
public WebElement transactionsPage;
@FindBy(id = "io.cambi:id/timeStamp")
public WebElement timeStamp;
@FindBy(id = "io.cambi:id/merchantName")
public WebElement merchantName;
@FindBy(id = "io.cambi:id/amount")
public WebElement ammount;
@FindBy(xpath = "//android.widget.TextView[@text='1 Pts']")
public WebElement demo;
@FindBy(xpath = "//android.widget.TextView[@text='$50.00']")
public WebElement demo2;
public void verifyTransactionsPage() {
Assert.assertTrue(isElementPresent(transactionsTital), "Transactions Tital is not appearing");
Assert.assertTrue(isElementPresent(transactionsPage), "Transactions page is not appearing");
clickOn(transactionsTital);
clickOn(transactionsPage);
}
public void verifyTransactionsHistory() {
Assert.assertTrue(isElementPresent(timeStamp), "Time Stamp is not appearing");
Assert.assertTrue(isElementPresent(merchantName), "Merchant Name is not appearing");
Assert.assertTrue(isElementPresent(ammount), "Ammount is not appearing");
}
public void scrollPage() throws InterruptedException {
waitForElement(demo);
// WebElement element = wd.findElement(By.id(“searchInputField”));
// element.sendKeys(“S”);
int x = demo.getLocation().getX();
int y = demo2.getLocation().getY();
System.out.println("X value: “+x+” Y value: "+y);
Thread.sleep(2000);
TouchAction action = new TouchAction((PerformsTouchActions) driver).tap(x+60, y+260).release();
action.perform();
//If need to enter few more data in to text field, again send it by using sendKeys method and perform the action
//element.sendKeys(“S”);
Thread.sleep(2000);
action.perform();
}
}
|
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/role")
public class RoleController {
@Value("${server.port}")
String port;
private Msg msg = new Msg();
@RequestMapping("/getRole")
public Msg getUser(String roleId){
Role role = new Role();
if(roleId!=null) {
role.setRole_id(roleId);
role.setRole_name("总经理");
role.setRights("9999999999999999999");
role.setRemark("port:"+port);
}
msg.setObj(role);
return msg;
}
}
|
/**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.app.ui;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.event.logical.shared.BeforeSelectionEvent;
import com.google.gwt.event.logical.shared.BeforeSelectionHandler;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.Frame;
import com.sencha.gxt.core.client.GXT;
import com.sencha.gxt.core.client.Style.SelectionMode;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.data.shared.IconProvider;
import com.sencha.gxt.data.shared.TreeStore;
import com.sencha.gxt.examples.resources.client.Utils.Theme;
import com.sencha.gxt.examples.resources.client.images.ExampleImages;
import com.sencha.gxt.explorer.client.app.ui.Page.SourceProperties;
import com.sencha.gxt.explorer.client.model.Example;
import com.sencha.gxt.explorer.client.model.Source;
import com.sencha.gxt.explorer.client.model.Source.FileType;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer.BorderLayoutData;
import com.sencha.gxt.widget.core.client.container.MarginData;
import com.sencha.gxt.widget.core.client.container.SimpleContainer;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent.SelectionChangedHandler;
import com.sencha.gxt.widget.core.client.tree.Tree;
public class SourceContainer extends SimpleContainer {
private final Example example;
public SourceContainer(Example example) {
super();
this.example = example;
}
@Override
protected void onShow() {
super.onShow();
// lazy initialize the subcontainer only when shown
if (getWidgetCount() == 0) {
final ContentPanel sourcePanel = new ContentPanel();
sourcePanel.setBodyStyleName("explorer-example-code");
if (GXT.isTouch()) {
sourcePanel.getElement().getStyle().setOverflow(Overflow.SCROLL);
} else {
sourcePanel.getElement().getStyle().setOverflow(Overflow.VISIBLE);
}
final Frame f = new Frame();
MarginData centerData = new MarginData();
centerData.setMargins(Theme.BLUE.isActive() || Theme.GRAY.isActive() ? new Margins(5) : Theme.NEPTUNE.isActive() ? new Margins(0, 0, 0, 8) : new Margins(10));
sourcePanel.setHeading("Source Code");
sourcePanel.add(f);
ContentPanel west = new ContentPanel();
west.addStyleName("explorer-example-files");
BorderLayoutData westData = new BorderLayoutData(300);
westData.setMargins(Theme.BLUE.isActive() || Theme.GRAY.isActive() ? new Margins(5, 0, 5, 5) : Theme.NEPTUNE.isActive() ? new Margins(0) : new Margins(10, 0, 10, 0));
westData.setCollapseHeaderVisible(true);
westData.setCollapsible(true);
west.setHeading("Select File");
SourceProperties sourceProperties = GWT.create(SourceProperties.class);
final TreeStore<Source> sources = new TreeStore<Source>(sourceProperties.key());
sources.addSubTree(0, example.getSources());
Tree<Source, String> tree = new Tree<Source, String>(sources, sourceProperties.nameLabel()) {
@Override
protected void onAfterFirstAttach() {
super.onAfterFirstAttach();
Source item = example.getSources().get(0).getChildren().get(0);
getSelectionModel().select(item, false);
}
};
tree.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
tree.getSelectionModel().addBeforeSelectionHandler(new BeforeSelectionHandler<Source>() {
@Override
public void onBeforeSelection(BeforeSelectionEvent<Source> event) {
Source m = event.getItem();
if (m.getType() == FileType.FOLDER) {
event.cancel();
}
}
});
tree.getSelectionModel().addSelectionChangedHandler(new SelectionChangedHandler<Source>() {
@Override
public void onSelectionChanged(SelectionChangedEvent<Source> event) {
List<Source> sels = event.getSelection();
if (sels.size() > 0) {
Source m = sels.get(0);
if (m.getType() != FileType.FOLDER) {
sourcePanel.setHeading(m.getName());
f.setUrl(m.getUrl());
}
}
}
});
tree.setIconProvider(new IconProvider<Source>() {
@Override
public ImageResource getIcon(Source model) {
switch (model.getType()) {
case CSS:
return ExampleImages.INSTANCE.css();
case XML:
return ExampleImages.INSTANCE.xml();
case JSON:
return ExampleImages.INSTANCE.json();
case FOLDER:
return ExampleImages.INSTANCE.folder();
case HTML:
return ExampleImages.INSTANCE.html();
case JAVA:
default:
return ExampleImages.INSTANCE.java();
}
}
});
tree.setAutoExpand(true);
west.add(tree);
BorderLayoutContainer subcontainer = new BorderLayoutContainer();
subcontainer.addStyleName("explorer-example-source");
subcontainer.setWestWidget(west, westData);
subcontainer.setCenterWidget(sourcePanel, centerData);
add(subcontainer);
}
}
}
|
public class ServiceFinder extends Service {
public ServiceFinder() {
}
public ServiceFinder(Person person) {
super(person);
}
Person find(String name) {
// поиск по БД
return new Person(1, "John");
}
public void add(Person person) {
// проверки
person.addFriend(person);
}
}
|
package com.github.dongchan.scheduler.dao;
import com.github.dongchan.scheduler.task.Execution;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
/**
* @author DongChan
* @date 2020/10/22
* @time 11:51 PM
*/
public interface TaskRepository {
boolean createIfNotExists(Execution execution);
List<Execution> getDue(Instant now, int limit);
void getScheduledExecutions(Consumer<Execution> consumer);
void getScheduledExecutions(String taskName, Consumer<Execution> consumer);
void remove(Execution execution);
boolean reschedule(Execution execution, Instant nextExecutionTime, Instant lastSuccess, Instant lastFailure, int consecutiveFailures);
boolean reschedule(Execution execution, Instant nextExecutionTime, Object newData, Instant lastSuccess, Instant lastFailure, int consecutiveFailures);
Optional<Execution> pick(Execution e, Instant timePicked);
List<Execution> getDeadExecutions(Instant olderThan);
void updateHeartbeat(Execution execution, Instant heartbeatTime);
List<Execution> getExecutionsFailingLongerThan(Duration interval);
Optional<Execution> getExecution(String taskName, String taskInstanceId);
int removeExecutions(String taskName);
}
|
package servicesubscriber1;
public class Methods {
public static boolean isDouble(String amount) {
try {
double amountInDoble = Double.parseDouble(amount);
return true;
} catch (Exception e) {
return false;
}
}
public static boolean isInt(String amount) {
try {
int amountInInt = Integer.parseInt(amount);
return true;
} catch (Exception e) {
return false;
}
}
}
|
package com.monkey1024.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
import java.io.File;
/**
* 文件上传
*/
@Controller
public class UploadController {
/**
* 处理单个文件上传
*
* @param photo
* @param session
* @return
* @throws Exception
*/
@RequestMapping("/upload1.do")
public ModelAndView upload1(MultipartFile photo, HttpSession session) throws Exception {
ModelAndView mv = new ModelAndView();
//判断用户是否上传了文件
if (!photo.isEmpty()) {
//获取服务器中文件上传的路径
String path = session.getServletContext().getRealPath("/upload");
//获取文件上传的名称
String fileName = photo.getOriginalFilename();
System.out.println(fileName);
//限制文件上传的类型
if ("image/png".equals(photo.getContentType())) {
File file = new File(path, fileName);
//完成文件上传
photo.transferTo(file);
} else {
mv.addObject("msg", "请选择png格式的图片上传");
mv.setViewName("/upload_fail");
return mv;
}
} else {
mv.addObject("msg", "请上传一张png个的图片");
mv.setViewName("/upload_fail");
return mv;
}
//跳转到成功页面
mv.setViewName("/upload_success");
return mv;
}
/**
* 处理多个文件上传
* @param photos
* @param session
* @return
* @throws Exception
*/
@RequestMapping("/upload2.do")
public ModelAndView upload2(@RequestParam MultipartFile[] photos, HttpSession session) throws Exception{
ModelAndView mv = new ModelAndView();
//获取服务器中文件上传的路径
String path = session.getServletContext().getRealPath("/upload");
//遍历MultipartFile数组
for (MultipartFile photo:photos){
//判断用户是否上传了文件
if (!photo.isEmpty()){
//获取文件上传的名称
String fileName = photo.getOriginalFilename();
System.out.println(fileName);
//限制文件上传的类型
if ("image/png".equals(photo.getContentType())){
File file = new File(path, fileName);
//完成文件上传
photo.transferTo(file);
}else {
mv.addObject("msg", "请选择png格式的图片上传");
mv.setViewName("/upload_fail");
return mv;
}
}else{
mv.addObject("msg", "请上传一张png个的图片");
mv.setViewName("/upload_fail");
return mv;
}
}
//跳转到成功页面
mv.setViewName("/upload_success");
return mv;
}
}
|
package audio;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class AudioManager {
private static Clip clip;
private static String levelSuffix;
private static Set<Clip> clips = new HashSet<Clip>();
public static void play(String value){
try{
InputStream is = new BufferedInputStream(ClassLoader.getSystemResourceAsStream(value + ".wav"));
AudioInputStream myInputStream = AudioSystem.getAudioInputStream(is);
clip=AudioSystem.getClip();
clip.open(myInputStream);
clip.start();
clips.add(clip);
} catch(Exception ex){
System.err.println( ex.getMessage() );
}
}
public static void playForLevel(String value){
String levelValue = value + levelSuffix;
play(levelValue);
}
public static void loop(String value){
try {
InputStream is = new BufferedInputStream(ClassLoader.getSystemResourceAsStream(value + ".wav"));
AudioInputStream myInputStream = AudioSystem.getAudioInputStream(is);
clip = AudioSystem.getClip();
clip.open(myInputStream);
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY);
clips.add(clip);
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
public static void loopForLevel(String value){
String levelValue = value + levelSuffix;
loop(levelValue);
}
public static void stop(){
if(clip == null)
return;
clip.stop();
for(Clip c : clips){
c.stop();
}
}
public static void setLevelSuffix(int levelNumber){
levelSuffix = "_level" + levelNumber;
}
}
|
package java.com.kaizenmax.taikinys_icl.model;
public interface MandiCampaignDataPushNetworkOperationInterface {
public void sendingMcDataToWebService()throws Exception;
}
|
package lab6;
import classesState.EstadoVacinacao;
import classesState.NaoVacinada;
public class Pessoa {
private String nome;
private String cpf;
private String endereco;
private String cartaoSUS;
private String email;
private String telefone;
private String profissao;
private String comorbidade;
private int idade;
private EstadoVacinacao estado;
public Pessoa(String nome, String cpf, String endereco, String cartaoSUS, String email, String telefone,
String profissao, String comorbidade, int idade) {
this.nome = nome;
this.cpf = cpf;
this.endereco = endereco;
this.cartaoSUS = cartaoSUS;
this.email = email;
this.telefone = telefone;
this.profissao = profissao;
this.comorbidade = comorbidade;
this.idade = idade;
this.estado = new NaoVacinada();
}
public void atualizaEstadoVacina(Pessoa pessoa) {
estado.alteraEstado(pessoa);
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getCartaoSUS() {
return cartaoSUS;
}
public void setCartaoSUS(String cartaoSUS) {
this.cartaoSUS = cartaoSUS;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getProfissao() {
return profissao;
}
public void setProfissao(String profissao) {
this.profissao = profissao;
}
public String getComorbidade() {
return comorbidade;
}
public void setComorbidade(String comorbidade) {
this.comorbidade = comorbidade;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getSituacao() {
return estado.toString();
}
public void setEstadoVacinacao(EstadoVacinacao estado) {
this.estado = estado;
}
@Override
public String toString() {
return "Pessoa [nome=" + nome + ", cpf=" + cpf + ", endereco=" + endereco + ", cartaoSUS=" + cartaoSUS
+ ", email=" + email + ", telefone=" + telefone + ", profissao=" + profissao + ", comorbidade="
+ comorbidade + ", idade=" + idade + ", estado=" + estado + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pessoa other = (Pessoa) obj;
if (cpf == null) {
if (other.cpf != null)
return false;
} else if (!cpf.equals(other.cpf))
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cpf == null) ? 0 : cpf.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
return result;
}
}
|
package mySQL;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import controllers.PasswordHasher;
import dao.UserDAO;
import models.User;
public class MySQLUserDAO implements UserDAO {
private final static String SELECT_LOGIN_QUERY = "SELECT * FROM users WHERE login=? ";
private final static String INSERT_QUERY = "INSERT INTO users(login, password, name, region, gender, comment)"
+ " VALUES(?, ?, ?,?,?,?)";
private final static String UPDATE_QUERY="UPDATE users SET login=?,password=?,name=?,region=?,gender=?,comment=? WHERE id=?";
MySQLDAOFactory mySQLDAOFactory = new MySQLDAOFactory();
@Override
public boolean checkUserByLogin(String login) {
User user = null;
ResultSet rs = null;
Connection conn = mySQLDAOFactory.openConnection();
try {
PreparedStatement prepSt;
prepSt = conn.prepareStatement(SELECT_LOGIN_QUERY);
System.out.println("SELECT_LOGIN_QUERY");
prepSt.setString(1, login);
rs = prepSt.executeQuery();
if (rs.next()) {
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
mySQLDAOFactory.closeConnection(conn);
}
return false;
}
@Override
public void insertUser(User user) {
Connection conn = mySQLDAOFactory.openConnection();
PreparedStatement prepSt;
try {
prepSt = conn.prepareStatement(INSERT_QUERY);
prepSt.setString(1, user.getLogin());
prepSt.setString(2, user.getPassword());
prepSt.setString(3, user.getName());
prepSt.setString(4, user.getRegion());
prepSt.setInt(5, user.getGender());
prepSt.setString(6, user.getComment());
prepSt.executeUpdate();
prepSt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
mySQLDAOFactory.closeConnection(conn);
}
}
@SuppressWarnings("null")
@Override
public User getUserByLoginPassword(String login, String password) {
User user = new User();
ResultSet rs = null;
Connection conn = mySQLDAOFactory.openConnection();
try {
PreparedStatement prepSt;
prepSt = conn.prepareStatement(SELECT_LOGIN_QUERY);
prepSt.setString(1, login);
rs = prepSt.executeQuery();
if (rs.next()) {
user.setId(rs.getInt("id"));
user.setLogin(rs.getString("login"));
user.setPassword(rs.getString("password"));
user.setName(rs.getString("name"));
user.setRegion(rs.getString("region"));
user.setGender(rs.getInt("gender"));
user.setComment(rs.getString("comment"));
if (user.getPassword().equals(new PasswordHasher().hash(password))) {
return user;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
mySQLDAOFactory.closeConnection(conn);
}
return null;
}
@Override
public void updateUser(User user) {
Connection conn = mySQLDAOFactory.openConnection();
try
{
// create our java preparedstatement using a sql update query
PreparedStatement ps = conn.prepareStatement(UPDATE_QUERY);
System.out.println("Up1");
// set the preparedstatement parameters
ps.setString(1,user.getLogin());
ps.setString(2,user.getPassword());
ps.setString(3,user.getName());
ps.setString(4,user.getRegion());
ps.setInt(5, user.getGender());
ps.setString(6,user.getComment());
ps.setLong(7, user.getId());
System.out.println("Up2");
// call executeUpdate to execute our sql update statement
ps.executeUpdate();
ps.close();
}
catch (SQLException se)
{
// log the exception
se.printStackTrace();
}
}
}
|
package com.test.gpstracker;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.rey.material.widget.Button;
import model.HeartBeatRequestBody;
import model.HeartBeatResponse;
import receiver.NotifReceiver;
import receiver.ReminderReceiver;
import restOptions.ServiceHelper;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import utils.GeneralHelper;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks {
private static final int RECEIVER_REQUEST_CODE = 123;
public static final String NOTIF_INTENT_KEY = "notif_intent";
public static final String NOTIF_OPEN = "open";
public static final String NOTIF_DISMISS = "dismiss";
public static final int NOTIF_ID = 102;
private static final String RECEIVER_ACTION = "action";
private GoogleMap mMap;
private AlarmManager am;
private Button logOut;
private GoogleApiClient googleApiClient;
private double longitude;
private double latitude;
private Runnable runnable;
private Handler handler = new Handler();
private ServiceHelper serviceHelper = new ServiceHelper();
private int oneSecond = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
GeneralHelper.setStatusBarColor(this, R.color.status_color);
checkGpsConnection();
initialParams();
itemClickListener();
}
private void checkGpsConnection() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(MapsActivity.this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
//**************************
builder.setAlwaysShow(true); //this is the key ingredient
//**************************
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
getCurrentLocation();
sendDataToServerInApp();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
MapsActivity.this, 1000);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
}
private void itemClickListener() {
logOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//cancel service
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent amintent = new Intent();
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), RECEIVER_REQUEST_CODE, amintent, PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pi);
//save login situation
SharedPreferences.Editor editor = getSharedPreferences(LoginActivity.LOGIN_STATUS, 0).edit();
editor.putBoolean(LoginActivity.LOGIN_KEY, false);
editor.apply();
Intent intent = new Intent(MapsActivity.this, LoginActivity.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
}
});
}
private void initialParams() {
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
logOut = (Button) findViewById(R.id.logOut);
runnable = new Runnable() {
@Override
public void run() {
getCurrentLocation();
serviceHelper.createAdapter();
final HeartBeatRequestBody heartBeatRequestBody = new HeartBeatRequestBody();
heartBeatRequestBody.setLat(latitude);
heartBeatRequestBody.setLng(longitude);
serviceHelper.setHeartBeat(heartBeatRequestBody, new Callback<HeartBeatResponse>() {
@Override
public void success(HeartBeatResponse heartBeatResponse, Response response) {
// Toast.makeText(MapsActivity.this, heartBeatResponse.getStatus()
// + " " + heartBeatRequestBody.getLat() + " " + heartBeatRequestBody.getLng()
// , Toast.LENGTH_LONG).show();
}
@Override
public void failure(RetrofitError error) {
}
});
sendDataToServerInApp();
}
};
}
@Override
public void onMapReady(GoogleMap googleMap) {
try {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
Toast.makeText(MapsActivity.this,"lat= "+ latitude
+ "lng= " + longitude
, Toast.LENGTH_LONG).show();
latitude=location.getLatitude();
longitude=location.getLongitude();
moveMap();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendDataToServerInApp() {
handler.postDelayed(runnable, 10000);
}
private void sendLocationToServer() {
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MapsActivity.this, ReminderReceiver.class);
intent.setAction(RECEIVER_ACTION);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), RECEIVER_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pi);
if (Build.VERSION.SDK_INT >= 19) {
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 10 * oneSecond, pi);
} else {
am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 10 * oneSecond, pi);
}
}
private void getCurrentLocation() {
mMap.clear();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
}
private void moveMap() {
LatLng latLng = new LatLng(latitude, longitude);
// mMap.addMarker(new MarkerOptions()
// .position(latLng)
// .draggable(true)
// .title("Marker in your position"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
private void makeNotif(Context context) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_big);
remoteViews.setTextViewText(R.id.notifLat, "lat= " + latitude);
remoteViews.setTextViewText(R.id.notifLng, "lng= " + longitude);
Intent intent = new Intent(context, NotifReceiver.class);
intent.putExtra(NOTIF_INTENT_KEY, NOTIF_OPEN);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
20, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.open, pendingIntent);
Intent intentm = new Intent(context, NotifReceiver.class);
intentm.putExtra(NOTIF_INTENT_KEY, NOTIF_DISMISS);
PendingIntent pendingIntentm = PendingIntent.getBroadcast(context,
22, intentm, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.dismiss, pendingIntentm);
Notification notification = new NotificationCompat.Builder(context)
.setContent(remoteViews)
.setCustomBigContentView(remoteViews)
// .setContentIntent(pendingIntent)
.setCustomHeadsUpContentView(remoteViews)
// .setCategory(Notification.CATEGORY_MESSAGE)
.setPriority(Notification.PRIORITY_MAX)
// .addAction(R.id.open,"op",pendingIntent)
// .addAction(R.id.close,"cl",pendingIntentm)
.setFullScreenIntent(pendingIntentm, true)
.setOngoing(false)
.setAutoCancel(false)
.setTicker("Location changed")
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIF_ID, notification);
}
@Override
protected void onPause() {
super.onPause();
if (runnable != null) {
handler.removeCallbacks(runnable);
sendLocationToServer();
}
Log.d("sajad","pause");
}
@Override
protected void onStop() {
super.onStop();
if (runnable != null) {
handler.removeCallbacks(runnable);
// sendLocationToServer();
}
Log.d("sajad","stop");
}
@Override
protected void onResume() {
super.onResume();
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent();
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), RECEIVER_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pi);
// sendDataToServerInApp();
Log.d("sajad","resume");
}
@Override
public void onConnected(@Nullable Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
}
|
package coordinate;
import java.awt.Rectangle;
public class Coordinate {
public static float X_MIN = -1f, X_MAX = 1f,
Y_MIN = -1f, Y_MAX = 1f,
Z_MIN = 1f, Z_MAX = 4f;
public static float CLOSE_BOUNDS = 0.3f;
float x, y, z;
public Coordinate(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public static boolean isWithBound(Coordinate c1, Coordinate c2) {
System.out.println(c1.getDistanceBetween(c2));
return c1.getDistanceBetween(c2) < CLOSE_BOUNDS;
}
public static Coordinate getAverage(Coordinate c1, Coordinate c2) {
float xx = (c1.x + c2.x) / 2;
float yy = (c1.y + c2.y) / 2;
float zz = (c1.z + c2.z) / 2;
return new Coordinate(xx, yy, zz);
}
public static int getX(float x, Rectangle bounds) {
x = (x - Coordinate.X_MIN) / 2;
return (int) Math.round(x * bounds.getWidth());
}
public static int getY(float y, Rectangle bounds) {
y = (y - Coordinate.Y_MIN) / 2;
return (int) Math.round(y * bounds.getHeight());
}
public float getDistanceBetween(Coordinate other) {
float dX = x - other.x;
float dY = y - other.y;
float dZ = z - other.z;
return (float) Math.sqrt(dX * dX + dY * dY + dZ * dZ);
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public float getZ() {
return z;
}
public void setZ(float z) {
this.z = z;
}
}
|
package com.conexion;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class Conexion {
public static Connection obtenerConexion() {
Connection cn = null;
try {
// String host = "127.7.165.2";
// String port = "3306";
// String url = String.format("jdbc:mysql://%s:%s/cochera_lp4", host, port);
//cargar driver
// Class.forName("com.mysql.jdbc.Driver"); // ESTE codigo jala del JAR.... es una clase con nombre "com.mysql...." ya esta definido
//conectar BD //la puerta de sql/nameBD/usuario, contrase�a
// cn = DriverManager.getConnection(url);
// cn = DriverManager.getConnection("https://aulafree-origenjuglar.rhcloud.com/phpmyadmin/cochera_lp4", "admin4i94wLB", "3KE8mpVN6LZU");//en el tuyo debe ser "" quizas
Class.forName("com.mysql.jdbc.Driver"); // ESTE codigo jala del JAR.... es una clase con nombre "com.mysql...." ya esta definido
//conectar BD //la puerta de sql/nameBD/usuario, contraseña
cn = DriverManager.getConnection("jdbc:mysql://127.7.165.2:3306/cochera_lp4", "admin4i94wLB", "3KE8mpVN6LZU");//en el tuyo debe ser "" quizas }
// cn = DriverManager.getConnection("jdbc:mysql://localhost/cochera_lp4", "root", "mysql");//en el tuyo debe ser "" quizas
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Usuario No Conectado a la base de Datoss");
}
return cn;
}
}
|
package com.huruilei.designpattern.decoratee;
/**
* @author: huruilei
* @date: 2019/11/5
* @description:
* @return
*/
public abstract class CondimentDecorator extends Beverage {
public abstract String getDescription();
}
|
package cn.kitho.web.controller.textRecording;
import cn.kitho.core.config.DetailTypes;
import cn.kitho.core.config.StatusType;
import cn.kitho.core.config.SystemConfig;
import cn.kitho.core.model.Types;
import cn.kitho.core.service.base.TypesService;
import cn.kitho.web.dto.base.BaseResult;
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by lingkitho on 16/11/26.
*/
@Controller
@RequestMapping("/types")
public class TypesController {
@InitBinder("data")
public void initBinder(WebDataBinder binder) {
binder.setFieldDefaultPrefix("data.");
}
@Resource
TypesService typesService;
@RequestMapping("/go")
public ModelAndView go(HttpServletRequest request, HttpServletResponse response){
ModelAndView modelAndView = new ModelAndView("/userModel/types");
Map<Integer,String> detail = DetailTypes.convertToMap();
detail.remove(DetailTypes.MAIN_PAGE_SAY_HI.getStatusIndex());//去掉首页招呼语
modelAndView.addObject("detail", detail);
modelAndView.addObject("lang", SystemConfig.LANGUAGE);
List<Types> sayHi = typesService.showArticleTypes(DetailTypes.MAIN_PAGE_SAY_HI);
if(null != sayHi && sayHi.size()>0) {
modelAndView.addObject("sayHi", sayHi.get(0));
}
return modelAndView;
}
/**
* 查询类型列表
* @param request
* @param response
* @return
*/
@RequestMapping("/select")
@ResponseBody
public BaseResult select(HttpServletRequest request, HttpServletResponse response){
return null;
}
/**
* 去添加
* @param request
* @param response
* @return
*/
@RequestMapping("/add")
@ResponseBody
public BaseResult add(@ModelAttribute("data") Types data,
HttpServletRequest request, HttpServletResponse response){
BaseResult result = new BaseResult(false);//返回结果
data.setLangNames(JSON.toJSONString(getLangMapsFromRequest(request)));
Types typeParam;
try {
typeParam = (Types) BeanUtils.cloneBean(data);
typeParam.setStatus(StatusType.AVALID.getStatusIndex());//初始状态为启用
boolean success = typesService.insertSelective(typeParam)>0;
result.setSuccess(success);
} catch (Exception e) {
}
return result;
}
/**
* 去编辑
* @param request
* @param response
* @return
*/
@RequestMapping("/modify")
public BaseResult modify(HttpServletRequest request, HttpServletResponse response){
return null;
}
/**
* 删除
* @param request
* @param response
* @return
*/
@RequestMapping("/delete")
@ResponseBody
public BaseResult delete(HttpServletRequest request, HttpServletResponse response){
return null;
}
/**
* 首页招呼语类型管理
* @param request
* @param response
* @return
*/
@RequestMapping("/sayHi")
@ResponseBody
public BaseResult sayHi(@ModelAttribute("data") Types data,
HttpServletRequest request, HttpServletResponse response){
BaseResult result = new BaseResult(false);//返回结果
data.setLangNames(JSON.toJSONString(getLangMapsFromRequest(request)));
Types typeParam;
try {
typeParam = (Types) BeanUtils.cloneBean(data);
boolean success;
if(null == typeParam.getId()) {//如果不存在,则新增
List<Types> temp = typesService.showArticleTypes(DetailTypes.MAIN_PAGE_SAY_HI);//获得招呼语的记录
if(null == temp || temp.size() <= 0) {
typeParam.setTypeId(DetailTypes.MAIN_PAGE_SAY_HI.getStatusIndex());//首页招呼语类型
typeParam.setStatus(StatusType.AVALID.getStatusIndex());//初始状态为启用
success = typesService.insertSelective(typeParam) > 0;
}else{
typeParam.setId(temp.get(0).getId());
success = typesService.updateByPrimaryKeySelective(typeParam) >= 0;//否则更新
}
}else {
success = typesService.updateByPrimaryKeySelective(typeParam) >= 0;//否则更新
}
result.setSuccess(success);
} catch (Exception e) {
}
return result;
}
/**
* 从请求中获取语言的map集合
* @param request
* @return
*/
Map<Integer,String> getLangMapsFromRequest(HttpServletRequest request){
Map<Integer,String> langMap = new HashMap<>();
for(Integer i : SystemConfig.LANGUAGE.keySet()){//获得语言
String str = request.getParameter("lang"+i);
langMap.put(i,str);
}
return langMap;
}
}
|
package com.tvm.arrayExample;
/**
*
* This method removes all negative integer from Array except first one.
*
*/
public class RemoveFirstNegative {
public static void main(String[] args) {
int[] array = new int[] { 10, 1, -3, 2, -4, -5, -6, 7 };
int newArrays[] = new int[10];
int j = 0;
boolean firstNegative = true;
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
if (firstNegative == true) {
newArrays[j] = array[i];
j++;
firstNegative = false;
}
} else {
newArrays[j] = array[i];
j++;
}
}
for (int i = 0; i < newArrays.length; i++) {
System.out.println(newArrays[i]);
}
}
}
|
package de.gaudian.webcrawler;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class ExcelWriter {
private static final String FILE_NAME = "C:\\GitRepository\\WebCrawler\\myJSoup\\Spendenorganisationen.xlsx";
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private int rowNum;
private int colNum;
public ExcelWriter() {
workbook = new XSSFWorkbook();
rowNum = 0;
colNum = 0;
}
public void writeHeader() {
System.out.println("Creating excel");
sheet = workbook.createSheet("Spendenorganisationen");
String[] datatype = {
"source", "iban", "bic", "company_name", "street", "zip_code", "city", "homepage", "telephone", "fax", "email", "legal_form", "category"
};
writeInRow(datatype);
}
public void writeAndClose() {
try {
FileOutputStream outputStream = new FileOutputStream(FILE_NAME, false);
workbook.write(outputStream);
workbook.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
public void writeSpendenInfo(List<SpendenInfos> spendenInfos) {
String[] datatype = new String[13];
for (SpendenInfos spendenInfo : spendenInfos) {
datatype[0] = spendenInfo.getSource();
datatype[1] = spendenInfo.getIban();
datatype[2] = spendenInfo.getBic();
datatype[3] = spendenInfo.getCompany_name();
datatype[4] = spendenInfo.getStreet();
datatype[5] = spendenInfo.getZip_code();
datatype[6] = spendenInfo.getCity();
datatype[7] = spendenInfo.getHomepage();
datatype[8] = spendenInfo.getTelephone();
datatype[9] = spendenInfo.getFax();
datatype[10] = spendenInfo.getEmail();
datatype[11] = spendenInfo.getLegal_form();
datatype[12] = spendenInfo.getCategory();
writeInRow(datatype);
}
}
private void writeInRow(String[] datatype) {
Row row = sheet.createRow(rowNum++);
for (String field : datatype) {
Cell cell = row.createCell(colNum++);
cell.setCellValue(field);
}
colNum = 0;
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.annotation.MergedAnnotation.Adapt;
import org.springframework.core.annotation.MergedAnnotations.SearchStrategy;
import org.springframework.lang.Nullable;
import org.springframework.util.MultiValueMap;
/**
* General utility methods for finding annotations, meta-annotations, and
* repeatable annotations on {@link AnnotatedElement AnnotatedElements}.
*
* <p>{@code AnnotatedElementUtils} defines the public API for Spring's
* meta-annotation programming model with support for <em>annotation attribute
* overrides</em>. If you do not need support for annotation attribute
* overrides, consider using {@link AnnotationUtils} instead.
*
* <p>Note that the features of this class are not provided by the JDK's
* introspection facilities themselves.
*
* <h3>Annotation Attribute Overrides</h3>
* <p>Support for meta-annotations with <em>attribute overrides</em> in
* <em>composed annotations</em> is provided by all variants of the
* {@code getMergedAnnotationAttributes()}, {@code getMergedAnnotation()},
* {@code getAllMergedAnnotations()}, {@code getMergedRepeatableAnnotations()},
* {@code findMergedAnnotationAttributes()}, {@code findMergedAnnotation()},
* {@code findAllMergedAnnotations()}, and {@code findMergedRepeatableAnnotations()}
* methods.
*
* <h3>Find vs. Get Semantics</h3>
* <p>The search algorithms used by methods in this class follow either
* <em>find</em> or <em>get</em> semantics. Consult the javadocs for each
* individual method for details on which search algorithm is used.
*
* <p><strong>Get semantics</strong> are limited to searching for annotations
* that are either <em>present</em> on an {@code AnnotatedElement} (i.e. declared
* locally or {@linkplain java.lang.annotation.Inherited inherited}) or declared
* within the annotation hierarchy <em>above</em> the {@code AnnotatedElement}.
*
* <p><strong>Find semantics</strong> are much more exhaustive, providing
* <em>get semantics</em> plus support for the following:
*
* <ul>
* <li>Searching on interfaces, if the annotated element is a class
* <li>Searching on superclasses, if the annotated element is a class
* <li>Resolving bridged methods, if the annotated element is a method
* <li>Searching on methods in interfaces, if the annotated element is a method
* <li>Searching on methods in superclasses, if the annotated element is a method
* </ul>
*
* <h3>Support for {@code @Inherited}</h3>
* <p>Methods following <em>get semantics</em> will honor the contract of Java's
* {@link java.lang.annotation.Inherited @Inherited} annotation except that locally
* declared annotations (including custom composed annotations) will be favored over
* inherited annotations. In contrast, methods following <em>find semantics</em>
* will completely ignore the presence of {@code @Inherited} since the <em>find</em>
* search algorithm manually traverses type and method hierarchies and thereby
* implicitly supports annotation inheritance without a need for {@code @Inherited}.
*
* @author Phillip Webb
* @author Juergen Hoeller
* @author Sam Brannen
* @since 4.0
* @see AliasFor
* @see AnnotationAttributes
* @see AnnotationUtils
* @see BridgeMethodResolver
*/
public abstract class AnnotatedElementUtils {
/**
* Build an adapted {@link AnnotatedElement} for the given annotations,
* typically for use with other methods on {@link AnnotatedElementUtils}.
* @param annotations the annotations to expose through the {@code AnnotatedElement}
* @since 4.3
*/
public static AnnotatedElement forAnnotations(Annotation... annotations) {
return new AnnotatedElementForAnnotations(annotations);
}
/**
* Get the fully qualified class names of all meta-annotation types
* <em>present</em> on the annotation (of the specified {@code annotationType})
* on the supplied {@link AnnotatedElement}.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationType the annotation type on which to find meta-annotations
* @return the names of all meta-annotations present on the annotation,
* or an empty set if not found
* @since 4.2
* @see #getMetaAnnotationTypes(AnnotatedElement, String)
* @see #hasMetaAnnotationTypes
*/
public static Set<String> getMetaAnnotationTypes(AnnotatedElement element,
Class<? extends Annotation> annotationType) {
return getMetaAnnotationTypes(element, element.getAnnotation(annotationType));
}
/**
* Get the fully qualified class names of all meta-annotation
* types <em>present</em> on the annotation (of the specified
* {@code annotationName}) on the supplied {@link AnnotatedElement}.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationName the fully qualified class name of the annotation
* type on which to find meta-annotations
* @return the names of all meta-annotations present on the annotation,
* or an empty set if none found
* @see #getMetaAnnotationTypes(AnnotatedElement, Class)
* @see #hasMetaAnnotationTypes
*/
public static Set<String> getMetaAnnotationTypes(AnnotatedElement element, String annotationName) {
for (Annotation annotation : element.getAnnotations()) {
if (annotation.annotationType().getName().equals(annotationName)) {
return getMetaAnnotationTypes(element, annotation);
}
}
return Collections.emptySet();
}
private static Set<String> getMetaAnnotationTypes(AnnotatedElement element, @Nullable Annotation annotation) {
if (annotation == null) {
return Collections.emptySet();
}
return getAnnotations(annotation.annotationType()).stream()
.map(mergedAnnotation -> mergedAnnotation.getType().getName())
.collect(Collectors.toCollection(LinkedHashSet::new));
}
/**
* Determine if the supplied {@link AnnotatedElement} is annotated with
* a <em>composed annotation</em> that is meta-annotated with an
* annotation of the specified {@code annotationType}.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationType the meta-annotation type to find
* @return {@code true} if a matching meta-annotation is present
* @since 4.2.3
* @see #getMetaAnnotationTypes
*/
public static boolean hasMetaAnnotationTypes(AnnotatedElement element, Class<? extends Annotation> annotationType) {
return getAnnotations(element).stream(annotationType).anyMatch(MergedAnnotation::isMetaPresent);
}
/**
* Determine if the supplied {@link AnnotatedElement} is annotated with a
* <em>composed annotation</em> that is meta-annotated with an annotation
* of the specified {@code annotationName}.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationName the fully qualified class name of the
* meta-annotation type to find
* @return {@code true} if a matching meta-annotation is present
* @see #getMetaAnnotationTypes
*/
public static boolean hasMetaAnnotationTypes(AnnotatedElement element, String annotationName) {
return getAnnotations(element).stream(annotationName).anyMatch(MergedAnnotation::isMetaPresent);
}
/**
* Determine if an annotation of the specified {@code annotationType}
* is <em>present</em> on the supplied {@link AnnotatedElement} or
* within the annotation hierarchy <em>above</em> the specified element.
* <p>If this method returns {@code true}, then {@link #getMergedAnnotationAttributes}
* will return a non-null value.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationType the annotation type to find
* @return {@code true} if a matching annotation is present
* @since 4.2.3
* @see #hasAnnotation(AnnotatedElement, Class)
*/
public static boolean isAnnotated(AnnotatedElement element, Class<? extends Annotation> annotationType) {
// Shortcut: directly present on the element, with no merging needed?
if (AnnotationFilter.PLAIN.matches(annotationType) ||
AnnotationsScanner.hasPlainJavaAnnotationsOnly(element)) {
return element.isAnnotationPresent(annotationType);
}
// Exhaustive retrieval of merged annotations...
return getAnnotations(element).isPresent(annotationType);
}
/**
* Determine if an annotation of the specified {@code annotationName} is
* <em>present</em> on the supplied {@link AnnotatedElement} or within the
* annotation hierarchy <em>above</em> the specified element.
* <p>If this method returns {@code true}, then {@link #getMergedAnnotationAttributes}
* will return a non-null value.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationName the fully qualified class name of the annotation type to find
* @return {@code true} if a matching annotation is present
*/
public static boolean isAnnotated(AnnotatedElement element, String annotationName) {
return getAnnotations(element).isPresent(annotationName);
}
/**
* Get the first annotation of the specified {@code annotationType} within
* the annotation hierarchy <em>above</em> the supplied {@code element} and
* merge that annotation's attributes with <em>matching</em> attributes from
* annotations in lower levels of the annotation hierarchy.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both
* within a single annotation and within the annotation hierarchy.
* <p>This method delegates to {@link #getMergedAnnotationAttributes(AnnotatedElement, String)}.
* @param element the annotated element
* @param annotationType the annotation type to find
* @return the merged {@code AnnotationAttributes}, or {@code null} if not found
* @since 4.2
* @see #getMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)
* @see #findMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)
* @see #getMergedAnnotation(AnnotatedElement, Class)
* @see #findMergedAnnotation(AnnotatedElement, Class)
*/
@Nullable
public static AnnotationAttributes getMergedAnnotationAttributes(
AnnotatedElement element, Class<? extends Annotation> annotationType) {
MergedAnnotation<?> mergedAnnotation = getAnnotations(element)
.get(annotationType, null, MergedAnnotationSelectors.firstDirectlyDeclared());
return getAnnotationAttributes(mergedAnnotation, false, false);
}
/**
* Get the first annotation of the specified {@code annotationName} within
* the annotation hierarchy <em>above</em> the supplied {@code element} and
* merge that annotation's attributes with <em>matching</em> attributes from
* annotations in lower levels of the annotation hierarchy.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both
* within a single annotation and within the annotation hierarchy.
* <p>This method delegates to {@link #getMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)},
* supplying {@code false} for {@code classValuesAsString} and {@code nestedAnnotationsAsMap}.
* @param element the annotated element
* @param annotationName the fully qualified class name of the annotation type to find
* @return the merged {@code AnnotationAttributes}, or {@code null} if not found
* @since 4.2
* @see #getMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)
* @see #findMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)
* @see #findMergedAnnotation(AnnotatedElement, Class)
* @see #getAllAnnotationAttributes(AnnotatedElement, String)
*/
@Nullable
public static AnnotationAttributes getMergedAnnotationAttributes(AnnotatedElement element,
String annotationName) {
return getMergedAnnotationAttributes(element, annotationName, false, false);
}
/**
* Get the first annotation of the specified {@code annotationName} within
* the annotation hierarchy <em>above</em> the supplied {@code element} and
* merge that annotation's attributes with <em>matching</em> attributes from
* annotations in lower levels of the annotation hierarchy.
* <p>Attributes from lower levels in the annotation hierarchy override attributes
* of the same name from higher levels, and {@link AliasFor @AliasFor} semantics are
* fully supported, both within a single annotation and within the annotation hierarchy.
* <p>In contrast to {@link #getAllAnnotationAttributes}, the search algorithm used by
* this method will stop searching the annotation hierarchy once the first annotation
* of the specified {@code annotationName} has been found. As a consequence,
* additional annotations of the specified {@code annotationName} will be ignored.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationName the fully qualified class name of the annotation type to find
* @param classValuesAsString whether to convert Class references into Strings or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to convert nested Annotation instances
* into {@code AnnotationAttributes} maps or to preserve them as Annotation instances
* @return the merged {@code AnnotationAttributes}, or {@code null} if not found
* @since 4.2
* @see #findMergedAnnotation(AnnotatedElement, Class)
* @see #findMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)
* @see #getAllAnnotationAttributes(AnnotatedElement, String, boolean, boolean)
*/
@Nullable
public static AnnotationAttributes getMergedAnnotationAttributes(AnnotatedElement element,
String annotationName, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
MergedAnnotation<?> mergedAnnotation = getAnnotations(element)
.get(annotationName, null, MergedAnnotationSelectors.firstDirectlyDeclared());
return getAnnotationAttributes(mergedAnnotation, classValuesAsString, nestedAnnotationsAsMap);
}
/**
* Get the first annotation of the specified {@code annotationType} within
* the annotation hierarchy <em>above</em> the supplied {@code element},
* merge that annotation's attributes with <em>matching</em> attributes from
* annotations in lower levels of the annotation hierarchy, and synthesize
* the result back into an annotation of the specified {@code annotationType}.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both
* within a single annotation and within the annotation hierarchy.
* @param element the annotated element
* @param annotationType the annotation type to find
* @return the merged, synthesized {@code Annotation}, or {@code null} if not found
* @since 4.2
* @see #findMergedAnnotation(AnnotatedElement, Class)
*/
@Nullable
public static <A extends Annotation> A getMergedAnnotation(AnnotatedElement element, Class<A> annotationType) {
// Shortcut: directly present on the element, with no merging needed?
if (AnnotationFilter.PLAIN.matches(annotationType) ||
AnnotationsScanner.hasPlainJavaAnnotationsOnly(element)) {
return element.getDeclaredAnnotation(annotationType);
}
// Exhaustive retrieval of merged annotations...
return getAnnotations(element)
.get(annotationType, null, MergedAnnotationSelectors.firstDirectlyDeclared())
.synthesize(MergedAnnotation::isPresent).orElse(null);
}
/**
* Get <strong>all</strong> annotations of the specified {@code annotationType}
* within the annotation hierarchy <em>above</em> the supplied {@code element};
* and for each annotation found, merge that annotation's attributes with
* <em>matching</em> attributes from annotations in lower levels of the annotation
* hierarchy and synthesize the results back into an annotation of the specified
* {@code annotationType}.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both within a
* single annotation and within annotation hierarchies.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element (never {@code null})
* @param annotationType the annotation type to find (never {@code null})
* @return the set of all merged, synthesized {@code Annotations} found,
* or an empty set if none were found
* @since 4.3
* @see #getMergedAnnotation(AnnotatedElement, Class)
* @see #getAllAnnotationAttributes(AnnotatedElement, String)
* @see #findAllMergedAnnotations(AnnotatedElement, Class)
*/
public static <A extends Annotation> Set<A> getAllMergedAnnotations(
AnnotatedElement element, Class<A> annotationType) {
return getAnnotations(element).stream(annotationType)
.collect(MergedAnnotationCollectors.toAnnotationSet());
}
/**
* Get <strong>all</strong> annotations of the specified {@code annotationTypes}
* within the annotation hierarchy <em>above</em> the supplied {@code element};
* and for each annotation found, merge that annotation's attributes with
* <em>matching</em> attributes from annotations in lower levels of the
* annotation hierarchy and synthesize the results back into an annotation
* of the corresponding {@code annotationType}.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both within a
* single annotation and within annotation hierarchies.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element (never {@code null})
* @param annotationTypes the annotation types to find
* @return the set of all merged, synthesized {@code Annotations} found,
* or an empty set if none were found
* @since 5.1
* @see #getAllMergedAnnotations(AnnotatedElement, Class)
*/
public static Set<Annotation> getAllMergedAnnotations(AnnotatedElement element,
Set<Class<? extends Annotation>> annotationTypes) {
return getAnnotations(element).stream()
.filter(MergedAnnotationPredicates.typeIn(annotationTypes))
.collect(MergedAnnotationCollectors.toAnnotationSet());
}
/**
* Get all <em>repeatable annotations</em> of the specified {@code annotationType}
* within the annotation hierarchy <em>above</em> the supplied {@code element};
* and for each annotation found, merge that annotation's attributes with
* <em>matching</em> attributes from annotations in lower levels of the annotation
* hierarchy and synthesize the results back into an annotation of the specified
* {@code annotationType}.
* <p>The container type that holds the repeatable annotations will be looked up
* via {@link java.lang.annotation.Repeatable}.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both within a
* single annotation and within annotation hierarchies.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element (never {@code null})
* @param annotationType the annotation type to find (never {@code null})
* @return the set of all merged repeatable {@code Annotations} found,
* or an empty set if none were found
* @throws IllegalArgumentException if the {@code element} or {@code annotationType}
* is {@code null}, or if the container type cannot be resolved
* @since 4.3
* @see #getMergedAnnotation(AnnotatedElement, Class)
* @see #getAllMergedAnnotations(AnnotatedElement, Class)
* @see #getMergedRepeatableAnnotations(AnnotatedElement, Class, Class)
*/
public static <A extends Annotation> Set<A> getMergedRepeatableAnnotations(
AnnotatedElement element, Class<A> annotationType) {
return getMergedRepeatableAnnotations(element, annotationType, null);
}
/**
* Get all <em>repeatable annotations</em> of the specified {@code annotationType}
* within the annotation hierarchy <em>above</em> the supplied {@code element};
* and for each annotation found, merge that annotation's attributes with
* <em>matching</em> attributes from annotations in lower levels of the annotation
* hierarchy and synthesize the results back into an annotation of the specified
* {@code annotationType}.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both within a
* single annotation and within annotation hierarchies.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* <p><strong>WARNING</strong>: if the supplied {@code containerType} is not
* {@code null}, the search will be restricted to supporting only repeatable
* annotations whose container is the supplied {@code containerType}. This
* prevents the search from finding repeatable annotations declared as
* meta-annotations on other types of repeatable annotations. If you need to
* support such a use case, favor {@link #getMergedRepeatableAnnotations(AnnotatedElement, Class)}
* over this method or alternatively use the {@link MergedAnnotations} API
* directly in conjunction with {@link RepeatableContainers} that are
* {@linkplain RepeatableContainers#and(Class, Class) composed} to support
* multiple repeatable annotation types.
* @param element the annotated element (never {@code null})
* @param annotationType the annotation type to find (never {@code null})
* @param containerType the type of the container that holds the annotations;
* may be {@code null} if the container type should be looked up via
* {@link java.lang.annotation.Repeatable}
* @return the set of all merged repeatable {@code Annotations} found,
* or an empty set if none were found
* @throws IllegalArgumentException if the {@code element} or {@code annotationType}
* is {@code null}, or if the container type cannot be resolved
* @throws AnnotationConfigurationException if the supplied {@code containerType}
* is not a valid container annotation for the supplied {@code annotationType}
* @since 4.3
* @see #getMergedAnnotation(AnnotatedElement, Class)
* @see #getAllMergedAnnotations(AnnotatedElement, Class)
*/
public static <A extends Annotation> Set<A> getMergedRepeatableAnnotations(
AnnotatedElement element, Class<A> annotationType,
@Nullable Class<? extends Annotation> containerType) {
return getRepeatableAnnotations(element, containerType, annotationType)
.stream(annotationType)
.collect(MergedAnnotationCollectors.toAnnotationSet());
}
/**
* Get the annotation attributes of <strong>all</strong> annotations of the specified
* {@code annotationName} in the annotation hierarchy above the supplied
* {@link AnnotatedElement} and store the results in a {@link MultiValueMap}.
* <p>Note: in contrast to {@link #getMergedAnnotationAttributes(AnnotatedElement, String)},
* this method does <em>not</em> support attribute overrides.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationName the fully qualified class name of the annotation type to find
* @return a {@link MultiValueMap} keyed by attribute name, containing the annotation
* attributes from all annotations found, or {@code null} if not found
* @see #getAllAnnotationAttributes(AnnotatedElement, String, boolean, boolean)
*/
@Nullable
public static MultiValueMap<String, Object> getAllAnnotationAttributes(
AnnotatedElement element, String annotationName) {
return getAllAnnotationAttributes(element, annotationName, false, false);
}
/**
* Get the annotation attributes of <strong>all</strong> annotations of
* the specified {@code annotationName} in the annotation hierarchy above
* the supplied {@link AnnotatedElement} and store the results in a
* {@link MultiValueMap}.
* <p>Note: in contrast to {@link #getMergedAnnotationAttributes(AnnotatedElement, String)},
* this method does <em>not</em> support attribute overrides.
* <p>This method follows <em>get semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationName the fully qualified class name of the annotation type to find
* @param classValuesAsString whether to convert Class references into Strings or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to convert nested Annotation instances into
* {@code AnnotationAttributes} maps or to preserve them as Annotation instances
* @return a {@link MultiValueMap} keyed by attribute name, containing the annotation
* attributes from all annotations found, or {@code null} if not found
*/
@Nullable
public static MultiValueMap<String, Object> getAllAnnotationAttributes(AnnotatedElement element,
String annotationName, final boolean classValuesAsString, final boolean nestedAnnotationsAsMap) {
Adapt[] adaptations = Adapt.values(classValuesAsString, nestedAnnotationsAsMap);
return getAnnotations(element).stream(annotationName)
.filter(MergedAnnotationPredicates.unique(MergedAnnotation::getMetaTypes))
.map(MergedAnnotation::withNonMergedAttributes)
.collect(MergedAnnotationCollectors.toMultiValueMap(AnnotatedElementUtils::nullIfEmpty, adaptations));
}
/**
* Determine if an annotation of the specified {@code annotationType}
* is <em>available</em> on the supplied {@link AnnotatedElement} or
* within the annotation hierarchy <em>above</em> the specified element.
* <p>If this method returns {@code true}, then {@link #findMergedAnnotationAttributes}
* will return a non-null value.
* <p>This method follows <em>find semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationType the annotation type to find
* @return {@code true} if a matching annotation is present
* @since 4.3
* @see #isAnnotated(AnnotatedElement, Class)
*/
public static boolean hasAnnotation(AnnotatedElement element, Class<? extends Annotation> annotationType) {
// Shortcut: directly present on the element, with no merging needed?
if (AnnotationFilter.PLAIN.matches(annotationType) ||
AnnotationsScanner.hasPlainJavaAnnotationsOnly(element)) {
return element.isAnnotationPresent(annotationType);
}
// Exhaustive retrieval of merged annotations...
return findAnnotations(element).isPresent(annotationType);
}
/**
* Find the first annotation of the specified {@code annotationType} within
* the annotation hierarchy <em>above</em> the supplied {@code element} and
* merge that annotation's attributes with <em>matching</em> attributes from
* annotations in lower levels of the annotation hierarchy.
* <p>Attributes from lower levels in the annotation hierarchy override
* attributes of the same name from higher levels, and
* {@link AliasFor @AliasFor} semantics are fully supported, both
* within a single annotation and within the annotation hierarchy.
* <p>In contrast to {@link #getAllAnnotationAttributes}, the search algorithm
* used by this method will stop searching the annotation hierarchy once the
* first annotation of the specified {@code annotationType} has been found.
* As a consequence, additional annotations of the specified
* {@code annotationType} will be ignored.
* <p>This method follows <em>find semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationType the annotation type to find
* @param classValuesAsString whether to convert Class references into
* Strings or to preserve them as Class references
* @param nestedAnnotationsAsMap whether to convert nested Annotation instances into
* {@code AnnotationAttributes} maps or to preserve them as Annotation instances
* @return the merged {@code AnnotationAttributes}, or {@code null} if not found
* @since 4.2
* @see #findMergedAnnotation(AnnotatedElement, Class)
* @see #getMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)
*/
@Nullable
public static AnnotationAttributes findMergedAnnotationAttributes(AnnotatedElement element,
Class<? extends Annotation> annotationType, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
MergedAnnotation<?> mergedAnnotation = findAnnotations(element)
.get(annotationType, null, MergedAnnotationSelectors.firstDirectlyDeclared());
return getAnnotationAttributes(mergedAnnotation, classValuesAsString, nestedAnnotationsAsMap);
}
/**
* Find the first annotation of the specified {@code annotationName} within
* the annotation hierarchy <em>above</em> the supplied {@code element} and
* merge that annotation's attributes with <em>matching</em> attributes from
* annotations in lower levels of the annotation hierarchy.
* <p>Attributes from lower levels in the annotation hierarchy override
* attributes of the same name from higher levels, and
* {@link AliasFor @AliasFor} semantics are fully supported, both
* within a single annotation and within the annotation hierarchy.
* <p>In contrast to {@link #getAllAnnotationAttributes}, the search
* algorithm used by this method will stop searching the annotation
* hierarchy once the first annotation of the specified
* {@code annotationName} has been found. As a consequence, additional
* annotations of the specified {@code annotationName} will be ignored.
* <p>This method follows <em>find semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationName the fully qualified class name of the annotation type to find
* @param classValuesAsString whether to convert Class references into Strings or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to convert nested Annotation instances into
* {@code AnnotationAttributes} maps or to preserve them as Annotation instances
* @return the merged {@code AnnotationAttributes}, or {@code null} if not found
* @since 4.2
* @see #findMergedAnnotation(AnnotatedElement, Class)
* @see #getMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)
*/
@Nullable
public static AnnotationAttributes findMergedAnnotationAttributes(AnnotatedElement element,
String annotationName, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
MergedAnnotation<?> mergedAnnotation = findAnnotations(element)
.get(annotationName, null, MergedAnnotationSelectors.firstDirectlyDeclared());
return getAnnotationAttributes(mergedAnnotation, classValuesAsString, nestedAnnotationsAsMap);
}
/**
* Find the first annotation of the specified {@code annotationType} within
* the annotation hierarchy <em>above</em> the supplied {@code element},
* merge that annotation's attributes with <em>matching</em> attributes from
* annotations in lower levels of the annotation hierarchy, and synthesize
* the result back into an annotation of the specified {@code annotationType}.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both
* within a single annotation and within the annotation hierarchy.
* <p>This method follows <em>find semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element
* @param annotationType the annotation type to find
* @return the merged, synthesized {@code Annotation}, or {@code null} if not found
* @since 4.2
* @see #findAllMergedAnnotations(AnnotatedElement, Class)
* @see #findMergedAnnotationAttributes(AnnotatedElement, String, boolean, boolean)
* @see #getMergedAnnotationAttributes(AnnotatedElement, Class)
*/
@Nullable
public static <A extends Annotation> A findMergedAnnotation(AnnotatedElement element, Class<A> annotationType) {
// Shortcut: directly present on the element, with no merging needed?
if (AnnotationFilter.PLAIN.matches(annotationType) ||
AnnotationsScanner.hasPlainJavaAnnotationsOnly(element)) {
return element.getDeclaredAnnotation(annotationType);
}
// Exhaustive retrieval of merged annotations...
return findAnnotations(element)
.get(annotationType, null, MergedAnnotationSelectors.firstDirectlyDeclared())
.synthesize(MergedAnnotation::isPresent).orElse(null);
}
/**
* Find <strong>all</strong> annotations of the specified {@code annotationType}
* within the annotation hierarchy <em>above</em> the supplied {@code element};
* and for each annotation found, merge that annotation's attributes with
* <em>matching</em> attributes from annotations in lower levels of the annotation
* hierarchy and synthesize the results back into an annotation of the specified
* {@code annotationType}.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both within a
* single annotation and within annotation hierarchies.
* <p>This method follows <em>find semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element (never {@code null})
* @param annotationType the annotation type to find (never {@code null})
* @return the set of all merged, synthesized {@code Annotations} found,
* or an empty set if none were found
* @since 4.3
* @see #findMergedAnnotation(AnnotatedElement, Class)
* @see #getAllMergedAnnotations(AnnotatedElement, Class)
*/
public static <A extends Annotation> Set<A> findAllMergedAnnotations(AnnotatedElement element, Class<A> annotationType) {
return findAnnotations(element).stream(annotationType)
.sorted(highAggregateIndexesFirst())
.collect(MergedAnnotationCollectors.toAnnotationSet());
}
/**
* Find <strong>all</strong> annotations of the specified {@code annotationTypes}
* within the annotation hierarchy <em>above</em> the supplied {@code element};
* and for each annotation found, merge that annotation's attributes with
* <em>matching</em> attributes from annotations in lower levels of the
* annotation hierarchy and synthesize the results back into an annotation
* of the corresponding {@code annotationType}.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both within a
* single annotation and within annotation hierarchies.
* <p>This method follows <em>find semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element (never {@code null})
* @param annotationTypes the annotation types to find
* @return the set of all merged, synthesized {@code Annotations} found,
* or an empty set if none were found
* @since 5.1
* @see #findAllMergedAnnotations(AnnotatedElement, Class)
*/
public static Set<Annotation> findAllMergedAnnotations(AnnotatedElement element, Set<Class<? extends Annotation>> annotationTypes) {
return findAnnotations(element).stream()
.filter(MergedAnnotationPredicates.typeIn(annotationTypes))
.sorted(highAggregateIndexesFirst())
.collect(MergedAnnotationCollectors.toAnnotationSet());
}
/**
* Find all <em>repeatable annotations</em> of the specified {@code annotationType}
* within the annotation hierarchy <em>above</em> the supplied {@code element};
* and for each annotation found, merge that annotation's attributes with
* <em>matching</em> attributes from annotations in lower levels of the annotation
* hierarchy and synthesize the results back into an annotation of the specified
* {@code annotationType}.
* <p>The container type that holds the repeatable annotations will be looked up
* via {@link java.lang.annotation.Repeatable}.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both within a
* single annotation and within annotation hierarchies.
* <p>This method follows <em>find semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* @param element the annotated element (never {@code null})
* @param annotationType the annotation type to find (never {@code null})
* @return the set of all merged repeatable {@code Annotations} found,
* or an empty set if none were found
* @throws IllegalArgumentException if the {@code element} or {@code annotationType}
* is {@code null}, or if the container type cannot be resolved
* @since 4.3
* @see #findMergedAnnotation(AnnotatedElement, Class)
* @see #findAllMergedAnnotations(AnnotatedElement, Class)
* @see #findMergedRepeatableAnnotations(AnnotatedElement, Class, Class)
*/
public static <A extends Annotation> Set<A> findMergedRepeatableAnnotations(AnnotatedElement element,
Class<A> annotationType) {
return findMergedRepeatableAnnotations(element, annotationType, null);
}
/**
* Find all <em>repeatable annotations</em> of the specified {@code annotationType}
* within the annotation hierarchy <em>above</em> the supplied {@code element};
* and for each annotation found, merge that annotation's attributes with
* <em>matching</em> attributes from annotations in lower levels of the annotation
* hierarchy and synthesize the results back into an annotation of the specified
* {@code annotationType}.
* <p>{@link AliasFor @AliasFor} semantics are fully supported, both within a
* single annotation and within annotation hierarchies.
* <p>This method follows <em>find semantics</em> as described in the
* {@linkplain AnnotatedElementUtils class-level javadoc}.
* <p><strong>WARNING</strong>: if the supplied {@code containerType} is not
* {@code null}, the search will be restricted to supporting only repeatable
* annotations whose container is the supplied {@code containerType}. This
* prevents the search from finding repeatable annotations declared as
* meta-annotations on other types of repeatable annotations. If you need to
* support such a use case, favor {@link #findMergedRepeatableAnnotations(AnnotatedElement, Class)}
* over this method or alternatively use the {@link MergedAnnotations} API
* directly in conjunction with {@link RepeatableContainers} that are
* {@linkplain RepeatableContainers#and(Class, Class) composed} to support
* multiple repeatable annotation types.
* @param element the annotated element (never {@code null})
* @param annotationType the annotation type to find (never {@code null})
* @param containerType the type of the container that holds the annotations;
* may be {@code null} if the container type should be looked up via
* {@link java.lang.annotation.Repeatable}
* @return the set of all merged repeatable {@code Annotations} found,
* or an empty set if none were found
* @throws IllegalArgumentException if the {@code element} or {@code annotationType}
* is {@code null}, or if the container type cannot be resolved
* @throws AnnotationConfigurationException if the supplied {@code containerType}
* is not a valid container annotation for the supplied {@code annotationType}
* @since 4.3
* @see #findMergedAnnotation(AnnotatedElement, Class)
* @see #findAllMergedAnnotations(AnnotatedElement, Class)
*/
public static <A extends Annotation> Set<A> findMergedRepeatableAnnotations(AnnotatedElement element,
Class<A> annotationType, @Nullable Class<? extends Annotation> containerType) {
return findRepeatableAnnotations(element, containerType, annotationType)
.stream(annotationType)
.sorted(highAggregateIndexesFirst())
.collect(MergedAnnotationCollectors.toAnnotationSet());
}
private static MergedAnnotations getAnnotations(AnnotatedElement element) {
return MergedAnnotations.from(element, SearchStrategy.INHERITED_ANNOTATIONS, RepeatableContainers.none());
}
private static MergedAnnotations getRepeatableAnnotations(AnnotatedElement element,
@Nullable Class<? extends Annotation> containerType, Class<? extends Annotation> annotationType) {
RepeatableContainers repeatableContainers;
if (containerType == null) {
// Invoke RepeatableContainers.of() in order to adhere to the contract of
// getMergedRepeatableAnnotations() which states that an IllegalArgumentException
// will be thrown if the container cannot be resolved.
//
// In any case, we use standardRepeatables() in order to support repeatable
// annotations on other types of repeatable annotations (i.e., nested repeatable
// annotation types).
//
// See https://github.com/spring-projects/spring-framework/issues/20279
RepeatableContainers.of(annotationType, null);
repeatableContainers = RepeatableContainers.standardRepeatables();
}
else {
repeatableContainers = RepeatableContainers.of(annotationType, containerType);
}
return MergedAnnotations.from(element, SearchStrategy.INHERITED_ANNOTATIONS, repeatableContainers);
}
private static MergedAnnotations findAnnotations(AnnotatedElement element) {
return MergedAnnotations.from(element, SearchStrategy.TYPE_HIERARCHY, RepeatableContainers.none());
}
private static MergedAnnotations findRepeatableAnnotations(AnnotatedElement element,
@Nullable Class<? extends Annotation> containerType, Class<? extends Annotation> annotationType) {
RepeatableContainers repeatableContainers;
if (containerType == null) {
// Invoke RepeatableContainers.of() in order to adhere to the contract of
// findMergedRepeatableAnnotations() which states that an IllegalArgumentException
// will be thrown if the container cannot be resolved.
//
// In any case, we use standardRepeatables() in order to support repeatable
// annotations on other types of repeatable annotations (i.e., nested repeatable
// annotation types).
//
// See https://github.com/spring-projects/spring-framework/issues/20279
RepeatableContainers.of(annotationType, null);
repeatableContainers = RepeatableContainers.standardRepeatables();
}
else {
repeatableContainers = RepeatableContainers.of(annotationType, containerType);
}
return MergedAnnotations.from(element, SearchStrategy.TYPE_HIERARCHY, repeatableContainers);
}
@Nullable
private static MultiValueMap<String, Object> nullIfEmpty(MultiValueMap<String, Object> map) {
return (map.isEmpty() ? null : map);
}
private static <A extends Annotation> Comparator<MergedAnnotation<A>> highAggregateIndexesFirst() {
return Comparator.<MergedAnnotation<A>> comparingInt(MergedAnnotation::getAggregateIndex).reversed();
}
@Nullable
private static AnnotationAttributes getAnnotationAttributes(MergedAnnotation<?> annotation,
boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
if (!annotation.isPresent()) {
return null;
}
return annotation.asAnnotationAttributes(Adapt.values(classValuesAsString, nestedAnnotationsAsMap));
}
/**
* Adapted {@link AnnotatedElement} that holds specific annotations.
*/
private static class AnnotatedElementForAnnotations implements AnnotatedElement {
private final Annotation[] annotations;
AnnotatedElementForAnnotations(Annotation... annotations) {
this.annotations = annotations;
}
@Override
@SuppressWarnings("unchecked")
@Nullable
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
for (Annotation annotation : this.annotations) {
if (annotation.annotationType() == annotationClass) {
return (T) annotation;
}
}
return null;
}
@Override
public Annotation[] getAnnotations() {
return this.annotations.clone();
}
@Override
public Annotation[] getDeclaredAnnotations() {
return this.annotations.clone();
}
}
}
|
package ro.ase.csie.g1093.testpractice.builder;
public class User {
//the class should have a lot of attributes
//all attributes should be final or at least private
private final String firstName;
private final String lastName;
private final int age;
private final String phoneNo;
private final String homeAddress;
private final String email;
//if you don't make a constructor with ALL of them, there will be an error
// private User(String firstName, String lastName, int age, String phoneNo, String homeAddress, String email) {
// super();
// this.firstName = firstName;
// this.lastName = lastName;
// this.age = age;
// this.phoneNo = phoneNo;
// this.homeAddress = homeAddress;
// this.email = email;
// }
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.email = builder.email;
this.homeAddress = builder.homeAddress;
this.phoneNo = builder.phoneNo;
}
//generate ONLY GETTERS
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getPhoneNo() {
return phoneNo;
}
public String getHomeAddress() {
return homeAddress;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "User: "+this.firstName+", "+this.lastName+", "+this.age+", "+this.phoneNo+", "+this.homeAddress+ "," + this.email;
}
//facem o clasa statica in interiorul clasei normale
public static class UserBuilder {
//we copy all the fields
private final String firstName;
private final String lastName;
private int age;
private String phoneNo;
private String homeAddress;
private String email;
//but only first and last name are REQUIRED,
//the rest are optional
//so we only keep those 2 final and the rest of them are only private
//we generate a ctor with those 2
public UserBuilder(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
//now generate userbuilder methods for all fields
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder email(String email) {
this.email = email;
return this;
}
public UserBuilder phoneNo(String phoneNo) {
this.phoneNo = phoneNo;
return this;
}
public UserBuilder address(String address) {
this.homeAddress = address;
return this;
}
public User build() {
// User user = new User(this.firstName, this.lastName, this.age,
// this.phoneNo,this.homeAddress, this.email);
User user = new User(this);
return user;
}
//we can also have this method here to perform validations, if required
private void validateUserObject(User user) {
//Do some basic validations to check
//if user object does not break any assumption of system
}
}
}
|
package controller;
import algorithm.annealing.test.SATestManager;
import algorithm.genetic.test.GATestManager;
import application.MainApplication;
import configuration.TestConfig;
import javafx.application.Platform;
import view.MainView;
public class MainController {
// View
private MainView view = new MainView(MainApplication.APP_WIDTH, MainApplication.APP_HEIGHT);
// Model Managers
private GATestManager gaTestManager = new GATestManager();
private SATestManager saTestManager = new SATestManager();
public void init() {
if (TestConfig.DISPLAY_UI) {
if (TestConfig.TEST_SA) {
saTestManager.addListener(tour -> {
// Run on the JavaFX thread
Platform.runLater(() -> {
view.updateTour(tour);
view.updateText("Distance: " + String.valueOf(tour.getDistance()));
});
});
}
if (TestConfig.TEST_GA) {
gaTestManager.addListener(tour -> {
// Run on the JavaFX thread
Platform.runLater(() -> {
view.updateTour(tour);
view.updateText("Distance: " + String.valueOf(tour.getDistance()));
});
});
}
}
}
public void run() {
if (TestConfig.TEST_SA)
saTestManager.test();
if (TestConfig.TEST_GA)
gaTestManager.test();
}
public MainView getView() {
return view;
}
}
|
/*
* (c) 2009 Thomas Smits
*/
package de.smits_net.tpe;
class PackagePrivateClass {
}
class NochEineKlasse {
}
class UndNochEine {
}
|
package com.gaoshin.fandroid;
import java.util.List;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.RemoteViews;
public abstract class WidgetProvider extends AppWidgetProvider {
public static final String UPDATE_ACTION = "common.android.UPDATE_APP_WIDGET";
private static final int[] txtResIds = {
R.id.text00, R.id.text01, R.id.text02, R.id.text03,
R.id.text10, R.id.text11, R.id.text12, R.id.text13,
R.id.text20, R.id.text21, R.id.text22, R.id.text23,
R.id.text30, R.id.text31, R.id.text32, R.id.text33,
};
private static final int[] imgResIds = {
R.id.img00, R.id.img01, R.id.img02, R.id.img03,
R.id.img10, R.id.img11, R.id.img12, R.id.img13,
R.id.img20, R.id.img21, R.id.img22, R.id.img23,
R.id.img30, R.id.img31, R.id.img32, R.id.img33,
};
private static final int[] contactIds = {
R.id.contact00, R.id.contact01, R.id.contact02, R.id.contact03,
R.id.contact10, R.id.contact11, R.id.contact12, R.id.contact13,
R.id.contact20, R.id.contact21, R.id.contact22, R.id.contact23,
R.id.contact30, R.id.contact31, R.id.contact32, R.id.contact33,
};
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getData() != null && intent.getData().toString().equals(UPDATE_ACTION)) {
RemoteViews views = updateWidget(context);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName componentName = new ComponentName(context, this.getClass());
appWidgetManager.updateAppWidget(componentName, views);
} else {
super.onReceive(context, intent);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for (int widgetId : appWidgetIds) {
RemoteViews views = updateWidget(context);
appWidgetManager.updateAppWidget(widgetId, views);
}
}
private RemoteViews updateWidget(Context context) {
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
List<RecentItem> recents = getRecents(context);
int i = 0;
for (; i < 16 && i < recents.size(); i++) {
views.setViewVisibility(contactIds[i], View.VISIBLE);
setupItem(recents.get(i), txtResIds[i], imgResIds[i], views);
}
for(;i<16; i++) {
views.setViewVisibility(contactIds[i], View.INVISIBLE);
}
return views;
}
private void setupItem(RecentItem recentItem, int txtResId, int imgResId, RemoteViews views) {
if (recentItem.getText() != null) {
views.setTextViewText(txtResId, recentItem.getText());
}
if (recentItem.getIcon() != null) {
views.setImageViewBitmap(imgResId, recentItem.getIcon());
}
if (recentItem.getIntent() != null) {
views.setOnClickPendingIntent(txtResId, recentItem.getIntent());
views.setOnClickPendingIntent(imgResId, recentItem.getIntent());
}
}
protected abstract List<RecentItem> getRecents(Context context);
}
|
package org.point85.domain.dto;
import org.point85.domain.DomainUtils;
import org.point85.domain.collector.OeeEvent;
import com.google.gson.annotations.SerializedName;
/**
* Data Transfer Object (DTO) for a recorded OEE event
*/
public class OeeEventDto {
@SerializedName(value = "type")
private String eventType;
@SerializedName(value = "equipment")
private String equipmentName;
@SerializedName(value = "source")
private String sourceId;
@SerializedName(value = "input")
private String inputValue;
@SerializedName(value = "output")
private String outputValue;
@SerializedName(value = "reason")
private String reason;
@SerializedName(value = "start")
private String startTimestamp;
@SerializedName(value = "end")
private String endTimestamp;
@SerializedName(value = "duration")
private Long duration;
@SerializedName(value = "job")
private String job;
@SerializedName(value = "collector")
private String collector;
@SerializedName(value = "amount")
private Double amount;
@SerializedName(value = "lostTime")
private Long lostTime;
@SerializedName(value = "material")
private String material;
@SerializedName(value = "shift")
private String shift;
@SerializedName(value = "team")
private String team;
@SerializedName(value = "uom")
private String uom;
public OeeEventDto(OeeEvent event) {
this.eventType = event.getEventType() != null ? event.getEventType().serialize() : null;
this.equipmentName = event.getEquipment() != null ? event.getEquipment().getName() : null;
this.sourceId = event.getSourceId();
this.inputValue = event.getInputValue() != null ? event.getInputValue().toString() : null;
this.setOutputValue(event.getOutputValue() != null ? event.getOutputValue().toString() : null);
this.reason = event.getReason() != null ? event.getReason().getName() : null;
this.startTimestamp = DomainUtils.offsetDateTimeToString(event.getStartTime(),
DomainUtils.OFFSET_DATE_TIME_8601);
this.endTimestamp = DomainUtils.offsetDateTimeToString(event.getEndTime(), DomainUtils.OFFSET_DATE_TIME_8601);
this.duration = event.getDuration() != null ? event.getDuration().getSeconds() : null;
this.job = event.getJob();
this.collector = event.getCollector();
this.amount = event.getAmount();
this.lostTime = (event.getLostTime() != null ? event.getLostTime().getSeconds() : null);
this.material = (event.getMaterial() != null ? event.getMaterial().getName() : null);
this.shift = (event.getShift() != null ? event.getShift().getName() : null);
this.team = (event.getTeam() != null ? event.getTeam().getName() : null);
this.uom = (event.getUOM() != null ? event.getUOM().getSymbol() : null);
}
public String getSourceId() {
return sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
public String getValue() {
return inputValue;
}
public void setValue(String value) {
this.inputValue = value;
}
public String getStartTimestamp() {
return startTimestamp;
}
public void setStartTimestamp(String timestamp) {
this.startTimestamp = timestamp;
}
public Long getDuration() {
return duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
public String getEndTimestamp() {
return endTimestamp;
}
public void setEndTimestamp(String endTimestamp) {
this.endTimestamp = endTimestamp;
}
public String getEquipmentName() {
return equipmentName;
}
public void setEquipmentName(String equipmentName) {
this.equipmentName = equipmentName;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("source id: " + sourceId);
sb.append(", equipment: " + equipmentName);
sb.append(", event: " + eventType);
sb.append(", value: " + inputValue);
sb.append(", start timestamp: " + startTimestamp);
sb.append(", end timestamp: " + endTimestamp);
sb.append(", duration: " + duration);
sb.append(", reason: " + reason);
return sb.toString();
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getOutputValue() {
return outputValue;
}
public void setOutputValue(String outputValue) {
this.outputValue = outputValue;
}
public String getCollector() {
return collector;
}
public void setCollector(String collector) {
this.collector = collector;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public Long getLostTime() {
return lostTime;
}
public void setLostTime(Long lostTime) {
this.lostTime = lostTime;
}
public String getMaterial() {
return material;
}
public void setMaterial(String material) {
this.material = material;
}
public String getShift() {
return shift;
}
public void setShift(String shift) {
this.shift = shift;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public String getUom() {
return uom;
}
public void setUom(String uom) {
this.uom = uom;
}
}
|
package pro.likada.dao.daoImpl;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pro.likada.bean.controller.LoginController;
import pro.likada.dao.UserDAO;
import pro.likada.model.Role;
import pro.likada.model.RoleEnum;
import pro.likada.model.User;
import pro.likada.util.HibernateUtil;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* Created by Yusupov on 12/14/2016.
*/
@SuppressWarnings("unchecked")
@Named("userDAO")
@Transactional
public class UserDAOImpl implements UserDAO {
private static final Logger LOGGER = LoggerFactory.getLogger(UserDAOImpl.class);
@Inject
private LoginController loginController;
@Override
public User findById(long id) {
LOGGER.info("Get all users with an ID: {}", id);
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(User.class, "user").setCacheable(true);
criteria.createAlias("user.userRoles", "role", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("user.userPermissions", "permission", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("user.subordinates", "subordinates", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("user.parents", "parents", JoinType.LEFT_OUTER_JOIN);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);//To avoid duplicates.
criteria.add(Restrictions.idEq(id));
User user = (User) criteria.uniqueResult();
session.close();
return user;
}
@Override
public User findByUsername(String username) {
LOGGER.info("Get all users with USERNAME: {}", username);
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(User.class, "user");
criteria.createAlias("user.userRoles", "role", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("user.userPermissions", "permission", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("user.subordinates", "subordinates", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("user.parents", "parents", JoinType.LEFT_OUTER_JOIN);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);//To avoid duplicates.
criteria.add(Restrictions.eq("user.username", username));
User user = (User) criteria.uniqueResult();
session.close();
return user;
}
@Override
public List<User> findByRole(String roleType){
LOGGER.info("Get all users with ROLE: {}", roleType);
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(User.class, "user");
criteria.createAlias("user.userRoles", "role", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("user.userPermissions", "permission", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("user.subordinates", "subordinates", JoinType.LEFT_OUTER_JOIN);
criteria.createAlias("user.parents", "parents", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.ilike("role.type", roleType));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List<User> users = (List<User>)criteria.list();
session.close();
return users;
}
@Override
public List<User> getAllUsers() {
LOGGER.info("Get all users");
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(User.class, "user");
criteria.createAlias("user.userRoles", "role");
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);//To avoid duplicates.
criteria.addOrder(Order.asc("user.title"));
List<User> users = (List<User>)criteria.setCacheable(true).list();
session.close();
return users;
}
@Override
public List<User> findAllUsersNotAddedToTable(String searchString, Set<User> customerManagers) {
LOGGER.info("Get all users according: {}", searchString);
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(User.class, "user");
criteria.createAlias("user.userRoles", "role");
// Apply filter to show users (for Manager place) of the Customer
User user = loginController.getCurrentUser();
List<Long> userChildIds = new LinkedList<>();
for(User u: user.getSubordinates())
for (Role r: u.getUserRoles())
if (RoleEnum.SALES_MANAGER.getRoleType().equals(r.getType()))
userChildIds.add(u.getId());
for (Role r: user.getUserRoles()){
if(RoleEnum.ADMIN.getRoleType().equals(r.getType())) {
criteria.add(Restrictions.ilike("role.type", RoleEnum.SALES_MANAGER.getRoleType()));
}
if(RoleEnum.SALES_MANAGER.getRoleType().equals(r.getType())) {
criteria.add(Restrictions.eq("user.id", user.getId()));
}
if(RoleEnum.SALES_MANAGER_ASSISTANT.getRoleType().equals(r.getType())) {
criteria.add(Restrictions.in("user.id", userChildIds)); // TODO optimize restriction for userChilds
}
}
// Add filter to do not to show Users that are already listed as Customer Manager in the table
if(customerManagers!=null && customerManagers.size()>0){
List<Long> currentCustomerManagersIds = new LinkedList<>();
for (User u: customerManagers)
currentCustomerManagersIds.add(u.getId());
criteria.add(Restrictions.not(Restrictions.in("id", currentCustomerManagersIds)));
}
// If in search field exists text, add restriction to show only users that matches to that string
if(searchString!=null && !searchString.isEmpty()) {
criteria.add(Restrictions.or(Restrictions.ilike("user.username", searchString, MatchMode.ANYWHERE),
Restrictions.ilike("user.firstName", searchString, MatchMode.ANYWHERE),
Restrictions.ilike("user.lastName", searchString, MatchMode.ANYWHERE),
Restrictions.ilike("user.patronymic", searchString, MatchMode.ANYWHERE),
Restrictions.ilike("user.title", searchString, MatchMode.ANYWHERE),
Restrictions.ilike("user.email", searchString, MatchMode.ANYWHERE),
Restrictions.ilike("user.phone", searchString, MatchMode.ANYWHERE),
Restrictions.ilike("user.mobile", searchString, MatchMode.ANYWHERE)));
}
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);//To avoid duplicates.
criteria.addOrder(Order.asc("user.firstName"));
criteria.addOrder(Order.asc("user.lastName"));
criteria.addOrder(Order.asc("user.title"));
List<User> users = (List<User>)criteria.list();
session.close();
return users;
}
@Override
public void changePassword(long userId, String newPassword) {
LOGGER.info("Change password of the user with ID"+userId+", new password: " + newPassword);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
User user = findById(userId);
user.setPassword(newPassword);
session.saveOrUpdate(user);
transaction.commit();
session.flush();
session.close();
}
@Override
public void save(User user) {
LOGGER.info("Saving a new user: " + user);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(user);
transaction.commit();
session.flush();
session.close();
}
@Override
public void deleteByUsername(String username) {
LOGGER.info("Delete user with username:" + username);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.delete(findByUsername(username));
transaction.commit();
session.flush();
session.close();
}
}
|
package com.soft1841.book.controller;
import com.soft1841.book.entity.Book;
import com.soft1841.book.service.BookService;
import com.soft1841.book.utils.ServiceFactory;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.VBox;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class ViewBookController implements Initializable {
@FXML
private FlowPane bookPane;
private List<Book> bookList;
private BookService bookService = ServiceFactory.getBookServiceInstance();
private static final int MAX_THREADS = 4;
//线程池配置
private final Executor exec = Executors.newFixedThreadPool(MAX_THREADS, runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t;
});
@Override
public void initialize(URL location, ResourceBundle resources) {
bookList = bookService.getAllBooks();
showBooks(bookList);
}
private void showBooks(List<Book> list) {
ObservableList<Node> observableList = bookPane.getChildren();
bookPane.getChildren().removeAll(observableList);
for (Book book : list) {
VBox vBox = new VBox();
vBox.setPrefSize(240, 300);
vBox.getStyleClass().add("box");
vBox.setSpacing(10);
vBox.setAlignment(Pos.CENTER);
ImageView imageView = new ImageView();
//利用线程池来加载图片,并设置为图书封面
exec.execute(new Runnable() {
@Override
public void run() {
imageView.setImage(new Image(book.getCover()));
}
});
imageView.setFitWidth(100);
imageView.setFitHeight(100);
imageView.getStyleClass().add("hover-change");
Label nameLabel = new Label(book.getName());
nameLabel.getStyleClass().add("font-title");
Label authorLabel = new Label("作者:" + book.getAuthor());
Label priceLabel = new Label("价格:" + book.getPrice());
Label stockLabel = new Label("库存:" + book.getStock());
Button delBtn = new Button("删除");
delBtn.getStyleClass().add("warning-theme");
vBox.getChildren().addAll(imageView, nameLabel, authorLabel, priceLabel, stockLabel, delBtn);
bookPane.getChildren().add(vBox);
delBtn.setOnAction(event -> {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("确认对话框");
alert.setContentText("确定要删除这行记录吗?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
bookService.deleteBook(book.getId());
bookPane.getChildren().remove(vBox);
}
});
}
}
}
|
package com.gaoshin.onsalelocal.osl.beans;
public enum SearchOrder {
DistanceAsc,
DistanceDesc,
UpdatedAsc,
UpdatedDesc,
}
|
package com.mycompany.ghhrkapp1.service;
import org.springframework.data.domain.Page;
import com.mycompany.ghhrkapp1.dto.PersonsDTO;
import com.mycompany.ghhrkapp1.entity.Persons;
public interface PersonService {
Iterable<Persons> listAll();
Page<Persons> listAllPaged(int page);
Persons save(PersonsDTO personsDTO);
}
|
package com.zantong.mobilecttx.base.fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.zantong.mobilecttx.R;
import com.zantong.mobilecttx.utils.PullToRefreshLayout;
import butterknife.Bind;
/**
* 可下拉刷新页面
*/
public abstract class PullableBaseFragment extends BaseFragment {
@Bind(R.id.pull_refresh_view)
PullToRefreshLayout mPullRefreshView;
/**
* 动态添加布局
*/
private View rootView;
@Override
protected int getLayoutResId() {
return R.layout.base_pullable_fragment;
}
@Override
public void initView(View view) {
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.base_content);
LayoutInflater inflater = LayoutInflater.from(getActivity());
if (rootView == null) {
rootView = inflater.inflate(getFragmentLayoutResId(), null);
}
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
linearLayout.addView(rootView, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
initFragmentView(view);
}
@Override
public void initData() {
mPullRefreshView.setPullDownEnable(isRefresh());
mPullRefreshView.setPullUpEnable(isLoadMore());
mPullRefreshView.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
@Override
public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
if (mPullRefreshView != null) mPullRefreshView.postDelayed(new Runnable() {
public void run() {
onRefreshData();
if (mPullRefreshView != null)
mPullRefreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
}
}, 1500);
}
@Override
public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
if (mPullRefreshView != null) mPullRefreshView.postDelayed(new Runnable() {
public void run() {
onLoadMoreData();
if (mPullRefreshView != null)
mPullRefreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
}
}, 1500);
}
});
loadingData();
}
/**
* 下拉数据设置
*/
protected abstract void onRefreshData();
protected abstract void onLoadMoreData();
protected abstract void initFragmentView(View view);
protected abstract void loadingData();
protected abstract int getFragmentLayoutResId();
@Override
protected void onForceRefresh() {
loadingData();
}
/**
* 是否下拉刷新 默认为不支持
*
* @return true 是,false 否
*/
protected boolean isRefresh() {
return true;
}
/**
* 是否加载更多 默认支持加载更多
*
* @return true 是,false 否
*/
protected boolean isLoadMore() {
return false;
}
@Override
public void onClick(View v) {
}
}
|
package slimeknights.tconstruct.tools.common.client.module;
import net.minecraft.util.ResourceLocation;
import slimeknights.mantle.client.gui.GuiElement;
import slimeknights.mantle.client.gui.GuiElementScalable;
import slimeknights.tconstruct.library.Util;
public final class GuiGeneric {
public static final ResourceLocation LOCATION = Util.getResource("textures/gui/generic.png");
// first one sets default texture w/h
public static final GuiElement cornerTopLeft = new GuiElement(0, 0, 7, 7, 64, 64);
public static final GuiElement cornerTopRight = new GuiElement(64 - 7, 0, 7, 7);
public static final GuiElement cornerBottomLeft = new GuiElement(0, 64 - 7, 7, 7);
public static final GuiElement cornerBottomRight = new GuiElement(64 - 7, 64 - 7, 7, 7);
public static final GuiElementScalable borderTop = new GuiElementScalable(7, 0, 64 - 7 - 7, 7);
public static final GuiElementScalable borderBottom = new GuiElementScalable(7, 64 - 7, 64 - 7 - 7, 7);
public static final GuiElementScalable borderLeft = new GuiElementScalable(0, 7, 7, 64 - 7 - 7);
public static final GuiElementScalable borderRight = new GuiElementScalable(64 - 7, 7, 7, 64 - 7 - 7);
public static final GuiElementScalable overlap = new GuiElementScalable(21, 45, 7, 14);
public static final GuiElement overlapTopLeft = new GuiElement(7, 40, 7, 7);
public static final GuiElement overlapTopRight = new GuiElement(14, 40, 7, 7);
public static final GuiElement overlapBottomLeft = new GuiElement(7, 47, 7, 7);
public static final GuiElement overlapBottomRight = new GuiElement(14, 47, 7, 7);
public static final GuiElementScalable textBackground = new GuiElementScalable(7 + 18, 7, 18, 10);
public static final GuiElementScalable slot = new GuiElementScalable(7, 7, 18, 18);
public static final GuiElementScalable slotEmpty = new GuiElementScalable(7 + 18, 7, 18, 18);
public static final GuiElement sliderNormal = new GuiElement(7, 25, 10, 15);
public static final GuiElement sliderLow = new GuiElement(17, 25, 10, 15);
public static final GuiElement sliderHigh = new GuiElement(27, 25, 10, 15);
public static final GuiElement sliderTop = new GuiElement(43, 7, 12, 1);
public static final GuiElement sliderBottom = new GuiElement(43, 38, 12, 1);
public static final GuiElementScalable sliderBackground = new GuiElementScalable(43, 8, 12, 30);
private GuiGeneric() {
}
}
|
package monitors;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import utils.CSV;
import utils.GetDate;
public class ProcessMonitor implements Runnable {
private boolean isOn=true;
private int sampleTime=0;
private String path="";
private String processName;
public ProcessMonitor(String processName) {
// TODO Auto-generated constructor stub
this.processName=processName;
}
@Override
public void run() {
// TODO Auto-generated method stub
String thisIP = "";
try {
thisIP = Inet4Address.getLocalHost().getHostAddress().replace("192.168", "").replace(".", "_");
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String date = GetDate.getDate();
String dateCleaned=date.replaceAll("[^0-9]+", "_");
String fileName=path+this.processName+thisIP+dateCleaned;
String dateHeader = "Date ";
String memoryHeader = processName +" memory";
String cpuHeader = processName +" CPU";
try (CSV csv =new CSV(fileName,dateHeader,memoryHeader,cpuHeader)) {
while(this.isOn()){
String processMemoreyUsage =""+ BasicMonitors.getProcessMemoreyUsage(processName);
double cpuUsageDouble = BasicMonitors.getCpuUsage(processName);
String preCPUUsage =(cpuUsageDouble<10)? "0":"";
String cpuUsage = preCPUUsage+cpuUsageDouble;
date = GetDate.getDate();
csv.addLine(date,processMemoreyUsage,cpuUsage);
try {
Thread.sleep(sampleTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
String processName = "studio";
Thread thread;
ProcessMonitor processMonitor=new ProcessMonitor(processName);
thread =new Thread(processMonitor);
thread.start();
Thread.sleep(60000);
processMonitor.setOff();
thread.join();
}
public boolean isOn() {
return isOn;
}
public void setOff() {
this.isOn = false;
}
public int getSampleTime() {
return sampleTime;
}
public void setSampleTime(int sampleTime) {
this.sampleTime = sampleTime;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
|
package hello;
public enum Car {
FERRARI,PORSCHE,LAMBORGHINI
}
|
package by.academy.homework.homework5;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class Task4 {
public static void main(String[] args) {
List<Integer> arrayList = new ArrayList<>();
addMarks(arrayList);
System.out.println("Список оценок: " + arrayList);
Iterator<Integer> iterator = arrayList.iterator();
Integer element = arrayList.get(0);
while (iterator.hasNext()) {
Integer nextElement = iterator.next();
if (element < nextElement) {
element = nextElement;
}
}
System.out.println("Наивысшая оценка:" + element);
}
private static void addMarks(List <Integer> arrayList) {
Random rand = new Random();
for (int i = 0; i < 10; i++) {
arrayList.add(1 + rand.nextInt(10));
}
}
}
|
/*
* 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 prototype;
/**
*
* @author robotica
*/
public class PrototypeFactory {
Animal prototypeAnimal;
public PrototypeFactory(Animal prototypeAnimal) {
this.prototypeAnimal = prototypeAnimal;
}
public Animal criarClone() {
return (Animal) prototypeAnimal.clone();
}
}
|
package asylumdev.adgresources.api.materialsystem.material;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
public class Materials {
public static List<BasicMaterial> materials = new ArrayList<>();
public static BlockMaterial advancium = new BlockMaterial("advancium", new Color(150, 50, 150), 0, 1, 1);
public void addMaterials() {
materials.add(advancium);
}
public void registerParts() {
for(int i = 0; i < materials.size(); i++) {
materials.get(i).regParts();
}
}
}
|
package com.prasnottar.nepalidateconverter.core;
import com.prasnottar.nepalidateconverter.exception.NepaliDateConverterException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by bibek on 6/24/17.
*/
class NepaliDateConverterImpl implements NepaliDateConverter {
private static final Logger LOG = Logger.getLogger(NepaliDateConverterImpl.class.getName());
@Override
public NepaliDate getNepaliDate(int englishYear, int englishMonth, int englishDay) {
String dateStr = englishYear + "-" + englishMonth + "-" + englishDay;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date dateOn = null;
try {
dateOn = dateFormat.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return this.getNepaliDate(dateOn);
}
private void validateEnglishDate(Date date) {
if (!Common.isEnglishDateInRange(date)) {
throw new NepaliDateConverterException("English Date is not valid date");
}
}
@Override
public NepaliDate getNepaliDate(java.util.Date date) {
this.validateEnglishDate(date);
LOG.log(Level.INFO, "Starting date {0} ", new Object[]{date.toString()});
int nepaliYear = STARTING_NEPALI_YEAR;
int nepaliMonth = STARTING_NEPALI_MONTH;
int nepaliDays = STARTING_NEPALI_DAY;
//same as starting english or nepali
int startingDayOfWeek = STARTING_DAY_OF_WEEK;
String startedDate = STARTING_ENGLISH_YEAR + "-" + STARTING_ENGLISH_MONTH + "-" + STARTING_ENGLISH_DAY;
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
Date starter = null;
try {
starter = inputFormat.parse(startedDate);
} catch (ParseException ex) {
}
LOG.info(startedDate);
long totalNumberOfEnglishDate =
this.totalNumberOfDaysFromGivenEnglishDayToStarting(starter, date);
LOG.log(Level.INFO, "Number of days{0}", new Object[]{totalNumberOfEnglishDate});
while (totalNumberOfEnglishDate != 0) {
int endOftheMonth = NepaliDateStorage
.findDaysInEndOftheNepaliMonth(nepaliYear, nepaliMonth);
nepaliDays++;
startingDayOfWeek++;
if (nepaliDays > endOftheMonth) {
nepaliMonth++;
nepaliDays = 1;
}
if (nepaliMonth > 12) {
nepaliYear++;
nepaliMonth = 1;
}
if (startingDayOfWeek > 7) {
startingDayOfWeek = 1;
}
totalNumberOfEnglishDate--;
}
return new NepaliDate(nepaliYear, nepaliMonth, nepaliDays, startingDayOfWeek);
}
private long totalNumberOfDaysFromGivenEnglishDayToStarting(java.util.Date startingDate, Date givenDate) {
long difference = givenDate.getTime() - startingDate.getTime();
return TimeUnit.DAYS.convert(difference, TimeUnit.MILLISECONDS);
}
@Override
public NepaliDate getNepaliDate(Calendar calendar) {
return this.getNepaliDate(calendar.getTime());
}
}
|
package com.hibernateExample.springHibernate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringHibernateExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringHibernateExampleApplication.class, args);
}
}
|
package com.minhvu.proandroid.sqlite.database.main.presenter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.minhvu.proandroid.sqlite.database.R;
import com.minhvu.proandroid.sqlite.database.Utils.DeEncrypter;
import com.minhvu.proandroid.sqlite.database.main.model.view.IGetShareModel;
import com.minhvu.proandroid.sqlite.database.main.presenter.view.IGetSharePresenter;
import com.minhvu.proandroid.sqlite.database.main.view.Activity.DetailNoteActivity;
import com.minhvu.proandroid.sqlite.database.main.view.Activity.view.IGetShareActivity;
import com.minhvu.proandroid.sqlite.database.models.entity.Note;
/**
* Created by vomin on 9/12/2017.
*/
public class GetSharePresenter extends MvpPresenter<IGetShareModel, IGetShareActivity.View> implements IGetSharePresenter {
private Uri currentUri = null;
@Override
public Context getActivityContext() {
return getView().getActivityContext();
}
@Override
public Context getAppContext() {
return getView().getAppContext();
}
@Override
public void onDestroy(boolean isChangingConfiguration) {
unbindView();
if (!isChangingConfiguration) {
model = null;
currentUri = null;
}
}
@Override
public void setCurrentUri(Uri uri) {
this.currentUri = uri;
}
@Override
public Uri getCurrentUri() {
return currentUri;
}
@Override
public void loadNote() {
if (currentUri == null) {
return;
}
Object v = getView();
Note note = model.loadNote(currentUri.getPathSegments().get(1));
if (note != null) {
if (!TextUtils.isEmpty(model.getmNote().getPassword())) {
getView().lockContent();
note.setContent("LOCK CONTENT");
}
long imageCount = model.getCountImages(Long.parseLong(currentUri.getPathSegments().get(1)));
getView().visibleView();
updateView(note);
getView().updateImageCount((int)imageCount);
}
}
@Override
public void updateView(Note note) {
getView().updateView(note.getTitle(), note.getContent());
}
@Override
public void onDetailOnClick() {
final Note note = model.getmNote();
if (!TextUtils.isEmpty(note.getPassword())) {
LayoutInflater inflater = (LayoutInflater) getActivityContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.popup_password_set, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivityContext());
builder.setView(dialogLayout);
final AlertDialog dialog = builder.create();
final EditText editText = (EditText) dialogLayout.findViewById(R.id.etPassWord);
editText.setFocusable(true);
ImageButton imgBtnNo = (ImageButton) dialogLayout.findViewById(R.id.btnNo);
ImageButton imgBtnYes = (ImageButton) dialogLayout.findViewById(R.id.btnYes);
imgBtnYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String password = editText.getText().toString();
if (TextUtils.isEmpty(password)) {
return;
}
String pas = DeEncrypter.decryptString(note.getPassword(), note.getPassSalt());
if (pas.equals(password)) {
dialog.dismiss();
startActivity();
} else {
editText.setText("");
}
}
});
imgBtnNo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
getView().showDialog(dialog);
} else {
startActivity();
}
}
private void startActivity() {
Intent intent = new Intent(getActivityContext(), DetailNoteActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setData(currentUri);
getView().getActivityContext().startActivity(intent);
}
@Override
public void saveNote(EditText title, EditText content) {
if (currentUri == null) {
boolean success = model.insertNote(title.getText().toString(), content.getText().toString());
if (success) {
Toast toast = Toast.makeText(getActivityContext(), "saved Data", Toast.LENGTH_SHORT);
getView().showToast(toast);
}
} else {
boolean success = model.updateNote(currentUri.getPathSegments().get(1),
title.getText().toString(), content.getText().toString());
if (success) {
Toast toast = Toast.makeText(getActivityContext(), "saved Data", Toast.LENGTH_SHORT);
getView().showToast(toast);
}
}
}
@Override
public void updateView() {
}
}
|
package fudan.database.project.dao.impl;
import fudan.database.project.dao.DAO;
import fudan.database.project.dao.DoctorDAO;
import fudan.database.project.entity.Doctor;
import java.util.List;
public class DoctorDAOJdbcImpl extends DAO<Doctor> implements DoctorDAO {
@Override
public List<Doctor> getAll() {
String sql = "SELECT doctorId, name, password, areaId FROM doctor";
return getForList(sql);
}
@Override
public void update(Doctor doctor) {
String sql = "UPDATE doctor SET name = ?, password = ? WHERE doctorId = ?";
update(sql, doctor.getName(), doctor.getPassword(), doctor.getDoctorId());
}
@Override
public Doctor get(String name) {
String sql = "SELECT doctorId, name, password, areaId FROM doctor WHERE name = ?";
return get(sql, name);
}
@Override
public Doctor get(int areaId) {
String sql = "SELECT doctorId, name, password, areaId FROM doctor WHERE areaId = ?";
return get(sql, areaId);
}
}
|
package com.comp445.lab2.http;
import com.comp445.lab2.file.server.FileServerHandler;
import com.comp445.lab2.file.server.DirectoryOutputMethod;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class FileServerHandlerTest {
@Test
public void testFetchDirectory_WithEnumPlain_shouldReturnValidString() throws IOException {
FileServerHandler FSHandler = new FileServerHandler();
String listOfFiles = FSHandler.fetchDirectory(DirectoryOutputMethod.Plain);
assertEquals("files:\ntest1.txt\ntest2.txt\ndont_change_me_test_file.txt\n", listOfFiles);
}
@Test
public void testFetchFile_WithValidFile_shouldReturnValidResponse() throws Exception {
FileServerHandler FSHandler = new FileServerHandler();
String fileContents = FSHandler.fetchFile("dont_change_me_test_file.txt");
assertEquals("test data", fileContents);
}
@Test(expected = FileNotFoundException.class)
public void testFetchFile_WithNonexistentFile_shouldThrow() throws Exception {
FileServerHandler FSHandler = new FileServerHandler();
FSHandler.fetchFile("DOES_NOT_EXIST");
}
}
|
/*
* 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 Num;
/**
*
* @author YNZ
*/
public class WhyMustDouble {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int rate = 10;
int t = 5;
double amount = 1000.0; //float is nto valid
for (int i = 0; i < t; t++) {
amount = amount * (1 - rate / 100);
}
}
}
|
package com.alibaba.druid.test;
import javax.sql.DataSource;
import org.junit.Assert;
import junit.framework.TestCase;
import org.nutz.dao.Chain;
import org.nutz.dao.Dao;
import org.nutz.dao.impl.NutDao;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;
import com.alibaba.druid.pool.DruidDataSource;
public class NutzTransactionTest extends TestCase {
private DataSource dataSource;
protected void setUp() throws Exception {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:jtds:sqlserver://192.168.1.105/petstore");
dataSource.setUsername("sa");
dataSource.setPassword("hello");
dataSource.setFilters("log4j");
// BasicDataSource dataSource = new BasicDataSource();
// dataSource.setDriverClassName("net.sourceforge.jtds.jdbc.Driver");
// dataSource.setUrl("jdbc:jtds:sqlserver://192.168.1.105/petstore");
// dataSource.setUsername("sa");
// dataSource.setPassword("hello");
this.dataSource = dataSource;
}
public void test_trans() throws Exception {
Dao dao = new NutDao(dataSource);
dao.clear("test");
// doTran1(dao);
doTran2(dao);
}
void doTran1(final Dao dao) {
try {
Trans.exec(new Atom() {
@Override
public void run() {
dao.insert("[test]", Chain.make("name", "1"));
throw new RuntimeException();
}
});
} catch (Exception e) {
}
Assert.assertEquals(0, dao.count("[test]"));
}
void doTran2(final Dao dao) {
try {
Trans.exec(new Atom() {
@Override
public void run() {
dao.insert("[test]", Chain.make("name", "1"));
dao.insert("[test]", Chain.make("name", "111111111111111111111111111111"));
}
});
} catch (Exception e) {
// e.printStackTrace();
}
Assert.assertEquals(0, dao.count("[test]"));
}
}
|
package com.citibank.ods.entity.pl.valueobject;
import java.math.BigInteger;
import com.citibank.ods.common.entity.valueobject.BaseEntityVO;
/**
*
*@author michele.monteiro,02/05/2007
*/
public class BaseTbgSystemEntityVO extends BaseEntityVO
{
// Codigo da segmentacao do sistema
private BigInteger m_sysSegCode = null;
// Codigo da segmentacao do sistema
private BigInteger m_sysCode = null;
//Nome do sistema
private String m_sysName = "";
//Codigo do status do sistema
private String m_sysStatCode="";
//Codigo do tipo de sistema
private BigInteger m_sysTypeCode = null;
/**
* @return Retorna o código do sistema.
*/
public BigInteger getSysCode()
{
return m_sysCode;
}
/**
* @param sysCode_.Seta o código do sistema.
*/
public void setSysCode( BigInteger sysCode_ )
{
m_sysCode = sysCode_;
}
/**
* @return Retorna o nome do sistema;
*/
public String getSysName()
{
return m_sysName;
}
/**
* @param sysName_.Seta o nome do sistema;
*/
public void setSysName( String sysName_ )
{
m_sysName = sysName_;
}
/**
* @return Retorna o código da segmentação do sistema.
*/
public BigInteger getSysSegCode()
{
return m_sysSegCode;
}
/**
* @param sysSegCode_.Seta o código da segmentação do sistema;
*/
public void setSysSegCode( BigInteger sysSegCode_ )
{
m_sysSegCode = sysSegCode_;
}
/**
* @return Retorna o status do sistema;
*/
public String getSysStatCode()
{
return m_sysStatCode;
}
/**
* @param sysStatCode_.Seta o status do sistema.
*/
public void setSysStatCode( String sysStatCode_ )
{
m_sysStatCode = sysStatCode_;
}
/**
* @return Retorna o tipo de sistema.
*/
public BigInteger getSysTypeCode()
{
return m_sysTypeCode;
}
/**
* @param sysTypeCode_.Seta o tipo de sistema.
*/
public void setSysTypeCode( BigInteger sysTypeCode_ )
{
m_sysTypeCode = sysTypeCode_;
}
}
|
package com.crealytics.reporting;
import com.crealytics.reporting.service.ReportService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class StartupApplicationListener implements ApplicationListener<ApplicationReadyEvent> {
private static final Logger logger = LogManager.getLogger(ReportService.class);
@Value("${reports.path}")
private String path;
@Autowired
ReportService reportService;
/*
* the listener executes the onApplicationEvent method when application is ready to start and all
* components are loaded this method main functionality is to call the reporting service to load all report
* files into the H2 database
* */
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
logger.info("start loading data into database");
reportService.parseFilesAndSaveInDB(path);
logger.info("finished loading data into database");
}
}
|
import org.junit.jupiter.api.Test;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.*;
class OfficeEmployeeTest {
@Test
void boxReassignBox() {
Date birthDate = new Date();
birthDate.setYear(birthDate.getYear()-30);
Date hireDate = new Date();
hireDate.setYear(birthDate.getYear()+25);
OfficeEmployee empForTest0 = new OfficeEmployee("Wojtek", "Lew", birthDate, hireDate,
new Address("Gdynia", "Odrębna", 19), 120);//value 600
Register register = new Register();
register.addEmployee(empForTest0);
register.delEmployee(empForTest0);
OfficeEmployee empForTest1 = new OfficeEmployee("Alojzy", "Krolikowski", birthDate, hireDate,
new Address("Wejherowo", "Okrezna", 13), 150);
register.addEmployee(empForTest1);
assertEquals(0, empForTest1.getBoxNumber());
}
}
|
package be.tcla.bookinventory.repository;
import be.tcla.bookinventory.model.Book;
import be.tcla.bookinventory.model.Genre;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BookJpaRepository extends JpaRepository<Book, Integer> {
List<Book> findByAuthorContaining(String author);
//Book findByIsbn(String isbn);
List<Book> findByGenreContaining(Genre genre);
List<Book> findByTitleContaining(String keyword);
List<Book> findByEbook(boolean ebook);
Book findByTitleAndAuthorContaining(String title, String author);
}
|
package io.shodo.banking.account.infra;
import io.shodo.banking.account.domain.core.Account;
import io.shodo.banking.account.domain.core.AccountNumber;
import io.shodo.banking.account.domain.core.PositiveAmount;
import io.shodo.banking.account.domain.core.Transaction;
import static io.shodo.banking.account.domain.core.Transaction.Type.DEPOSIT;
import static io.shodo.banking.account.domain.core.Transaction.Type.WITHDRAWAL;
import io.shodo.banking.account.domain.port.spi.TimeProvider;
import io.shodo.banking.account.infra.renderer.AccountStatementPrinter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import static org.mockito.BDDMockito.given;
import org.mockito.Mockito;
public class AccountStatementPrinterTest {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.ENGLISH);
private AccountStatementPrinter printer = new AccountStatementPrinter();
private TimeProvider timeProvider = Mockito.mock(TimeProvider.class);
@Test
void should_print_balance_line() {
assertThat(printer.renderBalanceLine(new PositiveAmount(1))).isEqualTo("Balance: 0,01 €");
assertThat(printer.renderBalanceLine(new PositiveAmount(10))).isEqualTo("Balance: 0,1 €");
assertThat(printer.renderBalanceLine(new PositiveAmount(100))).isEqualTo("Balance: 1,0 €");
assertThat(printer.renderBalanceLine(new PositiveAmount(1000))).isEqualTo("Balance: 10,0 €");
assertThat(printer.renderBalanceLine(new PositiveAmount(1223))).isEqualTo("Balance: 12,23 €");
}
@Test
void should_print_account_number_line() {
Account account = new Account(new AccountNumber("1234556789"), timeProvider);
assertThat(printer.renderAccountNumberLine(account)).isEqualTo("Statements for account: 1234556789");
}
@Test
void empty_history_should_print_only_the_header() {
Account account = Mockito.mock(Account.class);
given(account.transactions()).willReturn(Collections.emptyList());
assertThat(printer.renderStatements(account)).isEqualTo("""
| Date | Amount | Operation |
""");
}
@Test
void should_print_one_deposit_line_statement() {
Account account = Mockito.mock(Account.class);
given(account.transactions()).willReturn(
List.of(new Transaction(DEPOSIT, new PositiveAmount(1300), date("05/07/2019")))
);
assertThat(printer.renderStatements(account))
.isEqualTo("""
| Date | Amount | Operation |
| 05/07/2019 | 13,0 | DEPOSIT |
""");
}
@Test
void should_print_one_withdrawal_line_statement() {
Account account = Mockito.mock(Account.class);
given(account.transactions()).willReturn(
List.of(new Transaction(WITHDRAWAL, new PositiveAmount(1300), date("05/07/2019")))
);
assertThat(printer.renderStatements(account))
.isEqualTo("""
| Date | Amount | Operation |
| 05/07/2019 | 13,0 | WITHDRAWAL |
""");
}
@Test
void should_print_multiple_lines_statement() {
Account account = Mockito.mock(Account.class);
given(account.transactions()).willReturn(
List.of(
new Transaction(WITHDRAWAL, new PositiveAmount(1300), date("05/07/2019")),
new Transaction(DEPOSIT, new PositiveAmount(1200), date("06/07/2019")),
new Transaction(WITHDRAWAL, new PositiveAmount(100000), date("07/07/2019")),
new Transaction(DEPOSIT, new PositiveAmount(120221), date("12/07/2019")))
);
assertThat(printer.renderStatements(account))
.isEqualTo("""
| Date | Amount | Operation |
| 05/07/2019 | 13,0 | WITHDRAWAL |
| 06/07/2019 | 12,0 | DEPOSIT |
| 07/07/2019 | 1000,0 | WITHDRAWAL |
| 12/07/2019 | 1202,21 | DEPOSIT |
""");
}
private LocalDate date(String stringDate) {
return LocalDate.parse(stringDate, formatter);
}
}
|
package sales_tax;
import java.util.List;
import java.util.ArrayList;
/**
* Created by Eugene on 5/14/2015.
*/
public class ProductParser {
public List<Product> parseProducts(List<String> lines) {
List<Product> products = new ArrayList<>();
for(String line: lines){
String name = "";
String[] tokens = line.split(" ");
int quantity = Integer.parseInt(tokens[0]);
int i = 1;
while(!tokens[i].equals("at")) {
name += tokens[i] + " ";
i++;
}
double price = Double.parseDouble(tokens[tokens.length-1]);
products.add(new ProductFactory().create(quantity, name, price));
}
return products;
}
}
|
/**
* All rights Reserved, Designed By www.tydic.com
* @Title: SearchDao.java
* @Package com.taotao.search.dao
* @Description: TODO(用一句话描述该文件做什么)
* @author: axin
* @date: 2019年2月11日 下午9:05:01
* @version V1.0
* @Copyright: 2019 www.hao456.top Inc. All rights reserved.
*/
package com.taotao.search.dao;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import com.taotao.search.pojo.SearchResult;
/**
* @Description: TODO
* @ClassName: SearchDao
* @author: Axin
* @date: 2019年2月11日 下午9:05:01
* @Copyright: 2019 www.hao456.top Inc. All rights reserved.
*/
public interface SearchDao {
SearchResult search(SolrQuery query) throws SolrServerException ;
}
|
package com.energytrade.app.util;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
import org.springframework.stereotype.Component;
@Component
public class PushHelper {
private static final String webServiceURI = "https://onesignal.com/api/v1/notifications";
//private final static String notification_url = "https://onesignal.com/api/v1/notifications";
private final static String AUTHTOKEN = "Basic ZGQzMDc1MDktMzQ0NC00MzM1LTkwNGEtNzMxZjE1MzA0NWQ4";
public String pushToUser(String status, String playerId, String message, String wod)
throws ClassNotFoundException, SQLException {
Connection conn = null;
// JDBCConnection connref=new JDBCConnection();
// Class.forName("com.mysql.jdbc.Driver");
PreparedStatement st = null;
// conn = connref.getOracleConnection();
// CommonDBHelper commondbhelper=new CommonDBHelper();
// OrderDao odao=new OrderDao();
String strJsonBody = "";
try {
String jsonResponse;
// Proxy proxy = new Proxy(Proxy.Type.HTTP, new
// InetSocketAddress("www-proxy.idc.oracle.com", 80));
URL url = new URL("https://onesignal.com/api/v1/notifications");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Authorization", AUTHTOKEN);
con.setRequestMethod("POST");
//if (status.equalsIgnoreCase("notifyservicemanoforders")) {
strJsonBody = "{" + "\"app_id\": \"9b0a5ec6-e306-4aa7-9713-722d8ee1f47c\","
+ "\"include_external_user_ids\": [\"" +playerId+"\"],"
+ "\"data\": {\"response\": \"notifyorders\"}," + "\"contents\": {\"en\": \"" + message + "\"}," + "\"priority\": \"10\"" + "}";
//}
/*
* if (status.equalsIgnoreCase("notifybuyer")) {
*
* strJsonBody = "{" + "\"app_id\": \"843d9906-6279-49e6-9075-8ce45f8f14c5\"," +
* "\"include_player_ids\": [\"" + playerId + "\"]," +
* "\"data\": {\"response\": \"notifyorders\"}," + "\"contents\": {\"en\": \"" +
* message + " -" + wod + "\"}," + "\"priority\": \"10\"" + "}";
*
* }
*/
System.out.println("strJsonBody:\n" + strJsonBody);
byte[] sendBytes = strJsonBody.getBytes("UTF-8");
con.setFixedLengthStreamingMode(sendBytes.length);
OutputStream outputStream = con.getOutputStream();
outputStream.write(sendBytes);
int httpResponse = con.getResponseCode();
System.out.println("httpResponse: " + httpResponse);
if (httpResponse >= HttpURLConnection.HTTP_OK && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
} else {
Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
System.out.println("jsonResponse:\n" + jsonResponse);
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
public static void main(String args[]) throws ClassNotFoundException, SQLException {
PushHelper ph = new PushHelper();
ph.pushToUser("1", "1", "1", "1");
}
}
|
package ar.edu.unlam.scaw.persistencia;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = {"/applicationContext.xml"})
public class HsqlDataSource {
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL).addScript("db/sql/create-db.sql")
.addScript("db/sql/insert-data.sql").build();
return db;
}
}
|
package jire.player;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.UUID;
import jire.world.ChatMessage;
import jire.world.Entity;
import jire.world.UpdateFlagSet;
public class Player extends Entity {
private final transient List<LocalPlayerListEntry> localPlayers = new ArrayList<LocalPlayerListEntry>();
private final transient UpdateFlagSet updateFlags = new UpdateFlagSet();
private final transient Queue<ChatMessage> chatQueue = new LinkedList<ChatMessage>();
private transient UUID uuid;
private transient int index;
private final String username;
private final String password;
private final int rights;
public Player(UUID uuid, int index, String username, String password, int rights) {
this.uuid = uuid;
this.index = index;
this.username = username;
this.password = password;
this.rights = rights;
}
public UpdateFlagSet getUpdateFlags() {
return updateFlags;
}
public List<LocalPlayerListEntry> getLocalPlayerEntries() {
return localPlayers;
}
public Queue<ChatMessage> getChatQueue() {
return chatQueue;
}
public UUID getUUID() {
return uuid;
}
public int getIndex() {
return index;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public int getRights() {
return rights;
}
}
|
package zhuoxin.com.viewpagerdemo.info;
public class userInfo {
public String name;
public String passwd;
public userInfo(String name, String passwd) {
this.name = name;
this.passwd = passwd;
}
public String toString() {
return "userInfo{" +
"name='" + name + '\'' +
", passwd='" + passwd + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
|
package com.car;
/**
* Created by husiqin on 16/9/6.
*/
public class DoubleCar extends Car {
DoubleCar(String name, double pricepd, double capabilityT, int capabilityP) {
this.name = name;
this.pricepd = pricepd;
this.load = capabilityT;
this.numOfPerson = capabilityP;
}
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println(
'\t' + this.name + " " + '\t' + this.pricepd + " " + '\t' + this.numOfPerson + " " + '\t' + this.load);
}
}
|
import java.util.*;
public class Carnivore extends Animal
{
public Carnivore(String n, String sym, TreeSet<String> s, double dm, double ds, double be, double me, double le, double ie, double pm, double ps, double mr, double dr, double hr) {
super(n, sym, s, dm, ds, be, me, le, ie, pm, ps, mr, dr, hr);
}
public Carnivore(Species parent) {
super(parent.name, parent.symbol, parent.energySources, parent.deathMedian, parent.deathStd, parent.birthEnergy, parent.maxEnergy, parent.livingEnergy, parent.initialEnergy, parent.popMedian, parent.popStd, parent.moveRange, parent.detectRange, parent.hungerThreshold);
}
/**
* Calls methods from Animal class to try to eat
* @return boolean - true if the animal eats, false otherwise
*/
public boolean eat() {
return this.eatAnimal();
}
}
|
package com.alex.chess;
import com.alex.chess.enums.Color;
import static com.alex.chess.util.MapCoordinates.*;
public class Board {
private Cell[][] state;
public Board() {
this.state = new Cell[8][8];
for (int i = 0; i < 64; i++) {
if ((i + 1) % 2 != 0) {
state[i / 8][i % 8] = new Cell(Color.WHITE, null, new Coord(INDEX_TO_ROW.get(i/8), INDEX_TO_COLUMN.get(i%8)));
} else {
state[i / 8][i % 8] = new Cell(Color.BLACK, null, new Coord(INDEX_TO_ROW.get(i/8), INDEX_TO_COLUMN.get(i%8)));
}
}
}
public Cell[][] getState() {
return state;
}
}
|
package com.larryhsiao.nyx.base;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.hardware.fingerprint.FingerprintManagerCompat;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.larryhsiao.nyx.JotApplication;
import com.silverhetch.aura.AuraActivity;
import com.silverhetch.aura.fingerprint.Fingerprint;
import com.silverhetch.aura.fingerprint.FingerprintImpl;
import com.silverhetch.clotho.Source;
import com.silverhetch.clotho.storage.MemoryCeres;
import java.sql.Connection;
/**
* Activity for Jot.
*/
public abstract class JotActivity extends AuraActivity {
protected Source<Connection> db;
protected FirebaseRemoteConfig remoteConfig;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
JotApplication app = ((JotApplication) getApplicationContext());
db = app.db;
remoteConfig = app.remoteConfig;
remoteConfig.fetchAndActivate();
}
@Override
protected void onResume() {
super.onResume();
Fingerprint fingerprint = new FingerprintImpl(
FingerprintManagerCompat.from(this), new MemoryCeres()
);
fingerprint.enable(true); // enabled by default
JotApplication app = (JotApplication) getApplicationContext();
if (fingerprint.isEnabled() && 300000 < System.currentTimeMillis() - app.lastAuthed) {
Intent intent = new Intent(this, AuthActivity.class);
startActivity(intent);
}
}
}
|
package com.zxt.compplatform.workflow.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import com.googlecode.jsonplugin.JSONException;
import com.googlecode.jsonplugin.JSONUtil;
import com.opensymphony.xwork2.ActionSupport;
import com.zxt.compplatform.workflow.Util.WorkFlowUtil;
import com.zxt.compplatform.workflow.service.WorkflowAuthSettingService;
public class WorkflowAuthSetAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private WorkflowAuthSettingService workflowAuthSettingService;
/**
* 功能:保存权限配置
* 访问地址:/workflow/nodeAuthSet!add.action
* @return
*/
public String add(){
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter out = null;
String flag = "fail";
try {
out = response.getWriter();
} catch (IOException e1) {
e1.printStackTrace();
}
//获取相关的配置信息
//解析配置信息
String setting = request.getParameter("setting");
//System.out.println(setting);
try {
Object object = JSONUtil.deserialize(setting);
workflowAuthSettingService.addAuth(object);
/*Map settings = (HashMap)object;
String nodeid = settings.get("nodeid").toString();
List setlist = (List)settings.get("setting");
for (int i = 0; i < setlist.size(); i++) {//不同用户
Map userset = (HashMap)setlist.get(i);
EngWorkflowNodesetting nodeset = new EngWorkflowNodesetting();
if(nodeset.getId() == null|| "".equals(nodeset.getId())){
nodeset.setId(RandomGUID.geneGuid());
}
nodeset.setNodeId(nodeid);
Set userKeySet = userset.keySet();
Iterator userKeySetIter = userKeySet.iterator();
StringBuffer buffer = new StringBuffer("<functions>");
while(userKeySetIter.hasNext()){
String current = userKeySetIter.next().toString();
if("userid".equals(current)){//用户
nodeset.setNodeParticipator(userset.get("userid").toString());
}else{//配置函数
buffer.append("<function>").append("<authType>").append(current).append("</authType>");
Map map = (HashMap)userset.get(current);
buffer.append("<funcName>").append(map.get("funName")).append("<funcName>");
List list = (List)map.get("rows");
buffer.append("<params>");
for (int j = 0; j < list.size(); j++) {
Map paramMap = (Map)list.get(i);
buffer.append("<param>").append("<paramName>").append(paramMap.get("paramname")).append("</paramName>")
.append("<paramType>").append(paramMap.get("paramtype")).append("</paramType>")
.append("<paramValue>").append(paramMap.get("paramvalue")).append("</paramValue>")
.append("<paramOrder>").append(paramMap.get("order")).append("</paramOrder>")
.append("</param>");
}
buffer.append("</params></function>");
}
}
buffer.append("</functions>");
nodeset.setNodeAuthSetting(buffer.toString());
} */
flag = "success";
} catch (JSONException e) {
e.printStackTrace();
flag = "fail";
}
out.print(flag);
return null;
}
/**
* 获取某个流程定义的版本号列表
* 访问地址:/workflow/nodeAuthSet!getTemplateHis.action
* @return
*/
public String getTemplateHis(){
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter out = null;
try {
out = response.getWriter();
String processId = request.getParameter("processInstanceID");
int processID = 0;
processID = Integer.parseInt(processId);
JSONArray array = JSONArray.fromObject(WorkFlowUtil.findModelListByProcessId(processID));
out.print(array.toString());
} catch (IOException e) {
e.printStackTrace();
}finally{
out.close();
}
return null;
}
/**
* 获取前驱线的状态
* 访问地址:/workflow/nodeAuthSet!getPreLineStatus.action
* @return
*/
public String getPreLineStatus(){
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
String processInstanceID = req.getParameter("processInstanceID");
String modelId = req.getParameter("modelId");
String nodeid = req.getParameter("nodeid");
List list = null;
try{
int processId = 0;
if(processInstanceID != null && !"".equals(processInstanceID)){
processId = Integer.parseInt(processInstanceID);
}
int mid = 0;
if(modelId != null && !"".equals(modelId)){
mid = Integer.parseInt(modelId);
}
int nodeKey = 0 ;
if(nodeid != null && !"".equals(nodeid)){
nodeKey = Integer.parseInt(nodeid);
}
//list = workFlowFrameService.getWFModelNodeListByPId(processInstanceID);
list = WorkFlowUtil.findAllTransfer(processId, mid, nodeKey);
}catch(Exception e){
e.printStackTrace();
}
try {
String json = JSONArray.fromObject(list).toString();
res.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 获得节点参与者,同时将相关的以配置的权限查询出来
* 访问地址:workflow/nodeAuthSet!getNodeParticipants.action
* @return
*/
public String getNodeParticipants(){
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
PrintWriter out = null;
try {
out = res.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
String nodeidString = req.getParameter("nodeId");
String modelIdString = req.getParameter("modelId");
int nodeid = 0 ;
if(nodeidString != null && !"".equals(nodeidString)){
nodeid = Integer.parseInt(nodeidString);
}
int modelid = 0;
if(modelIdString != null && !"".equals(modelIdString)){
modelid = Integer.parseInt(modelIdString);
}
List list = WorkFlowUtil.backAllParticipantByactivityDefId(nodeid,modelid);
Map map = new HashMap();
map.put("rows", list);
map.put("total", list.size()+"");
JSONObject array = JSONObject.fromObject(map);
out.print(array.toString());
out.close();
return null;
}
/**
* 获取去node权限配置列表
* 访问地址:/workflow/nodeAuthSet!getNodeSetting.action
* @return
*/
public String getNodeSetting(){
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
PrintWriter out = null;
try {
out = res.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
String nodeidString = req.getParameter("nodeId");
String modelIdString = req.getParameter("modelId");
int nodeid = 0 ;
if(nodeidString != null && !"".equals(nodeidString)){
nodeid = Integer.parseInt(nodeidString);
}
int modelid = 0;
if(modelIdString != null && !"".equals(modelIdString)){
modelid = Integer.parseInt(modelIdString);
}
List listssList = workflowAuthSettingService.getPartinerOwnAuthList(modelIdString,nodeidString);
Map reMap = new HashMap();
reMap.put("rows", listssList);
reMap.put("total", listssList.size()+"");
JSONObject array = JSONObject.fromObject(reMap);
out.print(array.toString());
out.close();
return null;
}
public String delete(){
return null;
}
public String update(){
return null;
}
public WorkflowAuthSettingService getWorkflowAuthSettingService() {
return workflowAuthSettingService;
}
public void setWorkflowAuthSettingService(
WorkflowAuthSettingService workflowAuthSettingService) {
this.workflowAuthSettingService = workflowAuthSettingService;
}
}
|
package com.write;
public class dd {
}
/*
[java]
객체 지향 언어(OOP)
객체 : instance : 메모리에 실제 구현된 구현체
class -> 구현하기 위한 설계도
=> member - field : 속성 - instance variable
- class variable(static)
- method : 기능
접근제한자 메모리영역 리턴타입 이름(파라미터/아규먼트){body}
constructor : 객체 생성, 필드 초기화
oop 특징
- 추상화 abstract
- 다형성 polimorphism
- 상속 inheritance
- 캡슐화 encapsulation
type :
type 변수 = 값(literal);
기본타입 : call by value
참조타입 : call by reference
String -> "" => immutable
StringBuffer => mutable
opr :
control :
조건
if, switch
반복
for, while, do while
array : type[] = {} (정적)
= new type[] (동적)
복사 -> shallow copy : 얕은 복사, 주소값만 복사
deep copy : 깊은 복사, 값 복사
collection : 값 여러개, 크기 가변, <generics> / List Set Map
순서 o x x
중복 o x k : x, v : o
iterator : collection 뽑기
Map.Entry :
exception : 예외처리 try-catch
io stream : byte
thread : process 안의 작업단위
process : 실제 메모리에 올라간 프로그램 (일하는중)
program : 실행 파일(exe)
network :
uri : identifier
urn : name
url : location
tcp :
udp :
[DB]
- data 저장소
- rdb => relation entity (attribute tuple)
테이블 컬럼 로우
- noSql - mongodb - 대표적 - {key : value}형태 (json)
- 정규화
- oracle 11g xe
- SQL(Structured Query Language)
DDL : 정의
DML : 조작
DCL : 제어
- JOIN : table + table
- SUBQUERY : query 안에 query
(일반적으론 join 이 낫다)
PL/SQL :
Procedure, cursor
HTML : HyperTextMarkupLanguage - document를 tag로 구조화 - DOM탐색
CSS : Cascading StyleSheet - document를 꾸며준다
JAVASCRIPT : script language - document의 event
* java와 다른 특징 => function이 변수에 값으로 들어간다
$.ajax : 비동기 통신
[jsp/servlet]
servlet : java(html)
init() -> service() -> doGet()/doPost() -> destroy()
jsp : html(java)
redirect : 새로운 요청
forward : 이전과 같은 요청을 다음페이지에 전달
[Spring]
-> 경량 컨테이너 (EJB -> POJO)
1. DI/IOC
2. AOP
3. OCP
-> Spring MVC
동작 순서
Spring 버전 별 특징 및 쓰는 이유
3.x 클래스에서 빈 생성 가능
4.x
5.x 코틀린 등과 연동 가능 (확장성 증가)
Spring Boot : 서버 내장(default : tomcat)
디펜던시 추가 쉬움
[개인적으로 생각하는, 공부해보면 좋은 애들]
언어
- kotlin / swift : application 쪽
- golang : 수요가 적다 (당연히 공급도 적다.) = 일단 취업되면 내가 최고
- node.js / react.js : 웹개발에 많이 쓴다.
- python : 많은 분야에서 쓴다.
db
- mariadb : mysql 과 거의 똑같다. 중소기업은 mysql (or mariadb) 를 많이 쓴다.
- mongodb : 간단한 crud는 쉽다. 조금 들어가게 되면 어렵지만, 좋은 기능들이 많다.
기타
- intellij idea : 유료 (학생계정 1년 무료)
- vscode : front-end 개발에 거의 필수로 변하는 듯
*/
|
package com.zenwerx.findierock.data;
import java.util.ArrayList;
import java.util.Date;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.zenwerx.findierock.model.Artist;
import com.zenwerx.findierock.model.Event;
import com.zenwerx.findierock.model.Venue;
public class EventsHelper {
private static final String TAG = "findierock.EventsHelper";
public final String COL_EVENTID = "_id";
public final String COL_NAME = "name";
public final String COL_LATITUDE = "latitude";
public final String COL_LONGITUDE = "longitude";
public final String COL_DESCRIPTION = "description";
public final String COL_STARTTIME = "startTime";
public final String COL_AGEOFMAJORITY = "ageOfMajority";
public final String COL_VENUEID = "venueId";
public final String DATABASE_TABLE_EVENTS = "events";
public final String DATABASE_TABLE_EVENTARTISTS = "eventartists";
private final SQLiteDatabase mDb;
public EventsHelper(SQLiteDatabase db)
{
this.mDb = db;
}
private final ContentValues getContentValues(Event e)
{
final ContentValues cv = new ContentValues();
cv.put(COL_EVENTID, e.getEventId());
cv.put(COL_LATITUDE, e.getLatitude());
cv.put(COL_LONGITUDE, e.getLongitude());
cv.put(COL_NAME, e.getName());
cv.put(COL_DESCRIPTION, e.getDescription());
cv.put(COL_STARTTIME , (e.getStartTime().getTime()/1000));
cv.put(COL_AGEOFMAJORITY, e.getAgeOfMajority());
cv.put(COL_VENUEID, e.getVenueId());
return cv;
}
public ArrayList<Event> getEventsForToday()
{
ArrayList<Event> events = new ArrayList<Event>();
final Cursor c = mDb.query(DATABASE_TABLE_EVENTS, null, "date('now') = date(startTime, 'unixepoch', 'localtime')", null, null, null, null, null);
if (c != null && c.moveToFirst())
{
while (!c.isAfterLast())
{
Event e = readEvent(c);
events.add(e);
c.moveToNext();
}
}
if (c != null)
{
c.close();
}
return events;
}
public int countEventsForToday()
{
int result = 0;
final Cursor c = mDb.rawQuery("SELECT COUNT(1) FROM " + DATABASE_TABLE_EVENTS + " WHERE date('now') = date(startTime, 'unixepoch', 'localtime')", null);
if (c != null && c.moveToFirst())
{
result = c.getInt(0);
}
c.close();
return result;
}
public ArrayList<Event> getEventsForTodayOrLaterAtVenue(Venue v)
{
ArrayList<Event> events = new ArrayList<Event>();
final Cursor c = mDb.query(DATABASE_TABLE_EVENTS, null, "date('now') <= date(startTime, 'unixepoch', 'localtime') and venueId=?",
new String[] { Integer.toString(v.getVenueId()) }, null, null, COL_STARTTIME, null);
if (c != null && c.moveToFirst())
{
while (!c.isAfterLast())
{
Event e = readEvent(c, false);
events.add(e);
c.moveToNext();
}
}
if (c != null)
{
c.close();
}
return events;
}
public ArrayList<Event> getEventsForTodayOrLaterWithArtist(Artist a)
{
ArrayList<Event> events = new ArrayList<Event>();
final Cursor c = mDb.query(DATABASE_TABLE_EVENTS + " e, " + DATABASE_TABLE_EVENTARTISTS + " ea",
new String[] { "e." + COL_EVENTID, COL_AGEOFMAJORITY, COL_DESCRIPTION, COL_LATITUDE, COL_LONGITUDE, COL_NAME, COL_STARTTIME, COL_VENUEID },
"ea.EventId=e._id AND ea.ArtistId=? AND date('now') <= date(startTime, 'unixepoch', 'localtime')", new String[] { Integer.toString(a.getArtistId())},
null, null, null);
if (c != null && c.moveToFirst())
{
while (!c.isAfterLast())
{
Event e = readEvent(c, false);
events.add(e);
c.moveToNext();
}
}
if (c != null)
{
c.close();
}
return events;
}
public Event getEvent(int eventId)
{
final Cursor c = mDb.query(DATABASE_TABLE_EVENTS, null, "_id=?", new String[] { (new Integer(eventId)).toString() }, null, null, null, null);
Event e = null;
if (c != null && c.moveToFirst())
{
e = readEvent(c);
}
if (c != null)
{
c.close();
}
return e;
}
private Event readEvent(final Cursor c)
{
return readEvent(c, true);
}
private Event readEvent(final Cursor c, final boolean getVenue)
{
final int iId = c.getColumnIndex(COL_EVENTID);
final int iName = c.getColumnIndex(COL_NAME);
final int iLat = c.getColumnIndex(COL_LATITUDE);
final int iLong = c.getColumnIndex(COL_LONGITUDE);
final int iDesc = c.getColumnIndex(COL_DESCRIPTION);
final int iTime = c.getColumnIndex(COL_STARTTIME);
final int iAoM = c.getColumnIndex(COL_AGEOFMAJORITY);
final int iVID = c.getColumnIndex(COL_VENUEID);
Event e = new Event();
e.setAgeOfMajority(c.getInt(iAoM) != 0);
e.setDescription(c.getString(iDesc));
e.setEventId(c.getInt(iId));
e.setLatitude(c.getDouble(iLat));
e.setLongitude(c.getDouble(iLong));
e.setName(c.getString(iName));
Date d = new Date();
d.setTime(c.getLong(iTime)*1000);
e.setStartTime(d);
e.setVenueId(c.getInt(iVID));
if (getVenue)
{
Venue v = FindieDbHelper.getInstance().getVenueHelper().getVenueForEvent(e);
e.setVenue(v);
}
ArrayList<Artist> artists = FindieDbHelper.getInstance().getArtistHelper().getArtistsForEvent(e);
if (artists != null)
{
Artist[] aa = new Artist[artists.size()];
e.setArtists(artists.toArray(aa));
}
return e;
}
public void saveEvents(Event[] events)
{
saveEvents(events, true);
}
public void saveEvents(Event[] events, boolean saveVenue)
{
if (events != null)
{
try
{
mDb.beginTransaction();
for (Event e : events)
{
final ContentValues cv = getContentValues(e);
try
{
long id = mDb.insertOrThrow(DATABASE_TABLE_EVENTS, null, cv);
Log.d(TAG, "Inserted id " + Long.toString(id));
} catch (SQLiteConstraintException ex)
{
if (!(mDb.update(DATABASE_TABLE_EVENTS, cv, "_id=?", new String[] { Integer.toString(e.getEventId()) }) == 1))
throw ex;
}
// Save artists
ArtistHelper h = FindieDbHelper.getInstance().getArtistHelper();
h.saveArtists(e.getArtists());
h.mapArtistsToEvent(e.getArtists(), e);
if (saveVenue)
{
// Save venue
VenueHelper v = FindieDbHelper.getInstance().getVenueHelper();
v.saveVenues(new Venue[] { e.getVenue() });
}
}
mDb.setTransactionSuccessful();
}
catch (Exception ex)
{
ex.printStackTrace();
Log.e(TAG, "Can't insert: " + ex.toString());
}
finally
{
mDb.endTransaction();
}
}
}
public ArrayList<Event> findEvents(String search) {
ArrayList<Event> events = new ArrayList<Event>();
final Cursor c = mDb.query(DATABASE_TABLE_EVENTS, null, "name LIKE ?", new String[] { "%" + search + "%" }, null, null, null, null);
if (c != null && c.moveToFirst())
{
while (!c.isAfterLast())
{
Event e = readEvent(c);
events.add(e);
c.moveToNext();
}
}
if (c != null)
{
c.close();
}
return events;
}
}
|
package com.tu.common.service;
/**
* @Auther: tuyongjian
* @Date: 2019/12/6 10:11
* @Description:
*/
public interface IDubboService {
Integer add(int cost);
}
|
package au.gov.nsw.records.digitalarchive.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class LogoutAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)throws Exception
{
request.getSession().invalidate();
return mapping.findForward("logout");
}
}
|
package com.edasaki.rpg.dungeons;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.inventory.ItemStack;
import com.edasaki.rpg.items.EquipType;
import com.edasaki.rpg.items.RPGItem;
import com.edasaki.rpg.items.RandomItemGenerator;
public class DungeonReward {
public RPGItem item = null;
public int min, max;
public double baseChance;
private int diff;
public int tier = -1;
public DungeonReward(RPGItem item, int min, int max, double baseChance) {
this.item = item;
this.min = min;
this.max = max;
this.baseChance = baseChance;
this.diff = max - min;
}
public DungeonReward(int tier, int min, int max, double baseChance) {
this.tier = tier;
this.min = min;
this.max = max;
this.baseChance = baseChance;
this.diff = max - min;
}
private ItemStack getRoll() {
if (item != null)
return item.generate();
if (tier >= 1 && tier <= 5)
return RandomItemGenerator.generateEquip(EquipType.random(), tier);
try {
throw new Exception("Error: DungeonReward roll: " + item + ", " + tier);
} catch (Exception e) {
e.printStackTrace();
}
return RandomItemGenerator.generateEquip(EquipType.random(), 1);
}
public List<ItemStack> roll() {
ArrayList<ItemStack> arr = new ArrayList<ItemStack>();
for (int k = 0; k < min; k++) {
if (Math.random() < baseChance)
arr.add(getRoll());
}
double curr = baseChance;
for (int k = 0; k < diff; k++) {
if (Math.random() < curr) {
arr.add(getRoll());
}
curr *= 0.85;
}
return arr;
}
}
|
package ua.epam.course.java.block16;
import java.util.ArrayList;
import java.util.Arrays;
public class Faculty extends Thread {
private static int count = 0;
private int number;
private ArrayList<Student.specialities> specialities;
private ArrayList<Student> students = new ArrayList<>();
private int enterGroupSise;
private int interval;
private Queue queue;
/**
* @param enterGroupSise
* @param interval
*/
public Faculty(Student.specialities[] specialities, int enterGroupSise, int interval, Queue queue) {
this.specialities = new ArrayList<>(Arrays.asList(specialities));
this.enterGroupSise = enterGroupSise;
this.interval = interval;
this.queue = queue;
number = count++;
}
public String[] print() {
ArrayList<String> students = new ArrayList<>();
for (Student i: this.students) {
students.add(i.toString());
}
return (String[]) students.toArray();
}
public int countStudents() {
return students.size();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Faculty #" + number;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
while (!isInterrupted() && queue.isActual()) {
if (checkQueue()) {
synchronized (queue.lock) {
if (checkQueue()) {
for (int i = 0; i < enterGroupSise; i++) {
Student student = queue.getFirstStudent();
students.add(student);
View.getInstance().Print(student + " goes to " + toString());
}
}
}
}
try {
sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* @return
*/
private boolean checkQueue() {
synchronized (queue.lock) {
boolean validQueue = true;
if (queue.getSize() >= enterGroupSise) {
for (int i = 0; i < enterGroupSise; i++) {
if (!checkSpeciality(queue.getSpeciality(i))) {
validQueue = false;
break;
}
}
} else {
validQueue = false;
}
return validQueue;
}
}
private boolean checkSpeciality(Student.specialities speciality) {
for (Student.specialities i: specialities) {
if (speciality.equals(i))
{
return true;
}
}
return false;
}
}
|
package services;
import domain.Chef;
public interface ChefService extends Service<Chef, Long>{
}
|
package com.proyecto.ui.controller;
import javax.servlet.http.HttpServletRequest;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Button;
import org.zkoss.zul.Tabbox;
import com.proyecto.ui.components.MenuComponent;
@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class PrincipalController extends SelectorComposer<Component> {
private static final long serialVersionUID = 282567138990219970L;
@Wire
private Button btnSalir;
@Wire
private Tabbox tbxDestinoZul;
@Wire
private MenuComponent meu;
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
meu.menuComponent(tbxDestinoZul);
}
@Listen("onClick=#btnSalir")
public void salir() {
Executions.sendRedirect("/login.zul");
((HttpServletRequest)Executions.getCurrent().getNativeRequest()).getSession().invalidate();
}
}
|
package example.lgcode.launchstatus.dtos;
import com.google.gson.annotations.SerializedName;
import org.joda.time.DateTime;
import java.io.Serializable;
import java.util.List;
/**
* Created by leojg on 1/20/17.
*/
public class LaunchDTO implements Serializable {
@SerializedName("id")
private Integer id;
@SerializedName("name")
private String name;
@SerializedName("wsstamp")
private DateTime windowStart;
@SerializedName("westamp")
private DateTime windowEnd;
@SerializedName("location")
private LocationDTO location;
@SerializedName("rocket")
private RocketDTO rocket;
@SerializedName("status")
private Integer status;
@SerializedName("missions")
private List<MissionDTO> missions;
@SerializedName("vidURLs")
private List<String> vidURLs;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DateTime getWindowStart() {
return windowStart;
}
public void setWindowStart(DateTime windowStart) {
this.windowStart = windowStart;
}
public DateTime getWindowEnd() {
return windowEnd;
}
public void setWindowEnd(DateTime windowEnd) {
this.windowEnd = windowEnd;
}
public RocketDTO getRocket() {
return rocket;
}
public void setRocket(RocketDTO rocket) {
this.rocket = rocket;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public LocationDTO getLocation() {
return location;
}
public void setLocation(LocationDTO location) {
this.location = location;
}
public List<MissionDTO> getMissions() {
return missions;
}
public void setMissions(List<MissionDTO> missions) {
this.missions = missions;
}
public List<String> getVidURLs() {
return vidURLs;
}
public void setVidURLs(List<String> vidURLs) {
this.vidURLs = vidURLs;
}
}
|
package hu.alkfejl.utils;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import org.apache.commons.io.FileUtils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
public class Utils {
public static void showWarning(String message) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(null);
alert.setContentText(message);
alert.showAndWait();
}
public static String encodeBase64(File file) {
try {
return Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(file));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static Image decodeBase64(String string) {
if (string != null) {
try {
byte[] arr = Base64.getDecoder().decode(string);
File out = new File("img.png");
FileUtils.writeByteArrayToFile(out, arr);
return new Image(out.toURI().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
|
package formation.formation.service.rest;
import formation.domain.FormulaireReponses;
import formation.formation.service.itf.CustomerServiceItf;
import formation.formation.service.itf.FormulaireReponsesItf;
import javax.ejb.EJB;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
/**
* Created by victor on 12/12/2015.
*/
@Path("/formulaireReponses")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class FormulaireReponsesRestService {
@EJB
FormulaireReponsesItf service;
@GET
@Path("/{id}")
public Response get(@PathParam("id")Long id){
FormulaireReponses fr = service.get(id);
if(fr == null){
throw new NotFoundException("FormulaireReponses is not found");
}
return Response.ok(fr).build();
}
@POST
public Response create(FormulaireReponses formulaireReponses) throws Exception{
FormulaireReponses fr = service.create(formulaireReponses);
return Response.created(new URI("formulaireReponses/"+fr.getIdFormulaire())).build();
}
}
|
/**
* Please modify this class to meet your needs
* This class is not complete
*/
package com.wirelesscar.dynafleet.api;
import java.util.logging.Logger;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by Apache CXF 2.7.18
* 2017-06-30T14:30:13.624-05:00
* Generated source version: 2.7.18
*
*/
@javax.jws.WebService(
serviceName = "DynafleetAPI",
portName = "ServicePlanServicePort",
targetNamespace = "http://wirelesscar.com/dynafleet/api",
wsdlLocation = "https://api-preprod.dynafleetonline.com/wsdl",
endpointInterface = "com.wirelesscar.dynafleet.api.ServicePlanService")
public class ServicePlanServiceImpl implements ServicePlanService {
private static final Logger LOG = Logger.getLogger(ServicePlanServiceImpl.class.getName());
/* (non-Javadoc)
* @see com.wirelesscar.dynafleet.api.ServicePlanService#getServicePlan(com.wirelesscar.dynafleet.api.types.ApiServicePlanGetServicePlanTO apiServicePlanGetServicePlanTO1 )*
*/
public com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryArrayTO getServicePlan(com.wirelesscar.dynafleet.api.types.ApiServicePlanGetServicePlanTO apiServicePlanGetServicePlanTO1) throws DynafleetAPIException {
LOG.info("Executing operation getServicePlan");
System.out.println(apiServicePlanGetServicePlanTO1);
try {
com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryArrayTO _return = new com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryArrayTO();
java.util.List<com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryTO> _returnArray = new java.util.ArrayList<com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryTO>();
com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryTO _returnArrayVal1 = new com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryTO();
_returnArrayVal1.setHasOdometerAlert(true);
_returnArrayVal1.setHasOverdueAlert(true);
com.wirelesscar.dynafleet.api.types.ApiLong _returnArrayVal1Mileage = new com.wirelesscar.dynafleet.api.types.ApiLong();
_returnArrayVal1Mileage.setValue(3867317938438743357l);
_returnArrayVal1.setMileage(_returnArrayVal1Mileage);
_returnArrayVal1.setOperation("Operation-835754380");
com.wirelesscar.dynafleet.api.types.ApiDate _returnArrayVal1ServiceDate = new com.wirelesscar.dynafleet.api.types.ApiDate();
_returnArrayVal1ServiceDate.setValue(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-06-30T14:30:13.628-05:00"));
_returnArrayVal1.setServiceDate(_returnArrayVal1ServiceDate);
com.wirelesscar.dynafleet.api.types.ApiLong _returnArrayVal1ServicePlanEntryId = new com.wirelesscar.dynafleet.api.types.ApiLong();
_returnArrayVal1ServicePlanEntryId.setValue(-3364359255179894601l);
_returnArrayVal1.setServicePlanEntryId(_returnArrayVal1ServicePlanEntryId);
_returnArrayVal1.setStatus("Status-1701995092");
com.wirelesscar.dynafleet.api.types.ApiVehicleId _returnArrayVal1VehicleId = new com.wirelesscar.dynafleet.api.types.ApiVehicleId();
_returnArrayVal1VehicleId.setId(-1581120304627950185l);
_returnArrayVal1.setVehicleId(_returnArrayVal1VehicleId);
_returnArrayVal1.setVospCode("VospCode-791564356");
_returnArrayVal1.setVospOriginated(true);
_returnArray.add(_returnArrayVal1);
_return.getArray().addAll(_returnArray);
return _return;
} catch (java.lang.Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new DynafleetAPIException("DynafleetAPIException...");
}
/* (non-Javadoc)
* @see com.wirelesscar.dynafleet.api.ServicePlanService#getDeletedServicePlans(com.wirelesscar.dynafleet.api.types.ApiSessionId apiSessionId1 )*
*/
public com.wirelesscar.dynafleet.api.types.ApiLongArrayTO getDeletedServicePlans(com.wirelesscar.dynafleet.api.types.ApiSessionId apiSessionId1) throws DynafleetAPIException {
LOG.info("Executing operation getDeletedServicePlans");
System.out.println(apiSessionId1);
try {
com.wirelesscar.dynafleet.api.types.ApiLongArrayTO _return = new com.wirelesscar.dynafleet.api.types.ApiLongArrayTO();
java.util.List<com.wirelesscar.dynafleet.api.types.ApiLong> _returnArray = new java.util.ArrayList<com.wirelesscar.dynafleet.api.types.ApiLong>();
com.wirelesscar.dynafleet.api.types.ApiLong _returnArrayVal1 = new com.wirelesscar.dynafleet.api.types.ApiLong();
_returnArrayVal1.setValue(-1604004820273835123l);
_returnArray.add(_returnArrayVal1);
_return.getArray().addAll(_returnArray);
return _return;
} catch (java.lang.Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new DynafleetAPIException("DynafleetAPIException...");
}
/* (non-Javadoc)
* @see com.wirelesscar.dynafleet.api.ServicePlanService#getModifiedServicePlans(com.wirelesscar.dynafleet.api.types.ApiSessionId apiSessionId1 )*
*/
public com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryArrayTO getModifiedServicePlans(com.wirelesscar.dynafleet.api.types.ApiSessionId apiSessionId1) throws DynafleetAPIException {
LOG.info("Executing operation getModifiedServicePlans");
System.out.println(apiSessionId1);
try {
com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryArrayTO _return = new com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryArrayTO();
java.util.List<com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryTO> _returnArray = new java.util.ArrayList<com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryTO>();
com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryTO _returnArrayVal1 = new com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryTO();
_returnArrayVal1.setHasOdometerAlert(false);
_returnArrayVal1.setHasOverdueAlert(true);
com.wirelesscar.dynafleet.api.types.ApiLong _returnArrayVal1Mileage = new com.wirelesscar.dynafleet.api.types.ApiLong();
_returnArrayVal1Mileage.setValue(3205035217122504580l);
_returnArrayVal1.setMileage(_returnArrayVal1Mileage);
_returnArrayVal1.setOperation("Operation-1804896017");
com.wirelesscar.dynafleet.api.types.ApiDate _returnArrayVal1ServiceDate = new com.wirelesscar.dynafleet.api.types.ApiDate();
_returnArrayVal1ServiceDate.setValue(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-06-30T14:30:13.629-05:00"));
_returnArrayVal1.setServiceDate(_returnArrayVal1ServiceDate);
com.wirelesscar.dynafleet.api.types.ApiLong _returnArrayVal1ServicePlanEntryId = new com.wirelesscar.dynafleet.api.types.ApiLong();
_returnArrayVal1ServicePlanEntryId.setValue(-6635879755415330860l);
_returnArrayVal1.setServicePlanEntryId(_returnArrayVal1ServicePlanEntryId);
_returnArrayVal1.setStatus("Status2078223686");
com.wirelesscar.dynafleet.api.types.ApiVehicleId _returnArrayVal1VehicleId = new com.wirelesscar.dynafleet.api.types.ApiVehicleId();
_returnArrayVal1VehicleId.setId(2393051614170715542l);
_returnArrayVal1.setVehicleId(_returnArrayVal1VehicleId);
_returnArrayVal1.setVospCode("VospCode-827503535");
_returnArrayVal1.setVospOriginated(true);
_returnArray.add(_returnArrayVal1);
_return.getArray().addAll(_returnArray);
return _return;
} catch (java.lang.Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new DynafleetAPIException("DynafleetAPIException...");
}
}
|
package com.crmiguez.aixinainventory.service.itemtype;
import com.crmiguez.aixinainventory.entities.ItemType;
import java.util.List;
import java.util.Optional;
public interface IItemTypeService {
public List<ItemType> findAllItemTypes();
public Optional<ItemType> findItemTypeById(String itemTypeId);
public ItemType addItemType(ItemType itemType);
public ItemType updateItemType(ItemType itemTypeDetails, ItemType itemType);
public void deleteItemType (ItemType itemType);
}
|
package dev.fujioka.eltonleite.presentation.dto.order;
import java.time.LocalDateTime;
public class OrderResponseTO {
private Long id;
private LocalDateTime dateOrder;
private Long idUser;
public OrderResponseTO(Long id, LocalDateTime dateOrder, Long idUser) {
super();
this.id = id;
this.dateOrder = dateOrder;
this.idUser = idUser;
}
public Long getId() {
return id;
}
public LocalDateTime getDateOrder() {
return dateOrder;
}
public Long getIdUser() {
return idUser;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OrderResponseTO other = (OrderResponseTO) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
package com.awakenguys.kmitl.ladkrabangcountry.model;
import org.springframework.data.annotation.Id;
/**
* Created by Xync on 05-Nov-15.
*/
public class Bus_Line {
@Id
private String id;
private String line;
private String route;
public Bus_Line() {
}
public Bus_Line(String line, String route) {
this.line = line;
this.route = route;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
@Override
public String toString() {
return "Bus_Line{" +
"id='" + id + '\'' +
", line='" + line + '\'' +
", route='" + route + '\'' +
'}';
}
}
|
/*
* generated by Xtext
*/
package org.yazgel.snow.notation.text;
import org.eclipse.xtext.junit4.IInjectorProvider;
import com.google.inject.Injector;
public class SnowUiInjectorProvider implements IInjectorProvider {
@Override
public Injector getInjector() {
return org.yazgel.snow.notation.text.ui.internal.SnowActivator.getInstance().getInjector("org.yazgel.snow.notation.text.Snow");
}
}
|
import java.util.Scanner;
import java.util.Random;
public class Nim {
private Pile pileA;
private Pile pileB;
private Pile pileC;
private Scanner input;
private Random rnd;
// Default constructor, constructs the three piles
public Nim() {
pileA = new Pile();
pileB = new Pile();
pileC = new Pile();
}
// All the rules to handle user input
public boolean PlayerMove() {
input = new Scanner(System.in);
System.out.println("Select a pile: ");
String inp = input.next().toUpperCase();
boolean booleanflag=false;
if (inp.equals("A") || inp.equals("B") || inp.equals("C") ) {
if(inp.equals("A")) {
if(pileA.getSize() > 0) {
System.out.println("How many do you want to remove?");
int Amount = input.nextInt();
if(Amount>=1 && Amount<= pileA.getSize()) {
pileA.remove(Amount);
booleanflag = true;
return booleanflag;
}else {
System.out.println("Pick a number between 1 to "+ pileA.getSize());
// printPiles();
}
}else {
System.out.println("Pile a is empty, pick another");
// printPiles();
}
}else if(inp.equals("B") ) {
if( pileB.getSize() > 0) {
System.out.println("How many do you want to remove?");
int Amount = input.nextInt();
if(Amount>=1 && Amount<= pileB.getSize()) {
pileB.remove(Amount);
booleanflag = true;
return booleanflag;
}else {
System.out.println("Pick a number between 1 to "+ pileB.getSize());
// printPiles();
}
}else {
System.out.println("Pile b is empty, pick another");
// printPiles();
}
}else if (inp.equals("C") ) {
if (pileC.getSize() > 0) {
System.out.println("How many do you want to remove?");
int Amount = input.nextInt();
if(Amount>=1 && Amount<= pileC.getSize()) {
pileC.remove(Amount);
booleanflag = true;
return booleanflag;
}else {
System.out.println("Pick a number between 1 to "+ pileC.getSize());
// printPiles();
}
}else {
System.out.println("Pile c is empty, pick another");
// printPiles();
}
}
}else {
System.out.println("Invalid pile letter, select a, b or c");
// printPiles();
}
return booleanflag;
}
// Computer move if done
public void computerMove() {
rnd = new Random();
int randomMove;
char computerChoice;
//when all pile are not zero
if (pileA.getSize()!=0 && pileB.getSize()!=0 && pileC.getSize()!=0) {
String A= "ABC";
computerChoice = A.charAt(rnd.nextInt(3));
if (computerChoice == 'A') {
randomMove=1+ rnd.nextInt(pileA.getSize());
pileA.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}else if (computerChoice == 'B') {
randomMove=1+ rnd.nextInt(pileB.getSize() );
pileB.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}else if (computerChoice == 'C') {
randomMove=1+ rnd.nextInt(pileC.getSize() );
pileC.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}
//when AB are not zero
}else if (pileA.getSize()!=0 && pileB.getSize()!=0) {
String B="AB";
computerChoice = B.charAt(rnd.nextInt(2));
if (computerChoice == 'A') {
randomMove=1+ rnd.nextInt(pileA.getSize() );
pileA.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}else if (computerChoice == 'B') {
randomMove=1+ rnd.nextInt(pileB.getSize() );
pileB.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}
//when BC are not zero
}else if (pileB.getSize()!=0 && pileC.getSize()!=0) {
String C ="BC";
computerChoice = C.charAt(rnd.nextInt(2));
if (computerChoice == 'B') {
randomMove=1+ rnd.nextInt(pileB.getSize() );
pileB.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}else if (computerChoice == 'C') {
randomMove=1+ rnd.nextInt(pileC.getSize() ) ;
pileC.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}
//when AC are not zero
}else if (pileA.getSize()!=0 && pileB.getSize()!=0) {
String D = "AC";
computerChoice = D.charAt(rnd.nextInt(2));
if (computerChoice == 'A') {
randomMove= 1+rnd.nextInt(pileA.getSize() );
pileA.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}else if (computerChoice == 'B') {
randomMove=1+ rnd.nextInt(pileB.getSize() );
pileB.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}
//when single pile are not zero
}else if (pileA.getSize()!=0) {
computerChoice = 'A';
randomMove=rnd.nextInt(pileA.getSize() )+1;
pileA.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}else if (pileB.getSize()!=0) {
computerChoice = 'B';
randomMove= rnd.nextInt(pileB.getSize() )+1;
pileB.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}else if (pileC.getSize()!=0) {
computerChoice = 'C';
randomMove= rnd.nextInt(pileC.getSize() )+1;
pileC.remove(randomMove);
System.out.println("Computer takes "+ randomMove + " from pile "+ computerChoice);
}
}
// Is the game done?
public boolean done() {
boolean Done = false;
if (pileA.getSize() ==0 && pileB.getSize()==0 && pileC.getSize()==0) {
Done = true;
}
return Done;
}
// Print the current state of the piles
public void printPiles() {
System.out.println("\tA\t\tB\t\tC");
System.out.println("\t"+pileA.getSize()+"\t\t"+pileB.getSize()+"\t\t"+pileC.getSize());
}
}
|
package com.bag.core.config;
import com.mongodb.Mongo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.net.UnknownHostException;
/**
* Created by johnny on 25/11/15.
*/
@Configuration
public class DatabaseConfig {
@Bean
public MongoTemplate getTemplate() throws UnknownHostException {
return new MongoTemplate(getMongo(), "pentobag");
}
private Mongo getMongo() throws UnknownHostException {
return new Mongo("localhost");
}
}
|
package varTypes;
public class TipoPez {
int tipopez_id;
String descripcion;
float phMin, phMax, temMin, temMax;
public TipoPez(int tipopez_id, String descripcion, float phMin, float phMax, float temMin, float temMax) {
this.tipopez_id = tipopez_id;
this.descripcion = descripcion;
this.phMin = phMin;
this.phMax = phMax;
this.temMin = temMin;
this.temMax = temMax;
}
public TipoPez(String descripcion, float phMin, float phMax, float temMin, float temMax) {
this.descripcion = descripcion;
this.phMin = phMin;
this.phMax = phMax;
this.temMin = temMin;
this.temMax = temMax;
}
public int getTipopez_id() {
return tipopez_id;
}
public void setTipopez_id(int tipopez_id) {
this.tipopez_id = tipopez_id;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public float getPhMin() {
return phMin;
}
public void setPhMin(float phMin) {
this.phMin = phMin;
}
public float getPhMax() {
return phMax;
}
public void setPhMax(float phMax) {
this.phMax = phMax;
}
public float getTemMin() {
return temMin;
}
public void setTemMin(float temMin) {
this.temMin = temMin;
}
public float getTemMax() {
return temMax;
}
public void setTemMax(float temMax) {
this.temMax = temMax;
}
}
|
/**
*
*/
/**
* @author Aloy
*
*/
package Control.output;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.