text
stringlengths 10
2.72M
|
|---|
package com.hcl.neo.eloader.common;
@SuppressWarnings("rawtypes")
public class Logger extends org.apache.log4j.Logger{
protected Logger(String name) {
super(name);
}
public static void debug(Class clazz, Object message){
getLogger(clazz).debug(message);
}
public static void info(Class clazz, Object message){
getLogger(clazz).info(message);
}
public static void warn(Class clazz, Object message){
getLogger(clazz).warn(message);
}
public static void error(Class clazz, Object message){
getLogger(clazz).error(message);
}
public static void error(Class clazz, Object message, Throwable t){
getLogger(clazz).error(message, t);
}
public static void error(Class clazz, Throwable t){
getLogger(clazz).error(t.getMessage(), t);
}
}
|
package com.gonzajf.spring.masteringSpring.config;
import java.time.LocalDate;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.util.UrlPathHelper;
import com.gonzajf.spring.masteringSpring.util.LocalDateFormatter;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableWebMvc
@EnableSwagger2
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatterForFieldType(LocalDate.class, new LocalDateFormatter());
}
@Bean
public LocaleResolver localeResolver() {
return new SessionLocaleResolver();
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> container.addErrorPages(new ErrorPage(MultipartException.class, "/uploadError"));
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
configurer.setUseRegisteredSuffixPatternMatch(true);
}
@Bean
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(path -> path.startsWith("/api"))
.build();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
|
/**
* project name:ach
* file name:MsgTmplConstant
* package name:com.cdkj.common.constant
* date:2017-08-25 15:43
* author:yw
* Copyright (c) CD Technology Co.,Ltd. All rights reserved.
*/
package com.cdkj.constant;
/**
* description: //TODO <br>
* date: 2017-08-25 15:43
*
* @author yw
* @version 1.0
* @since JDK 1.8
*/
public interface MsgTmplConstant {
/**
* 验证码短信模板
*/
String MSG_TMPL_REG_LOG_IDENTIFY_CODE = "MSG_TMPL_REG_LOG_IDENTIFY_CODE";
}
|
package com.quickdoodle.trainer;
import java.util.LinkedHashMap;
import com.quickdoodle.model.activationfunction.DataUtils;
public class Test {
public static void main(String[] args) {
//Input schedule
LinkedHashMap<Integer, Float> schedule = new LinkedHashMap<Integer, Float>();
schedule.put(1, 0.1f);
schedule.put(3, 0.078f);
schedule.put(5, 0.06f);
schedule.put(7, 0.035f);
schedule.put(8, 0.018f);
ModelTrainer trainer = new ModelTrainer();
//Max epoch
trainer.setMaxEpoch(10);
trainer.setSchedule(schedule);
String[] objectList = {
"0 bus", "1 cat", "2 carrot", "3 diamond", "4 fish",
"5 flower"};
//Input konfigurasi layer
//100, 28, 299
trainer.initializeModel(784, new int[]{1500}, 6);
//trainer.initializeModel("String")
//Ukuran batch dan rasio
System.out.println(trainer.initializeDataset(objectList, 40000, 0.9f));
trainer.train(null);
//Run dan save input nama
/*DataUtils.saveText("./model4"
+ ""
+ ".csv", trainer.exportModel());
/*Dataset dataset = new Dataset(objectList, 10, 0.8f);
TrainableModel m = new TrainableModel(784, new int[]{1000}, 10);
ArrayList<Doodle> train = dataset.getTrainDatas();
Doodle data = train.get(0);
m.train(data.getPixelValues(), data.getTarget());
double[] result = m.guess(data.getPixelValues());
//m.train(new double[]{10}, new double[] {1, 0});
System.out.println(Arrays.toString(result));
int[] hiddenLayers = {10};
TrainableModel nn = new TrainableModel(2, hiddenLayers, 2);
nn.setLearningRate(0.03);
double[][] input = {
{1.0, 90},
{190, 1.0},
{120, 1.0},
{6.0, 200},
{5.0, 90},
{80, 2.0},
{98, 1.0},
{1.0, 100}};
double[][] target = {
{0.0, 1.0},
{1.0, 0.0},
{1.0, 0.0},
{0.0, 1.0},
{0.0, 1.0},
{1.0, 0.0},
{1.0, 0.0},
{0.0, 1.0}};
for(int i = 0; i < 100; i++) {
for(int j = 0; i < input.length; i++)
nn.train(input[j], target[j]);
nn.setLearningRate(nn.getLearningRate() * 0.99);
}
double[][] test = {
{1.0, 190},
{190, 1.0},
{120, 1.0}};
String model = nn.export();
for(int i = 0; i < test.length; i++) {
double[] result = nn.guess(test[i]);
for(int j = 0; j < result.length; j++)
System.out.print(result[j] +" ");
System.out.println();
}
System.out.println();
Model m = new Model(model);
System.out.println(m.export());
for(int i = 0; i < test.length; i++) {
double[] result = m.guess(test[i]);
for(int j = 0; j < result.length; j++)
System.out.print(result[j] +" ");
System.out.println();
}*/
}
}
|
package com.jlmcdeveloper.notes.ui.login;
import com.jlmcdeveloper.notes.ui.base.MvpView;
public interface LoginMvpView extends MvpView {
void finishedAnimation(String info);
void openMainActivity();
}
|
package com.stylefeng.guns.rest.film.bean.rebuild;
import com.stylefeng.guns.rest.film.bean.MtimeFilmT;
/**
* @Author: Qiu
* @Date: 2019/6/5 17:02
*/
public class BoxRankFilm extends MtimeFilmT {
private int filmId;
private int boxNum;
public BoxRankFilm() {
}
public BoxRankFilm(int filmId, String imgAddress, String filmName, int boxNum) {
this.setFilmId(filmId);
this.setImgAddress(imgAddress);
this.setFilmName(filmName);
this.setBoxNum(boxNum);
}
public int getBoxNum() {
return boxNum;
}
public void setBoxNum(int boxNum) {
this.boxNum = boxNum;
}
public int getFilmId() {
return filmId;
}
public void setFilmId(int filmId) {
this.filmId = filmId;
}
@Override
public String getImgAddress() {
return super.getImgAddress();
}
@Override
public String getFilmName() {
return super.getFilmName();
}
}
|
package com.quaspecsystems.payspec.persistence.repository;
import java.util.Set;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import com.quaspecsystems.payspec.persistence.domain.Menu;
@Transactional
public interface MenuRepository extends CrudRepository<Menu, Long> {
@Query("select c from Menu as c where c.profile.id=?1 order by c.displayIndex asc")
Set<Menu> findAllActiveMenus(Long profleId);
}
|
package de.kfs.db;
import javafx.stage.Stage;
/**
* Factory for use of injecting SceneManger via Google guice
*/
public interface SceneManagerFactory {
/**
* Creates instance of the SceneManager
*
* @param primaryStage Stage used by JavaFX application
* @return SceneManger for main application
*/
SceneManager create(Stage primaryStage);
}
|
package com.staniul.teamspeak.modules.adminlists;
import com.staniul.teamspeak.commands.CommandResponse;
import com.staniul.teamspeak.commands.Teamspeak3Command;
import com.staniul.teamspeak.query.Client;
import com.staniul.teamspeak.query.ClientDatabase;
import com.staniul.teamspeak.query.Query;
import com.staniul.teamspeak.query.QueryException;
import com.staniul.teamspeak.security.clientaccesscheck.ClientGroupAccess;
import com.staniul.xmlconfig.CustomXMLConfiguration;
import com.staniul.xmlconfig.annotations.UseConfig;
import com.staniul.xmlconfig.annotations.WireConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
@UseConfig("modules/afl.xml")
public class AdminOfflineList {
private static Logger log = LogManager.getLogger(AdminOfflineList.class);
@WireConfig
private CustomXMLConfiguration config;
private final Query query;
private List<Servergroup2> servergroup2s;
@Autowired
public AdminOfflineList(Query query) {
this.query = query;
}
@PostConstruct
private void init() {
servergroup2s = config.getClasses(Servergroup2.class, "groups.servergroup2");
}
@Teamspeak3Command("!refafl")
@ClientGroupAccess("servergroups.headadmins")
public CommandResponse refreshAdminOfflineList(Client client, String params) throws QueryException {
refreshAdminList();
return new CommandResponse(config.getString("commands.refafl[@response]"));
}
public void refreshAdminList() throws QueryException {
Map<Servergroup2, List<ClientDatabase>> data = new HashMap<>();
for (Servergroup2 servergroup2 : servergroup2s) {
data.put(servergroup2, !servergroup2.isSolo() ?
query.getClientDatabaseListInServergroup(servergroup2.getId()) :
query.getClientDatabaseListInServergroup(servergroup2.getId()).subList(0, 1)
);
}
refreshDisplay(data);
}
private void refreshDisplay(Map<Servergroup2, List<ClientDatabase>> data) throws QueryException {
int count = 0;
for (Map.Entry<Servergroup2, List<ClientDatabase>> entry : data.entrySet()) {
count += entry.getValue().size();
}
StringBuilder description = new StringBuilder();
for (Servergroup2 servergroup2 : servergroup2s) {
description.append("[IMG]").append(servergroup2.getIcon()).append("[/IMG]")
.append(config.getString("display[@header]").replace("$HEADER$", servergroup2.getName()))
.append("\n");
data.get(servergroup2).sort(Comparator.comparing(ClientDatabase::getNickname, Comparator.comparing(String::toLowerCase)));
for (ClientDatabase admin : data.get(servergroup2)) {
description.append(config.getString("display[@listsign]"))
.append(config.getString("display[@entry]")
.replace("$NICKNAME$", admin.getNickname())
.replace("$UNIQUEID$", admin.getUniqueId()))
.append("\n");
}
description.append("\n");
}
description.append(config.getString("display[@count]").replace("%NUMBER%", Integer.toString(count))).append("\n");
query.channelChangeDescription(description.toString(), config.getInt("display[@id]"));
}
}
|
package seperate;
import java.util.*;
import com.opencsv.bean.CsvBindByName;
public class UserModel {
@CsvBindByName
private String ProgramName;
@CsvBindByName
private String Location;
@CsvBindByName
private String PhoneNumber;
@CsvBindByName
private String Website;
@CsvBindByName
private String MealInformation;
/**
* Gets the name of the hero
*
* @return the hero name of this UserModel
*/
public String getProgramName() {
return this.ProgramName;
}
public void setProgramName(String name) {
this.ProgramName = name;
}
public String getLocation() {
return this.Location;
}
public void setLocation(String name) {
this.Location = name;
}
public String getPhoneNumber() {
return this.PhoneNumber;
}
public void setPhoneNumber(String name) {
this.PhoneNumber = name;
}
public String getWebsite() {
return this.Website;
}
public void setWebsite(String name) {
this.Website = name;
}
/**
* Gets the name of the book
*
* @return the book name of this UserModel
*/
public String getMealInformation() {
return this.MealInformation;
}
public void setMealInformation(String mealInfo) {
this.MealInformation = mealInfo;
}
}
|
package Tutorial.P3_ActorTool.S4_FSM_State.Buncher;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.LinkedList;
import static Tutorial.P3_ActorTool.S4_FSM_State.Buncher.Message.*;
import static Tutorial.P3_ActorTool.S4_FSM_State.Buncher.Message.Flush.*;
/**
* Created by lam.nm on 6/12/2017.
*/
class BuncherTest {
private LoggingAdapter logger;
static ActorSystem system;
@BeforeAll
public static void setup() {
system = ActorSystem.create("BuncherTest");
Logging.getLogger(system, BuncherTest.class);
}
@Test
public void testBuncher() throws Exception {
final ActorRef buncher = system.actorOf(Props.create(Buncher.class), "buncher");
final ActorRef probe = system.actorOf(Props.create(Probe.class), "probe");
buncher.tell(new SetTarget(probe), probe);
buncher.tell(new Queue(42), probe);
buncher.tell(new Queue(43), probe);
LinkedList<Object> lstObj1 = new LinkedList<>();
lstObj1.add(42);
lstObj1.add(43);
Assert.assertEquals(lstObj1.size(), 2);
buncher.tell(new Queue(44), probe);
buncher.tell(Flush, probe);
buncher.tell(new Queue(45), probe);
LinkedList<Object> lstObj2 = new LinkedList<>();
lstObj2.add(44);
Assert.assertEquals(lstObj2.size(), 1);
LinkedList<Object> lstObj3 = new LinkedList<>();
lstObj3.add(45);
Assert.assertEquals(lstObj3.size(), 1);
Thread.sleep(5000);
system.terminate();
}
}
|
/*
* 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 search;
import BDD.Requete;
import Entite.Classe;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author seck
*/
public class SearchClasse {
Requete requete = new Requete();
public Classe RechercherParId(int i) {
String req = "SELECT * FROM classe WHERE id_Classe="+i;
Classe c = new Classe();
ResultSet res = requete.exeRead(req);
try {
while (res.next()) {
c.setIdClasse(res.getInt(1));
c.setNomClasse((res.getString(2)));
c.setAnneeScolaire(res.getString(3));
}
} catch (SQLException ex) {
Logger.getLogger(SearchClasse.class.getName()).log(Level.SEVERE, null, ex);
}
return c;
}
public ArrayList<Classe> RechercherParNomClasse(String classe) {
String req = "SELECT * FROM classe WHERE nom_classe='" + classe + "'";
ArrayList<Classe> liste = new ArrayList<>();
Classe c = new Classe();
ResultSet res = requete.exeRead(req);
try {
while (res.next()) {
c.setIdClasse(res.getInt(1));
c.setNomClasse((res.getString(2)));
c.setAnneeScolaire(res.getString(3));
liste.add(c);
}
} catch (SQLException ex) {
Logger.getLogger(SearchClasse.class.getName()).log(Level.SEVERE, null, ex);
}
return liste;
}
public ArrayList<Classe> RechercherParAnnee(String annee) {
String req = "SELECT * FROM classe WHERE annee_scolaire='" + annee + "'";
ArrayList<Classe> liste = new ArrayList<>();
Classe c = new Classe();
ResultSet res = requete.exeRead(req);
try {
while (res.next()) {
c.setIdClasse(res.getInt(1));
c.setNomClasse((res.getString(2)));
c.setAnneeScolaire(res.getString(3));
liste.add(c);
}
} catch (SQLException ex) {
Logger.getLogger(SearchClasse.class.getName()).log(Level.SEVERE, null, ex);
}
return liste;
}
}
|
package com.lenovohit.ssm.payment.model.si;
public class SIPrePayRequest {
}
|
package com.codeclan.coursebooker.coursebooker.projections;
import com.codeclan.coursebooker.coursebooker.models.Booking;
import com.codeclan.coursebooker.coursebooker.models.Course;
import com.codeclan.coursebooker.coursebooker.models.Customer;
import org.springframework.data.rest.core.config.Projection;
@Projection(name = "embedBookingIntoAnything", types = Booking.class)
public interface EmbedBookingIntoAnything {
String getDate();
Course getCourse();
Customer getCustomer();
}
|
package model;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Cargo {
private StringProperty id;
private StringProperty nombre;
public Cargo(String nombre) {
this.nombre = new SimpleStringProperty("nombre");
}
public Cargo( String id, String nombre) {
this.nombre = new SimpleStringProperty(nombre);
this.id = new SimpleStringProperty(id);
}
/**
* @return the id
*/
public StringProperty getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(StringProperty id) {
this.id = id;
}
/**
* @return the nombre
*/
public StringProperty getNombre() {
return nombre;
}
/**
* @param nombre the nombre to set
*/
public void setNombre(StringProperty nombre) {
this.nombre = nombre;
}
}
|
package ru.atott.combiq.web.controller;
import org.springframework.stereotype.Controller;
@Controller
public class PromoController {
}
|
package br.com.vitormarcal.gestao_consulta.auth;
import br.com.vitormarcal.gestao_consulta.auth.model.ERole;
import br.com.vitormarcal.gestao_consulta.auth.model.Role;
import br.com.vitormarcal.gestao_consulta.auth.model.User;
import br.com.vitormarcal.gestao_consulta.auth.repositorio.RoleRepositorio;
import br.com.vitormarcal.gestao_consulta.auth.repositorio.UserRepositorio;
import br.com.vitormarcal.gestao_consulta.auth.request.LoginRequest;
import br.com.vitormarcal.gestao_consulta.auth.request.SignupRequest;
import br.com.vitormarcal.gestao_consulta.auth.response.JwtResponse;
import br.com.vitormarcal.gestao_consulta.chat.response.MessageResponse;
import br.com.vitormarcal.gestao_consulta.security.jwt.JwtUtils;
import br.com.vitormarcal.gestao_consulta.security.services.UserDetailsImpl;
import br.com.vitormarcal.gestao_consulta.tecnico.model.Tecnico;
import br.com.vitormarcal.gestao_consulta.tecnico.repositorio.TecnicoRepositorio;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
TecnicoRepositorio tecnicoRepositorio;
@Autowired
UserRepositorio userRepositorio;
@Autowired
RoleRepositorio roleRepositorio;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
Long tecnicoId = tecnicoRepositorio.findByUserId(userDetails.getId()).map(Tecnico::getId).orElse(null);
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
userDetails.getCadastroCompleto(),
roles,tecnicoId));
}
@PostMapping("/signup")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
if (userRepositorio.existsByUsername(signUpRequest.getUsername())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Username já está em uso!"));
}
if (userRepositorio.existsByEmail(signUpRequest.getEmail())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email já está em uso!"));
}
// Create new user's account
User user = new User(signUpRequest.getUsername(),
signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()));
user.setNome(signUpRequest.getNome());
user.setTelefone(signUpRequest.getTelefone());
Set<String> strRoles = signUpRequest.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepositorio.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role não encontrada."));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepositorio.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role não encontrada."));
roles.add(adminRole);
user.setCadastroCompleto(true);
break;
case "tecnico":
Role modRole = roleRepositorio.findByName(ERole.ROLE_TECNICO)
.orElseThrow(() -> new RuntimeException("Error: Role não encontrada."));
roles.add(modRole);
user.setCadastroCompleto(false);
break;
default:
Role userRole = roleRepositorio.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role não encontrada."));
roles.add(userRole);
user.setCadastroCompleto(true);
}
});
}
user.setRoles(roles);
userRepositorio.save(user);
return ResponseEntity.ok(new MessageResponse("Usuário registrado com sucesso!"));
}
}
|
package cn.Thread;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* 使用Callable 接收返回值
* @author Administrator
*
*/
class MyThread4 implements Runnable, Callable<String>{ //多线程操作类
private int ticket = 10; //定义的类中属性
@Override
public String call() throws Exception{
for(int x = 0 ; x <100;x++){
if(this.ticket > 0){
System.out.println("买票:ticket=" + this.ticket--);
}
}
return "票已卖光";
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
public class TextDemo4 {
public static void main(String[] args) throws Exception {
MyThread4 my1 = new MyThread4();
MyThread4 my2 = new MyThread4();
FutureTask<String> task1 = new FutureTask<String>(my1); //目的是取得call()返回结果
FutureTask<String> task2 = new FutureTask<String>(my2);
//FutureTask是Runnable接口子类,所以可以使用Thread类的构造来接收task对象
//启动线程
new Thread(task1).start();
new Thread(task2).start();
//多线程执行完毕后可以取得内容,依靠FutureTask的父接口Future中的get()方法完成
System.out.println("A线程的返回结果:" + task1.get());
System.out.println("B线程的返回结果:" + task2.get());
}
}
|
package com.citibank.ods.common.functionality;
import com.citibank.ods.common.functionality.valueobject.BaseFncVO;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* [Class description]
*
* @see package com.citibank.ods.common.functionality;
* @version 1.0
* @author bruno.zanetti,Mar 9, 2007
*
* <PRE>
*
* <U>Updated by: </U> <U>Description: </U>
*
* </PRE>
*/
public interface ODSHistoryDetailFnc
{
public void loadForConsult( BaseFncVO fncVO_ );
}
|
package ru.buryachenko.moviedescription.database;
import android.annotation.SuppressLint;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
import ru.buryachenko.moviedescription.api.MovieJson;
@Entity
public class MovieRecord {
@PrimaryKey
private Integer id;
private Double popularity;
private Integer voteCount;
private String posterPath;
private Boolean adult;
private String originalLanguage;
private String originalTitle;
private String title;
private Float voteAverage;
private String overview;
private String releaseDate;
private boolean liked;
@Ignore
private int usefulness;
public MovieRecord(MovieJson filmJson) {
title = filmJson.getTitle();
overview = filmJson.getOverview();
id = filmJson.getId();
posterPath = "https://image.tmdb.org/t/p/w500/" + filmJson.getPosterPath();
popularity = filmJson.getPopularity();
voteCount = filmJson.getVoteCount();
adult = filmJson.getAdult();
originalLanguage = filmJson.getOriginalLanguage();
originalTitle = filmJson.getOriginalTitle();
voteAverage = filmJson.getVoteAverage();
releaseDate = filmJson.getReleaseDate();
liked = false;
// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
// try {
// releaseDate = formatter.parse(filmJson.getReleaseDate());
// } catch (ParseException ignored) {}
}
public MovieRecord() {
}
public Integer getId() {
return id;
}
public Double getPopularity() {
return popularity;
}
public Integer getVoteCount() {
return voteCount;
}
public String getPosterPath() {
return posterPath;
}
public Boolean getAdult() {
return adult;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public String getOriginalTitle() {
return originalTitle;
}
public String getTitle() {
return title;
}
@SuppressLint("DefaultLocale")
public String getCompareFlag() {
return String.format("%4d", usefulness) + title;
}
public Float getVoteAverage() {
return voteAverage;
}
public String getOverview() {
return overview;
}
public String getReleaseDate() {
return releaseDate;
}
public void setPopularity(Double popularity) {
this.popularity = popularity;
}
public void setVoteCount(Integer voteCount) {
this.voteCount = voteCount;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public void setAdult(Boolean adult) {
this.adult = adult;
}
public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public void setTitle(String title) {
this.title = title;
}
public void setVoteAverage(Float voteAverage) {
this.voteAverage = voteAverage;
}
public void setOverview(String overview) {
this.overview = overview;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public void setId(Integer id) {
this.id = id;
}
public boolean isLiked() {
return liked;
}
public int getUsefulness() {
return usefulness;
}
public void setLiked(boolean liked) {
this.liked = liked;
}
public void setUsefulness(int usefulness) {
this.usefulness = usefulness;
}
}
|
package com.example.cropad;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ViewFlipper;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import static com.example.cropad.Constants.*;
public class fragment_market extends Fragment {
public Button log_out;
ViewFlipper v_flip;
public Button add_market;
public Button weather;
public Button inputform;
public Button marketplace;
public Button expertarticles;
private static final String PREF_NAME = "LOGIN";
public void flipperimage(String image) {
ImageView imgview = new ImageView(getContext());
// imgview.setBackgroundResource(image);
// Picasso.with(getApplicationContext()).load("http://10.0.4.196:5656/images/barley.jpg").into(imgview);
// Picasso.with(getApplicationContext()).load(URL_Image+image).into(imgview);
v_flip.addView(imgview);
v_flip.setInAnimation(getContext(), android.R.anim.slide_in_left);
v_flip.setOutAnimation(getContext(), android.R.anim.slide_out_right);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_market,container,false);
final SharedPreferences sharedpreferences = getActivity().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
marketplace = view.findViewById(R.id.nearbymarketplace);
marketplace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println("this is clicked");
Intent market = new Intent(getActivity(), Market_list.class);
startActivity(market);
}
});
add_market = view.findViewById(R.id.addmarket);
add_market.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent addmkt = new Intent(getContext(), add_market.class);
startActivity(addmkt);
}
});
// SimpleDateFormat sdf = new SimpleDateFormat("MM");
// String currentmonth = sdf.format(new Date());
// Integer currentmonthin = Integer.valueOf(currentmonth);
//
// int rabi[] = {R.drawable.jowar, R.drawable.wheat, R.drawable.peas};
// int kharif[] = {R.drawable.sugar, R.drawable.jowar};
//
// v_flip = (ViewFlipper) view.findViewById(R.id.flipper);
//
// RequestQueue requestQueue = Volley.newRequestQueue(getContext());
// JSONObject jsonObject = new JSONObject();
//
// final String requestBody = jsonObject.toString();
//
// ConnectionManager.sendData(requestBody, requestQueue, URL + "/image", new ConnectionManager.VolleyCallback() {
// @Override
// public void onSuccessResponse(String result) {
// JSONObject jsonObject = null;
// try {
// jsonObject = new JSONObject(result);
// } catch (JSONException e) {
// e.printStackTrace();
// }
// String success = null;
// JSONArray array = null;
// try {
// success = jsonObject.getString("success");
// array = jsonObject.getJSONArray("imageURL");
// } catch (JSONException e) {
// e.printStackTrace();
// }
//
// if (success.equals("true")) {
// int i = 0;
// String a;
// for (i = 0; i < array.length(); i++) {
// try {
// a = array.getString(i);
// System.out.println("URL" + a);
// flipperimage(a);
// } catch (JSONException e) {
// e.printStackTrace();
// }
//
// }
// }
// }
//
// @Override
// public void onErrorResponse(VolleyError error) {
//
// error.printStackTrace();
//
// }
// });
//
// if (currentmonthin >= 04 && currentmonthin <= 10)
// {
// for (int i = 0; i < rabi.length; i++) {
// flipperimage(rabi[i]);
// }
//
// }
//
// else{
// for (int i = 0; i < kharif.length; i++) {
// flipperimage(kharif[i]);
// }
//
// }
return view;
}
}
|
package cn.com.finn.base;
/**
* 原型
*
* @author Finn Zhao
* @version 2017年2月16日
*/
public interface Prototype {
}
|
package me.jcomo.slimtwitter.activities;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import com.codepath.apps.slimtwitter.R;
import me.jcomo.slimtwitter.fragments.SearchTimelineFragment;
public class SearchActivity extends AppCompatActivity {
SearchTimelineFragment searchFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (null == savedInstanceState) {
searchFragment = SearchTimelineFragment.newInstance(query);
}
setSearchTitle(query);
displaySearchResults();
}
}
private void setSearchTitle(String query) {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(query);
}
}
private void displaySearchResults() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fl_container, searchFragment);
ft.commit();
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.core.data;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import net.datacrow.console.ComponentFactory;
import net.datacrow.core.DcRepository;
import net.datacrow.core.modules.DcModule;
import net.datacrow.core.modules.DcModules;
import net.datacrow.core.objects.DcField;
import net.datacrow.core.objects.DcMapping;
import net.datacrow.core.objects.DcObject;
import net.datacrow.core.objects.Picture;
import net.datacrow.util.StringUtils;
import net.datacrow.util.Utilities;
import org.apache.log4j.Logger;
/**
* Used to filter for items.
* A filter is created out of filter entries (see {@link DataFilterEntry}).
* Filters can be saved to a file for reuse. Filters are used on the web as well as in
* the normal GUI.
*
* @author Robert Jan van der Waals
*/
public class DataFilter {
private static Logger logger = Logger.getLogger(DataFilter.class.getName());
private int module;
private final static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
private String name;
public static final int _SORTORDER_ASCENDING = 0;
public static final int _SORTORDER_DESCENDING = 1;
private int sortOrder = _SORTORDER_ASCENDING;
private DcField[] order;
private Collection<DataFilterEntry> entries = new ArrayList<DataFilterEntry>();
private final static Calendar cal = Calendar.getInstance();
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
/**
* Creates a filter based on the supplied item.
* @param dco
*/
public DataFilter(DcObject dco) {
this.module = dco.getModule().getIndex();
setEntries(dco);
}
/**
* Creates a filter based on an xml definition.
* @param xml
* @throws Exception
*/
public DataFilter(String xml) throws Exception {
parse(xml);
}
/**
* Creates an empty filter for a specific module.
* @param module
*/
public DataFilter(int module) {
this.module = module;
}
/**
* Creates a filter using the supplied entries.
* @param module
* @param entries
*/
public DataFilter(int module, Collection<DataFilterEntry> entries) {
this(module);
this.entries = entries;
}
public int getSortOrder() {
return sortOrder;
}
/**
* Sets the order. Results retrieved will be sorted based on this order.
* @param s Array of field names (column names).
*/
public void setOrder(String[] s) {
order = new DcField[s.length];
DcModule m = DcModules.get(module);
for (int i = 0; i < s.length; i++)
order[i] = m.getField(s[i]);
}
public void setSortOrder(int sortOrder) {
this.sortOrder = sortOrder;
}
/**
* Sets the order. Results retrieved will be sorted based on this order.
* @param order Array of fields.
*/
public void setOrder(DcField[] order) {
this.order = order;
}
/**
* Adds a single entry to this filter.
* @param entry
*/
public void addEntry(DataFilterEntry entry) {
entries.add(entry);
}
/**
* Sets the entries for this filter.
* Existing entries will be overwritten.
* @param entries
*/
public void setEntries(Collection<DataFilterEntry> entries) {
this.entries = entries;
}
/**
* Returns all entries belonging to this filter.
* @return
*/
public Collection<DataFilterEntry> getEntries() {
return entries;
}
/**
* Sets the entries based on the supplied item.
* Existing entries will be overridden.
* @param dco
*/
public void setEntries(DcObject dco) {
entries.clear();
for (DcField field : dco.getFields()) {
if (field.isSearchable() && dco.isChanged(field.getIndex())) {
entries.add(new DataFilterEntry(DataFilterEntry._AND,
field.getModule(),
field.getIndex(),
Operator.EQUAL_TO,
dco.getValue(field.getIndex())));
}
}
}
/**
* Returns the order information.
* @return
*/
public DcField[] getOrder() {
return order;
}
/**
* Returns the name of this filter.
*/
public String getName() {
return name;
}
/**
* Set the name of this filter.
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns the module for which this filter has been created.
*/
public int getModule() {
return module;
}
@Override
public String toString() {
return getName();
}
@Override
public boolean equals(Object o) {
String name1 = o instanceof DataFilter ? ((DataFilter) o).getName() : "";
String name2 = getName();
name1 = name1 == null ? "" : name1;
name2 = name2 == null ? "" : name2;
return name1.equals(name2);
}
/**
* Parses the XML filter definition.
* @param xml Filter definition
* @throws Exception
*/
private void parse(String xml) throws Exception {
module = Integer.parseInt(StringUtils.getValueBetween("<MODULE>", "</MODULE>", xml));
name = StringUtils.getValueBetween("<NAME>", "</NAME>", xml);
if (xml.contains("<SORTORDER>"))
sortOrder = Integer.parseInt(StringUtils.getValueBetween("<SORTORDER>", "</SORTORDER>", xml));
String sEntries = StringUtils.getValueBetween("<ENTRIES>", "</ENTRIES>", xml);
int idx = sEntries.indexOf("<ENTRY>");
while (idx != -1) {
String sEntry = StringUtils.getValueBetween("<ENTRY>", "</ENTRY>", sEntries);
int op = Integer.valueOf(StringUtils.getValueBetween("<OPERATOR>", "</OPERATOR>", sEntry)).intValue();
Operator operator = null;
for (Operator o : Operator.values()) {
if (o.getIndex() == op)
operator = o;
}
int iField = Integer.valueOf(StringUtils.getValueBetween("<FIELD>", "</FIELD>", sEntry)).intValue();
int iModule = Integer.valueOf(StringUtils.getValueBetween("<MODULE>", "</MODULE>", sEntry)).intValue();
String sValue = StringUtils.getValueBetween("<VALUE>", "</VALUE>", sEntry);
String sAndOr = StringUtils.getValueBetween("<ANDOR>", "</ANDOR>", sEntry);
Object value = null;
if (sValue.length() > 0) {
DcField field = DcModules.get(iModule).getField(iField);
int valueType = field.getValueType();
if (valueType == DcRepository.ValueTypes._BOOLEAN) {
value = Boolean.valueOf(sValue);
} else if (
valueType == DcRepository.ValueTypes._DATE ||
valueType == DcRepository.ValueTypes._DATETIME) {
value = sdf.parse(sValue);
} else if (valueType == DcRepository.ValueTypes._DCOBJECTCOLLECTION) {
StringTokenizer st = new StringTokenizer(sValue, ",");
Collection<DcObject> values = new ArrayList<DcObject>();
while (st.hasMoreElements()) {
DataFilter df = new DataFilter(field.getReferenceIdx());
df.addEntry(new DataFilterEntry(DataFilterEntry._AND,
field.getReferenceIdx(),
DcObject._ID,
Operator.EQUAL_TO,
(String) st.nextElement()));
values.addAll(DataManager.get(df));
}
value = values;
} else if (valueType == DcRepository.ValueTypes._DCOBJECTREFERENCE) {
DataFilter df = new DataFilter(field.getReferenceIdx());
df.addEntry(new DataFilterEntry(DataFilterEntry._AND,
field.getReferenceIdx(),
DcObject._ID,
Operator.EQUAL_TO,
sValue));
List<DcObject> items = DataManager.get(df);
value = items != null && items.size() == 1 ? items.get(0) : sValue;
} else if (valueType == DcRepository.ValueTypes._LONG) {
value = Long.valueOf(sValue);
} else {
value = sValue;
}
}
addEntry(new DataFilterEntry(sAndOr, iModule, iField, operator, value));
sEntries = sEntries.substring(sEntries.indexOf("</ENTRY>") + 8, sEntries.length());
idx = sEntries.indexOf("<ENTRY>");
}
Collection<DcField> fields = new ArrayList<DcField>();
String sOrder = StringUtils.getValueBetween("<ORDER>", "</ORDER>", xml);
idx = sOrder.indexOf("<FIELD>");
while (idx != -1) {
int iField = Integer.parseInt(StringUtils.getValueBetween("<FIELD>", "</FIELD>", sOrder));
fields.add(DcModules.get(module).getField(iField));
sOrder = sOrder.substring(sOrder.indexOf("</FIELD>") + 8, sOrder.length());
idx = sOrder.indexOf("<FIELD>");
}
order = fields.toArray(new DcField[0]);
}
/**
* Creates a xml definition for this filter.
*/
public String toStorageString() {
String storage = "<FILTER>\n";
storage += "<NAME>" + getName() + "</NAME>\n";
storage += "<MODULE>" + getModule() + "</MODULE>\n";
storage += "<SORTORDER>" + getSortOrder() + "</SORTORDER>\n";
storage += "<ENTRIES>\n";
Object value;
String ids;
for (DataFilterEntry entry : entries) {
if ( entry == null ||
entry.getOperator() == null ||
(entry.getOperator().needsValue() && entry.getValue() == null)) continue;
storage += "<ENTRY>\n";
storage += "<ANDOR>" + entry.getAndOr() + "</ANDOR>\n";
storage += "<OPERATOR>" + entry.getOperator().getIndex() + "</OPERATOR>\n";
storage += "<MODULE>" + entry.getModule() + "</MODULE>\n";
storage += "<FIELD>" + entry.getField() + "</FIELD>\n";
value = "";
if (entry.getOperator().needsValue()) {
if (entry.getValue() instanceof Collection) {
ids = "";
for (Object o : ((Collection) entry.getValue())) {
if (o != null && o instanceof DcObject) {
ids += (ids.length() > 0 ? "," : "") + ((DcObject) o).getID();
} else {
logger.debug("Expected an instance of DcObject for Collections for DataFilter. Unexpected value encountered " + o);
}
}
value = ids;
} else if (entry.getValue() instanceof DcObject) {
value = ((DcObject) entry.getValue()).getID();
} else if (entry.getValue() instanceof Date) {
value = sdf.format((Date) entry.getValue());
} else {
value = entry.getValue().toString();
}
}
storage += "<VALUE>" + value + "</VALUE>\n";
storage += "</ENTRY>\n";
}
storage += "</ENTRIES>\n";
storage += "<ORDER>\n";
for (int i = 0; i < order.length; i++)
storage += "<FIELD>" + order[i].getIndex() + "</FIELD>\n";
storage += "</ORDER>\n";
storage += "</FILTER>\n";
return storage;
}
/**
* Creates an entirely flat structure of the data.
* - Items will be returned duplicated in case of multiple references.
* - Pictures get their filename returned
*
* @param fields
* @param order
* @return
*/
public String toSQLFlatStructure(int[] fields) {
DcModule module = DcModules.get(getModule());
int[] queryFields = fields == null || fields.length == 0 ? module.getFieldIndices() : fields;
StringBuffer sql = new StringBuffer();
StringBuffer joins = new StringBuffer();
sql.append("SELECT DISTINCT ");
joins.append(" FROM ");
joins.append(module.getTableName());
joins.append(" MAINTABLE ");
DcModule mapping;
DcModule reference;
String subTable;
String mapTable;
int tableCounter = 0;
int columnCounter = 0;
DcField field;
for (int idx : queryFields) {
field = module.getField(idx);
if (field.isLoanField())
continue;
if (columnCounter > 0)
sql.append(", ");
if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) {
mapping = DcModules.get(DcModules.getMappingModIdx(module.getIndex(), field.getReferenceIdx(), field.getIndex()));
reference = DcModules.get(field.getReferenceIdx());
mapTable = " MAPTABLE" + tableCounter;
joins.append(" LEFT OUTER JOIN ");
joins.append(mapping.getTableName());
joins.append(mapTable);
joins.append(" ON ");
joins.append(mapTable);
joins.append(".");
joins.append(mapping.getField(DcMapping._A_PARENT_ID).getDatabaseFieldName());
joins.append(" = MAINTABLE.ID");
subTable = " SUBTABLE" + tableCounter;
joins.append(" LEFT OUTER JOIN ");
joins.append(reference.getTableName());
joins.append(subTable);
joins.append(" ON ");
joins.append(subTable);
joins.append(".ID");
joins.append(" = ");
joins.append(mapTable);
joins.append(".");
joins.append(mapping.getField(DcMapping._B_REFERENCED_ID).getDatabaseFieldName());
sql.append(subTable);
sql.append(".");
sql.append(reference.getField(reference.getDisplayFieldIdx()).getDatabaseFieldName());
tableCounter++;
} else if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTREFERENCE) {
reference = DcModules.get(field.getReferenceIdx());
subTable = " SUBTABLE" + tableCounter;
joins.append(" LEFT OUTER JOIN ");
joins.append(reference.getTableName());
joins.append(subTable);
joins.append(" ON ");
joins.append(subTable);
joins.append(".ID = MAINTABLE.");
joins.append(field.getDatabaseFieldName());
sql.append(subTable);
sql.append(".");
sql.append(reference.getField(reference.getDisplayFieldIdx()).getDatabaseFieldName());
tableCounter++;
} else if (field.getValueType() == DcRepository.ValueTypes._PICTURE) {
reference = DcModules.get(DcModules._PICTURE);
subTable = " SUBTABLE" + tableCounter;
sql.append("(case when ");
sql.append(subTable);
sql.append(".OBJECTID IS NULL then '' else ");
sql.append("'/mediaimages/'+MAINTABLE.ID+'_");
sql.append(field.getDatabaseFieldName());
sql.append("_small.jpg' ");
sql.append("END) AS ");
sql.append(field.getDatabaseFieldName());
joins.append(" LEFT OUTER JOIN ");
joins.append(reference.getTableName());
joins.append(subTable);
joins.append(" ON ");
joins.append(subTable);
joins.append(".OBJECTID = MAINTABLE.ID");
joins.append(" AND ");
joins.append(subTable);
joins.append(".");
joins.append(reference.getField(Picture._B_FIELD));
joins.append("='");
joins.append(field.getDatabaseFieldName());
joins.append("'");
tableCounter++;
} else if (!field.isUiOnly()) {
sql.append("MAINTABLE.");
sql.append(field.getDatabaseFieldName());
} else {
sql.append("'N/A' AS ");
sql.append("NA");
sql.append(columnCounter);
}
columnCounter++;
}
sql.append(joins.toString());
addEntries(sql, module);
return sql.toString();
}
public String toSQL(int[] fields, boolean orderResults, boolean includeMod) {
DcField field;
DcModule m = DcModules.get(getModule());
int[] queryFields = fields == null || fields.length == 0 ? m.getFieldIndices() : fields;
Collection<DcModule> modules = new ArrayList<DcModule>();
if (m.isAbstract())
modules.addAll(DcModules.getPersistentModules(m));
else
modules.add(m);
StringBuffer sql = new StringBuffer();
int columnCounter = 0;
int moduleCounter = 0;
if (m.isAbstract()) {
sql.append("SELECT MODULEIDX");
for (int idx : queryFields) {
field = m.getField(idx);
if (!field.isUiOnly()) {
sql.append(", ");
sql.append(field.getDatabaseFieldName());
columnCounter++;
}
}
sql.append(" FROM (");
}
for (DcModule module : modules) {
columnCounter = 0;
if (moduleCounter > 0)
sql.append(" UNION ");
sql.append(" SELECT ");
if (m.isAbstract() || includeMod) {
sql.append(module.getIndex());
sql.append(" AS MODULEIDX ");
columnCounter++;
}
if (m.isAbstract()) {
for (DcField abstractField : m.getFields()) {
if (!abstractField.isUiOnly()) {
if (columnCounter > 0) sql.append(", ");
sql.append(abstractField.getDatabaseFieldName());
columnCounter++;
}
}
} else {
for (int idx : queryFields) {
field = m.getField(idx);
if (field != null && !field.isUiOnly()) {
if (columnCounter > 0) sql.append(", ");
sql.append(field.getDatabaseFieldName());
columnCounter++;
}
}
}
sql.append(" FROM ");
sql.append(module.getTableName());
if (orderResults)
addOrderByClause(sql);
addEntries(sql, module);
moduleCounter++;
}
if (m.isAbstract()) sql.append(") media ");
// add a join to the reference table part of the sort
if (orderResults) addOrderBy(sql);
return sql.toString();
}
@SuppressWarnings("unchecked")
private void addEntries(StringBuffer sql, DcModule module) {
boolean hasConditions = false;
DcModule entryModule;
List<DataFilterEntry> childEntries = new ArrayList<DataFilterEntry>();
Object value;
int operator;
int counter2;
int counter = 0;
String queryValue = null;
DcField field;
DcModule m = DcModules.get(getModule());
for (DataFilterEntry entry : getEntries()) {
if (!m.isAbstract()) {
entryModule = DcModules.get(entry.getModule());
if (entry.getModule() != getModule()) {
childEntries.add(entry);
continue;
}
} else {
entryModule = module;
}
field = entryModule.getField(entry.getField());
if ( field.isUiOnly() &&
field.getValueType() != DcRepository.ValueTypes._DCOBJECTCOLLECTION &&
field.getValueType() != DcRepository.ValueTypes._PICTURE)
continue;
hasConditions = true;
operator = entry.getOperator().getIndex();
value = entry.getValue() != null ? Utilities.getQueryValue(entry.getValue(), field) : null;
if (value != null) {
if (value instanceof Date)
queryValue = "'" + formatter.format((Date) value) + "'";
else {
queryValue = String.valueOf(value);
if (field.getValueType() == DcRepository.ValueTypes._STRING)
queryValue = queryValue.replaceAll("\'", "''");
}
}
if (counter > 0) sql.append(entry.isAnd() ? " AND " : " OR ");
if (counter == 0) sql.append(" WHERE ");
boolean useUpper = field.getValueType() == DcRepository.ValueTypes._STRING &&
field.getIndex() != DcObject._ID &&
field.getValueType() != DcRepository.ValueTypes._DCOBJECTREFERENCE &&
field.getValueType() != DcRepository.ValueTypes._DCPARENTREFERENCE &&
field.getValueType() != DcRepository.ValueTypes._DCOBJECTCOLLECTION;
if (field.getValueType() == DcRepository.ValueTypes._STRING) {
if (useUpper) sql.append("UPPER(");
sql.append(field.getDatabaseFieldName());
if (useUpper) sql.append(")");
} else if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION ||
field.getValueType() == DcRepository.ValueTypes._PICTURE) {
sql.append("ID");
} else {
sql.append(field.getDatabaseFieldName());
}
if (field.getValueType() == DcRepository.ValueTypes._PICTURE) {
if (operator == Operator.IS_EMPTY.getIndex())
sql.append(" NOT");
DcModule picModule = DcModules.get(DcModules._PICTURE);
sql.append(" IN (SELECT OBJECTID FROM " + picModule.getTableName() +
" WHERE " + picModule.getField(Picture._B_FIELD).getDatabaseFieldName() +
" = '" + field.getDatabaseFieldName() + "')");
} else if ((operator == Operator.IS_EMPTY.getIndex() && field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) ||
(operator == Operator.IS_FILLED.getIndex() && field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION)) {
if (operator == Operator.IS_EMPTY.getIndex())
sql.append(" NOT");
DcModule mapping = DcModules.get(DcModules.getMappingModIdx(entryModule.getIndex(), field.getReferenceIdx(), field.getIndex()));
sql.append(" IN (SELECT " + mapping.getField(DcMapping._A_PARENT_ID).getDatabaseFieldName() +
" FROM " + mapping.getTableName() +
" WHERE " + mapping.getField(DcMapping._A_PARENT_ID).getDatabaseFieldName() + " = ID)");
} else if ( operator == Operator.CONTAINS.getIndex() ||
operator == Operator.DOES_NOT_CONTAIN.getIndex() ||
(operator == Operator.EQUAL_TO.getIndex() && field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) ||
(operator == Operator.NOT_EQUAL_TO.getIndex() && field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION)) {
if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) {
if (operator == Operator.DOES_NOT_CONTAIN.getIndex() ||
operator == Operator.IS_EMPTY.getIndex() ||
operator == Operator.NOT_EQUAL_TO.getIndex())
sql.append(" NOT");
sql.append(" IN (");
DcModule mapping = DcModules.get(DcModules.getMappingModIdx(entryModule.getIndex(), field.getReferenceIdx(), field.getIndex()));
sql.append("SELECT ");
sql.append(mapping.getField(DcMapping._A_PARENT_ID).getDatabaseFieldName());
sql.append(" FROM ");
sql.append(mapping.getTableName());
sql.append(" WHERE ");
sql.append(mapping.getField(DcMapping._B_REFERENCED_ID).getDatabaseFieldName());
sql.append(" IN (");
if (!(value instanceof Collection)) {
sql.append("'");
sql.append(value);
sql.append("'");
sql.append(")");
} else {
counter2 = 0;
for (Object o : (Collection) value) {
if (counter2 > 0) sql.append(",");
sql.append("'");
if (o instanceof DcObject)
sql.append(((DcObject) o).getID());
else
sql.append(o.toString());
sql.append("'");
counter2++;
}
sql.append(")");
}
sql.append(")");
} else {
if (operator == Operator.DOES_NOT_CONTAIN.getIndex()) sql.append(" NOT");
sql.append(" LIKE ");
if (useUpper) sql.append("UPPER(");
sql.append("'%" + queryValue + "%'");
if (useUpper) sql.append(")");
}
} else if (operator == Operator.ENDS_WITH.getIndex()) {
sql.append(" LIKE ");
if (useUpper) sql.append("UPPER(");
sql.append("'%" + queryValue + "'");
if (useUpper) sql.append(")");
} else if (operator == Operator.EQUAL_TO.getIndex()) {
if (useUpper) {
sql.append(" = UPPER('"+ queryValue +"')");
} else {
sql.append(" = ");
if (value instanceof String) sql.append("'");
sql.append(queryValue);
if (value instanceof String) sql.append("'");
}
} else if (operator == Operator.BEFORE.getIndex() ||
operator == Operator.LESS_THEN.getIndex()) {
sql.append(" < ");
sql.append(queryValue);
} else if (operator == Operator.AFTER.getIndex() ||
operator == Operator.GREATER_THEN.getIndex()) {
sql.append(" > ");
sql.append(queryValue);
} else if (operator == Operator.IS_EMPTY.getIndex()) {
sql.append(" IS NULL");
} else if (operator == Operator.IS_FILLED.getIndex()) {
sql.append(" IS NOT NULL");
} else if (operator == Operator.NOT_EQUAL_TO.getIndex()) {
sql.append(" <> ");
if (useUpper) {
sql.append(" UPPER('"+ queryValue +"')");
} else {
if (value instanceof String) sql.append("'");
sql.append(queryValue);
if (value instanceof String) sql.append("'");
}
} else if (operator == Operator.STARTS_WITH.getIndex()) {
sql.append(" LIKE ");
if (useUpper) sql.append("UPPER(");
sql.append("'" + queryValue + "%'");
if (useUpper) sql.append(")");
} else if (operator == Operator.TODAY.getIndex()) {
sql.append(" = TODAY");
} else if (operator == Operator.DAYS_BEFORE.getIndex()) {
cal.setTime(new Date());
Long days = (Long) entry.getValue();
cal.add(Calendar.DATE, -1 * days.intValue());
sql.append(" = '" + formatter.format(cal.getTime()) + "'");
} else if (operator == Operator.DAYS_AFTER.getIndex()) {
Long days = (Long) entry.getValue();
cal.add(Calendar.DATE, days.intValue());
sql.append(" = '" + formatter.format(cal.getTime()) + "'");
} else if (operator == Operator.MONTHS_AGO.getIndex()) {
Long days = (Long) entry.getValue();
cal.add(Calendar.MONTH, -1 * days.intValue());
cal.set(Calendar.DAY_OF_MONTH, 1);
sql.append(" BETWEEN '" + formatter.format(cal.getTime()) + "'");
cal.set(Calendar.DAY_OF_MONTH, cal.getMaximum(Calendar.DAY_OF_MONTH));
sql.append(" AND '" + formatter.format(cal.getTime()) + "'");
} else if (operator == Operator.YEARS_AGO.getIndex()) {
Long days = (Long) entry.getValue();
cal.add(Calendar.YEAR, -1 * days.intValue());
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
sql.append(" BETWEEN '" + formatter.format(cal.getTime()) + "'");
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 31);
sql.append(" AND '" + formatter.format(cal.getTime()) + "'");
}
counter++;
}
if (childEntries.size() > 0) {
DcModule childModule = DcModules.get(childEntries.get(0).getModule());
DataFilter df = new DataFilter(childModule.getIndex());
for (DataFilterEntry entry : childEntries)
df.addEntry(entry);
String subSelect = df.toSQL(new int[] {childModule.getParentReferenceFieldIndex()}, false, false);
if (hasConditions)
sql.append(" AND ID IN (");
else
sql.append(" WHERE ID IN (");
sql.append(subSelect);
sql.append(")");
}
addLoanConditions(getEntries(), module, sql, hasConditions);
}
private void addOrderByClause(StringBuffer sql) {
if (order != null && order.length > 0) {
for (DcField orderOn : order) {
// can happen; old configurations
if (orderOn == null) continue;
if (orderOn.getFieldType() == ComponentFactory._REFERENCEFIELD ||
orderOn.getFieldType() == ComponentFactory._REFERENCESFIELD) {
String column = orderOn.getFieldType() == ComponentFactory._REFERENCESFIELD ?
DcModules.get(orderOn.getModule()).getPersistentField(orderOn.getIndex()).getDatabaseFieldName() :
orderOn.getDatabaseFieldName();
String referenceTableName = DcModules.get(orderOn.getReferenceIdx()).getTableName();
sql.append(" LEFT OUTER JOIN ");
sql.append(referenceTableName);
sql.append(" ON ");
sql.append(referenceTableName);
sql.append(".ID = ");
sql.append(column);
}
}
}
}
private void addOrderBy(StringBuffer sql) {
int counter = 0;
DcModule module = DcModules.get(getModule());
DcModule referenceMod;
DcField field = module.getField(module.getDefaultSortFieldIdx());
if (order != null && order.length > 0) {
for (DcField orderOn : order) {
if (orderOn != null) {
sql.append(counter == 0 ? " ORDER BY " : ", ");
if (orderOn.getValueType() == DcRepository.ValueTypes._DCOBJECTREFERENCE ||
orderOn.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) {
referenceMod = DcModules.get(orderOn.getReferenceIdx());
sql.append(referenceMod.getTableName());
sql.append(".");
sql.append(referenceMod.getField(referenceMod.getSystemDisplayFieldIdx()).getDatabaseFieldName());
sql.append(getSortOrder() == _SORTORDER_ASCENDING ? "" : " DESC");
} else if (!orderOn.isUiOnly() && orderOn.getDatabaseFieldName() != null) {
sql.append(orderOn.getDatabaseFieldName());
sql.append(getSortOrder() == _SORTORDER_ASCENDING ? "" : " DESC");
}
counter++;
}
}
} else if (field != null && !field.isUiOnly()) {
sql.append(" ORDER BY ");
sql.append(module.getField(module.getDefaultSortFieldIdx()).getDatabaseFieldName());
}
}
private void addLoanConditions(Collection<DataFilterEntry> entries, DcModule module, StringBuffer sql, boolean hasConditions) {
Object person = null;
Object duration = null;
Object available = null;
Object queryValue;
for (DataFilterEntry entry : entries) {
queryValue = Utilities.getQueryValue(entry.getValue(), DcModules.get(entry.getModule()).getField(entry.getField()));
if (entry.getField() == DcObject._SYS_AVAILABLE)
available = queryValue;
if (entry.getField() == DcObject._SYS_LENDBY)
person = queryValue;
if (entry.getField() == DcObject._SYS_LOANDURATION)
duration = queryValue;
}
if (available == null && person == null && duration == null)
return;
sql.append(hasConditions ? " AND " : " WHERE ");
String maintable = module.getTableName();
String current = formatter.format(new Date());
String daysCondition = duration != null ? " AND DATEDIFF('dd', startDate , '" + current + "') >= " + duration : "";
String personCondition = person != null ? " AND PersonID = '" + person + "'" : "";
if (available != null && Boolean.valueOf(available.toString()))
sql.append(" ID NOT IN (select objectID from Loans where objectID = " + maintable
+ ".ID AND enddate IS NULL AND startDate <= '" + current + "')");
else
sql.append(" ID IN (select objectID from Loans where objectID = " + maintable
+ ".ID " + daysCondition + " AND enddate IS NULL AND startDate <= '" + current + "'" + personCondition + ")");
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : super.hashCode();
}
public boolean equals(DataFilter df) {
return name != null && df.getName() != null ? name.equals(df.getName()) : df.getName() != null || name != null;
}
}
|
package evolutionYoutube;
public class Mi_cuenta extends Mi_cuenta_ventana {
/**
*
*/
private static final long serialVersionUID = 1L;
public Mi_perfil _unnamed_Mi_perfil_;
public Datos_personales _unnamed_Datos_personales_;
public Mi_cuenta() {
datos_personales.addComponent(new Datos_personales());
}
}
|
package ks.types.dataFeed.accounting.csv;
public interface IAccountingWorkbook <S extends IAccountingSheet<IAccountingRow<IAccountingCell>, IAccountingCell>>{
public S getSheetByName(String name);
public void addSheet(String name);
}
|
package com.flyusoft.apps.jointoil.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.flyusoft.apps.jointoil.dao.CompressorDao;
import com.flyusoft.apps.jointoil.entity.Compressor;
import com.flyusoft.apps.jointoil.entity.Well;
import com.flyusoft.apps.jointoil.service.CompressorService;
import com.flyusoft.common.orm.Page;
import com.flyusoft.common.orm.PropertyFilter;
@Service
@Transactional
public class CompressorServiceImpl implements CompressorService {
@Autowired
private CompressorDao compressorDao;
@Override
public void saveCompressor(Compressor _compressor) {
compressorDao.save(_compressor);
}
@Override
public void deleteCompressor(List<String> _ids) {
int tmp = compressorDao.delete(_ids);
if (tmp == -1) {
System.out.println("删除IDS集合失败");
}
}
@Override
@Transactional(readOnly = true)
public Compressor getCompressor(String _id) {
return compressorDao.get(_id);
}
@Override
@Transactional(readOnly = true)
public Page<Compressor> searchCompressor(Page<Compressor> _page, List<PropertyFilter> _filters) {
return compressorDao.findPage(_page, _filters);
}
@Override
@Transactional(readOnly = true)
public List<Compressor> getAllCompressors() {
return compressorDao.getAll("compressorCode", true);
}
@Override
@Transactional(readOnly = true)
public List<Compressor> getCompressorsByRoomId(String roomId) {
return compressorDao.searchcompreCompressorByRoomId(roomId);
}
@Override
@Transactional(readOnly = true)
public List<Compressor> searchAllCompressorAndIndex() {
return compressorDao.searchAllCompressorAndIndex();
}
}
|
package com.company;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
public class Main {
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(10);
Semaphore semaphore = new Semaphore(4);
for (int i = 1; i <cdl.getCount() ; i++) {
new Passengers(i, semaphore, cdl).start();
}
try {
cdl.await();
Thread.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("We have got a message, all passengers on the bus will travell from the East side"+ "they enjoy their trip!");
}
}
|
package com.atguigu.lgl;
public class Test {
public static void main(String[] args) {
// Student student = new Student();
Student student = new Student(1001, 30, 50, 70);
student.age = 10;
student.sex = '女';
student.age = 27;
System.out.println(student.aver());
System.out.println(student.max());
System.out.println(student.min());
}
}
|
package br.com.fiap.teste;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import br.com.fiap.beans.Voluntario;
import br.com.fiap.bo.VoluntarioBO;
import br.com.fiap.dao.VoluntarioDAO;
public class VoluntarioTeste {
public static void main(String[] args) throws Exception {
VoluntarioDAO dao = new VoluntarioDAO();
Voluntario v = new Voluntario();
VoluntarioBO bo = new VoluntarioBO();
/*
v.setEmail(JOptionPane.showInputDialog("Qual o e-mail do voluntário?"));
v.setNome(JOptionPane.showInputDialog("Qual o nome do voluntário?"));
v.setCpf(Integer.parseInt(JOptionPane.showInputDialog("Qual o CPF do voluntário?")));
v.setDtNascimento(JOptionPane.showInputDialog("Qual a data de nascimento voluntário?"));
v.setProfissao(JOptionPane.showInputDialog("Qual a profissão do voluntário?"));
v.setSenha(JOptionPane.showInputDialog("Qual o senha do voluntário?"));
v.setStatus(true);
v.setTelefone(JOptionPane.showInputDialog("Qual o telefone do voluntário?"));
dao.add(v);
*/
List<Voluntario> lstVoluntario = new ArrayList<Voluntario>();
lstVoluntario = dao.find();
for (Voluntario voluntario : lstVoluntario) {
System.out.println("Código do voluntário: " + voluntario.getCodigo());
System.out.println("Nome do voluntário: " + voluntario.getNome());
System.out.println("E-mail do voluntário: " + voluntario.getEmail());
System.out.println("CPF do voluntário: " + voluntario.getCpf());
System.out.println("Data de nascimento do voluntário: " + voluntario.getDtNascimento());
System.out.println("Ações que participou: " + voluntario.getAcoesParticipou());
System.out.println("Ações que realizou: " + voluntario.getAcoesRealizou() + "\n");
}
lstVoluntario = dao.findTop3();
if(lstVoluntario.size() == 0){
System.out.println("Parece que nenhum voluntário participou de uma ação! :(");
} else{
System.out.println("=== TOP 3 VOLUNTÁRIOS ===");
for (Voluntario voluntario : lstVoluntario) {
System.out.println("Nome do voluntário: " + voluntario.getNome());
System.out.println("CPF do voluntário: " + voluntario.getCpf());
System.out.println("Ações que participou: " + voluntario.getAcoesParticipou() + "\n");
}
}
v.setCodigo(4);
v.setEmail("tesess@teste.com");
v.setNome("NomeTeste");
v.setCpf(43546521l);
v.setDtNascimento("23/12/95");
v.setProfissao("Desenvolvedor");
v.setSenha("7412369");
v.setStatus(false);
v.setTelefone("2122358521");
if(bo.editarVoluntario(v)){
System.out.println("VALIDOU");
}else{
System.out.println("NÃO VALIDOU");
}
Voluntario voluntario = bo.buscaVoluntarioById(3);
System.out.println("==============================================================");
System.out.println("Código do voluntário: " + voluntario.getCodigo());
System.out.println("Nome do voluntário: " + voluntario.getNome());
System.out.println("E-mail do voluntário: " + voluntario.getEmail());
System.out.println("CPF do voluntário: " + voluntario.getCpf());
System.out.println("Data de nascimento do voluntário: " + voluntario.getDtNascimento());
System.out.println("Ações que participou: " + voluntario.getAcoesParticipou());
System.out.println("Ações que realizou: " + voluntario.getAcoesRealizou() + "\n");
}
}
|
/**
* Copyright 2014 零志愿工作室 (http://www.0will.com). All rights reserved.
* File Name: BaseEntity.java
* Author: chenlong
* Encoding UTF-8
* Version: 1.0
* Date: 2014年12月4日
* History:
*/
package com.Owill.web.system.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author chenlong(chenlongwill@163.com)
* @version Revision: 1.0.0 Date: 2014年12月4日
*/
@Controller
@RequestMapping("/chatroom")
public class TstChatroomController {
/** */
@RequestMapping(value = "/robot", method = RequestMethod.GET)
public String list(Model model) {
return "test01/chatroom";
}
}
|
package com.treela.thefarmerguy.repository;
import com.treela.thefarmerguy.model.Session;
import java.util.List;
import java.util.Map;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface SessionRepository extends CrudRepository<Session, Integer> {
public Session findById(String id);
public long countById(String id);
public boolean existsByIdAndUserid(String id, long userid);
@Modifying
@Query(value = "select sess.userid from session as sess\n" +
"left join users as user on user.id = sess.userid\n" +
"where sess.userid = :userid and sess.id = :id and user.isadmin > 1",
nativeQuery = true)
public List<Map<String, Object>> isAdmin(
@Param("id") String id,
@Param("userid") long userid);
}
|
package by.epam.aliaksei.litvin.services;
import by.epam.aliaksei.litvin.domain.User;
import by.epam.aliaksei.litvin.service.UserService;
import by.epam.aliaksei.litvin.service.impl.UserServiceImpl;
import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring.xml")
public class UserServiceImplTest {
@Autowired
private UserServiceImpl userService;
private static final String EMAIL = "test@test.com";
private User user1;
private User user2;
private User user3;
@Before
public void setup() {
user1 = new User();
user2 = new User();
user3 = new User();
user1.setEmail(EMAIL);
userService.save(user1);
userService.save(user2);
userService.save(user3);
}
@After
public void tearDown() {
userService.removeAll();
}
@Test
public void testSaveUser_andGetAllUsers() {
assertEquals(userService.getAll().size(), 3);
}
@Test
public void testRemoveUser() {
userService.remove(user1);
assertEquals(userService.getAll().size(), 2);
}
@Test
public void testGetUserById() {
Long id = 0L;
User user = userService.getById(id);
assertEquals(user.getId(), id);
}
@Test
public void testGetUserByEmail() {
User userByEmail = userService.getUserByEmail(EMAIL);
assertEquals(userByEmail.getEmail(), EMAIL);
}
}
|
package com.rev.service.spring;
import com.rev.dao.GenericRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.List;
/**
*
* @Author Trevor
* @param <T> The model to access
*/
@RestController
public abstract class GenericController<T> {
@Autowired
private GenericRepository<T> dao;
@PostMapping(path = "post", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Serializable> post(@RequestBody T t){
Serializable id = dao.save(t);
return new ResponseEntity<Serializable>(id, id!=null ? HttpStatus.CREATED : HttpStatus.INTERNAL_SERVER_ERROR );
}
@GetMapping(path = "get/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<T> get(@PathVariable String id){
T t;
try{ //try to parse the id as an int
t = dao.findById(Integer.parseInt(id));
}
catch (final NumberFormatException e){
t = dao.findById(id);
}
return new ResponseEntity<T>(t, t!=null ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR );
}
@GetMapping(path = "get", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<T>> getAll(){
List<T> t = dao.findAll();
return new ResponseEntity<List<T>>(t, t!=null ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR);
}
@PutMapping(path = "put", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> put(@RequestBody T t){
Boolean success = dao.update(t);
return new ResponseEntity<>(null, success ? HttpStatus.NO_CONTENT : HttpStatus.INTERNAL_SERVER_ERROR );
}
@DeleteMapping(path = "delete/{id}")
public ResponseEntity<Void> delete(@PathVariable String id){
Boolean success;
try{ //try to parse the id as an int
success = dao.deleteById(Integer.parseInt(id));
}
catch (final NumberFormatException e){
success = dao.deleteById(id);
}
return new ResponseEntity<>(null, success ? HttpStatus.NO_CONTENT : HttpStatus.INTERNAL_SERVER_ERROR );
}
}
|
package com.example;
import com.example.model.Data;
import com.hazelcast.core.IMap;
import com.hazelcast.query.Predicates;
import com.hazelcast.query.SqlPredicate;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static com.example.TestUtil.generateTestData;
import static com.example.TestUtil.populateTestData;
import static com.example.TestUtil.ALPHA;
/**
* Hello world!
*/
public class App {
public static final Logger LOGGER = Logger.getLogger(App.class);
private static final int BENCHMARK_INTERVAL = 30;
private static final int TEST_DATA_SIZE = 1000000;
public static void main(String[] args) {
LOGGER.info("starting application");
ApplicationContext context = new ClassPathXmlApplicationContext("/application-context.xml");
List<Data> testData = generateTestData(TEST_DATA_SIZE);
IMap<String, Data> dataMap = context.getBean("dataMap", IMap.class);
LOGGER.info("inserting into non-indexedDataMap");
populateTestData(dataMap, testData);
IMap<String, Data> indexedDataMap = context.getBean("indexedDataMap", IMap.class);
LOGGER.info("inserting into indexedDataMap");
populateTestData(indexedDataMap, testData);
LOGGER.info("benchmarking predicate search on non-indexed collection");
benchMarkPredicateSearch(dataMap);
LOGGER.info("benchmarking predicate search on indexed collection");
benchMarkPredicateSearch(indexedDataMap);
LOGGER.info("benchmarking sql search on non-indexed collection");
benchMarkSqlPredicateSearch(dataMap);
LOGGER.info("benchmarking sql search on indexed collection");
benchMarkSqlPredicateSearch(indexedDataMap);
LOGGER.info("benchmarking sql search on indexed collection with where clause having both, indexed and non-indexed column");
benchMarkSqlPrdWithNonIndexedCol(indexedDataMap);
// CacheManager cacheManager = context.getBean(HazelcastCacheManager.class);
// Cache cache = cacheManager.getCache("dataMap");
// cache.get("AA");
((AbstractApplicationContext) context).close();
LOGGER.info("end");
}
private static void benchMarkSqlPrdWithNonIndexedCol(IMap<String, Data> map) {
int count = 0;
Random r = new Random();
long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(BENCHMARK_INTERVAL);
while (System.currentTimeMillis() < endTime) {
String assetId = new String(new char[]{ALPHA[r.nextInt(25)], ALPHA[r.nextInt(25)]});
Collection<?> result = map.values(new SqlPredicate("assetId = '" + assetId + "' AND nav > 0.5"));
// LOGGER.info(String.format("for assetId: %s matches found: %d", assetId, result.size()));
count++;
}
LOGGER.info(String.format("performed: %d searches in: %d secs ", count, BENCHMARK_INTERVAL));
}
private static void benchMarkPredicateSearch(IMap<String, Data> map) {
int count = 0;
Random r = new Random();
long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(BENCHMARK_INTERVAL);
while (System.currentTimeMillis() < endTime) {
String assetId = new String(new char[]{ALPHA[r.nextInt(25)], ALPHA[r.nextInt(25)]});
Collection<?> result = map.values(Predicates.equal("assetId", assetId));
// LOGGER.info(String.format("for assetId: %s matches found: %d", assetId, result.size()));
count++;
}
LOGGER.info(String.format("performed: %d searches in: %d secs ", count, BENCHMARK_INTERVAL));
}
private static void benchMarkSqlPredicateSearch(IMap<String, Data> map) {
int count = 0;
Random r = new Random();
long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(BENCHMARK_INTERVAL);
while (System.currentTimeMillis() < endTime) {
String assetId = new String(new char[]{ALPHA[r.nextInt(25)], ALPHA[r.nextInt(25)]});
Collection<?> result = map.values(new SqlPredicate("assetId = '" + assetId + "'"));
// LOGGER.info(String.format("for assetId: %s matches found: %d", assetId, result.size()));
count++;
}
LOGGER.info(String.format("performed: %d searches in: %d secs ", count, BENCHMARK_INTERVAL));
}
}
|
package cn.xeblog.xechat.controller;
import cn.xeblog.xechat.domain.vo.ResponseVO;
import cn.xeblog.xechat.service.UploadService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
/**
* 上传文件
*
* @author yanpanyi
* @date 2019/03/27
*/
@RestController
@RequestMapping("/api/upload")
public class UploadController {
@Resource
private UploadService uploadService;
/**
* 上传图片
*
* @param multipartFile
* @return
* @throws Exception
*/
@PostMapping("/image")
public ResponseVO uploadImage(@RequestParam("file") MultipartFile multipartFile) throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("path", uploadService.uploadImage(multipartFile));
return new ResponseVO(jsonObject);
}
}
|
package com.GestiondesClub.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.GestiondesClub.dao.DemandeAfficheRepository;
@Service
public class DemandeEventServ {
@Autowired
private DemandeAfficheRepository demAfficheDao;
}
|
package com.redislabs.research.redis;
import com.redislabs.research.Document;
import com.redislabs.research.Index;
import com.redislabs.research.Query;
import com.redislabs.research.Spec;
import com.sun.deploy.util.ArrayUtil;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.CRC32;
/**
* PartitionedIndex wraps multiple partitions of simple indexes and queries them concurrently
*/
public class PartitionedIndex implements Index {
Index[] partitions;
// this is basically java 8's newWorkStealingPool
static ExecutorService pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors(),
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
int timeoutMilli;
String name;
public static PartitionedIndex newSimple(String name, Spec spec, int numPartitions, int timeoutMilli,
int numThreads,
String ...redisURIs) throws IOException {
return new PartitionedIndex(new SimpleIndex.Factory(), name,spec,numPartitions,timeoutMilli,numThreads,redisURIs);
}
public static PartitionedIndex newFulltext(String name, Spec spec, int numPartitions, int timeoutMilli,
int numThreads,
String ...redisURIs) throws IOException {
return new PartitionedIndex(new FullTextFacetedIndex.Factory(), name,spec,numPartitions,timeoutMilli,numThreads,redisURIs);
}
public PartitionedIndex(IndexFactory factory, String name, Spec spec, int numPartitions, int timeoutMilli,
int numThreads,
String ...redisURIs ) throws IOException {
this.name = name;
partitions = new Index[numPartitions];
this.timeoutMilli = timeoutMilli;
for (int i =0; i < numPartitions; i++) {
String pname = String.format("%s{%d}", name, i);
partitions[i] = factory.create(pname, spec, redisURIs[i % redisURIs.length]);
}
}
private CRC32 hash = new CRC32();
synchronized int partitionFor(String id) {
hash.reset();
hash.update(id.getBytes());
return (int) (hash.getValue() % partitions.length);
}
@Override
public Boolean index(Document ...docs) throws IOException {
ArrayList[] parts = new ArrayList[partitions.length];
for (int i =0; i < partitions.length; i++) {
parts[i] = new ArrayList(1);
}
// TODO: Make this transactional and pipelined
for (Document doc : docs) {
parts[partitionFor(doc.getId())].add(doc);
}
for (int i =0; i < partitions.length; i++) {
if (parts[i].size() > 0) {
partitions[i].index((Document[]) parts[i].toArray(new Document[parts[i].size()]));
}
}
return true;
}
@Override
public List<Entry> get(final Query q) throws IOException, InterruptedException {
// this is the queue we use to aggregate the results
final PriorityQueue<Entry> entries = new PriorityQueue<>(q.sort.limit*partitions.length);
List<Callable<List<Entry>>> tasks = new ArrayList<>(partitions.length);
// submit the sub tasks to the thread pool
for (final Index idx : partitions) {
tasks.add(new Callable<List<Entry>>() {
@Override
public List<Entry> call() throws Exception {
return idx.get(q);
}
});
}
List<Future<List<Entry>>> futures = pool.invokeAll(tasks, timeoutMilli, TimeUnit.MILLISECONDS);
for (Future<List<Entry>> future : futures ) {
if (!future.isCancelled()) {
try {
List<Entry> es = future.get();
if (es != null) {
entries.addAll(es);
}
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
while (entries.size() > q.sort.limit) {
entries.poll();
}
List<Entry> ret = new ArrayList<>(entries.size());
while (entries.size() > 0) {
ret.add(entries.poll());
}
Collections.reverse(ret);
return ret;
}
@Override
public Boolean delete(String... ids) {
for (Index idx : partitions) {
idx.delete(ids);
}
return true;
}
@Override
public Boolean drop() {
for (Index idx : partitions) {
idx.drop();
}
return true;
}
@Override
public String id() {
return name;
}
}
|
package com._520it.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
import com._520it.jdbc.JDBCUtils_V1;
import com._520it.jdbc.JDBCUtils_V2;
import com._520it.jdbc.JDBCUtils_V3;
public class TestUtil {
/**
* 根据id进行更改操作
*/
@Test
public void testUpdate() {
Connection conn=null;
PreparedStatement pstmt=null;
try {
//获取连接
conn=JDBCUtils_V3.getConnection();
//sql语句
String sql="update user set upassword=? where id=?";
//获取预编译语句对象
pstmt = conn.prepareStatement(sql);
//设置占位符
pstmt.setString(1, "qweqwe");
pstmt.setInt(2, 2);
//执行sql语句
int row = pstmt.executeUpdate();
if (row>0) {
System.out.println("更新成功");
}else {
System.out.println("更新失败");
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
JDBCUtils_V3.close(conn, pstmt, null);
}
}
/**
* 刪除操作
*/
@Test
public void testDel() {
Connection conn=null;
PreparedStatement pstmt=null;
try {
//获取连接
conn=JDBCUtils_V3.getConnection();
//sql语句
String sql="delete from user where id=?";
//获取预编译语句对象
pstmt = conn.prepareStatement(sql);
//设置占位符
pstmt.setInt(1, 1);
//执行sql语句
int row = pstmt.executeUpdate();
if (row>0) {
System.out.println("刪除成功");
}else {
System.out.println("刪除失败");
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
JDBCUtils_V3.close(conn, pstmt, null);
}
}
/**
* 插入操作
*/
@Test
public void testAdd() {
Connection conn=null;
PreparedStatement pstmt=null;
try {
//获取连接
conn=JDBCUtils_V2.getConnection();
//sql语句
String sql="insert into user values(?,?,?)";
//获取预编译语句对象
pstmt = conn.prepareStatement(sql);
//设置占位符
pstmt.setInt(1, 6);
pstmt.setString(2, "ww");
pstmt.setString(3, "123");
//执行sql语句
int row = pstmt.executeUpdate();
if (row>0) {
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
JDBCUtils_V2.close(conn, pstmt, null);
}
}
/**
* 根据id查询用户信息
*/
@Test
public void testId() {
Connection conn=null;
PreparedStatement preparedStatement=null;
ResultSet query=null;
try {
//获得连接对象
conn = JDBCUtils_V1.getConnection();
//书写sql语句
String sql="select * from user where id =?";
//获得预执行对象
preparedStatement =conn.prepareStatement(sql);
//设置占位符参数
preparedStatement.setInt(1, 1);
//执行sql语句
query = preparedStatement.executeQuery();
//处理结果集
while (query.next()) {
int id = query.getInt(1);
String name = query.getString(2);
String password = query.getString(3);
System.out.println("id:"+id+"name:"+name+"pwd:"+password);
}
//关闭资源不能放在try里面,防止上面语句出错的情况下,导致资源一直不关闭!!!占用资源
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭资源
JDBCUtils_V1.close(conn, preparedStatement, query);
}
}
}
|
package com.travel.lodge.userservice.dto;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
@Data
public class AddUserRequest {
@NotNull
private String firstName;
@NotNull
private String lastName;
@NotNull
@Length(max = 28)
@Pattern(regexp = "^[a-z0-9]+@[a-z]+\\.[a-z]{2,6}$")
private String email;
@NotNull
@Length(max=16)
private String password;
private String location;
@NotNull
@Length(max=20)
private String contactNo;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vpssmsserver;
import java.io.Serializable;
/**
*
* @author Royal
*/
public class Subject implements Serializable{
private String subjectId;
private String name;
private String status;
private String date;
public Subject(){
}
public Subject(String subjectId,String name,String status,String date){
this.subjectId=subjectId;
this.name=name;
this.status=status;
this.date=date;
}
/**
* @return the subjectId
*/
public String getSubjectId() {
return subjectId;
}
/**
* @param subjectId the subjectId to set
*/
public void setSubjectId(String subjectId) {
this.subjectId = subjectId;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
/**
* @return the date
*/
public String getDate() {
return date;
}
/**
* @param date the date to set
*/
public void setDate(String date) {
this.date = date;
}
}
|
package com.capgemini.batatatinhadellivery.enums;
public enum StatusPedido {
RECEBIDO, PREPARANDO, A_CAMINHO, ENTREGUE;
}
|
/**
*/
package com.wdl.dao.rbac.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.wdl.base.dao.impl.BaseDaoImpl;
import com.wdl.dao.rbac.OrgDao;
import com.wdl.entity.rbac.Org;
@Repository("DepartmentDao")
public class OrgDaoImpl extends BaseDaoImpl implements OrgDao {
@Override
public List<Org> findByDeleted() {
String hql = " from Org dt where dt.deleted=0 order by dt.levelCode asc";
List<Org> list = this.find(hql);
if (list != null) {
return list;
}
return null;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.support;
import java.beans.PropertyEditor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.PropertyEditorRegistrySupport;
import org.springframework.beans.SimpleTypeConverter;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.BeanIsAbstractException;
import org.springframework.beans.factory.BeanIsNotAFactoryException;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.CannotLoadBeanClassException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.SmartFactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.config.Scope;
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import org.springframework.core.DecoratingClassLoader;
import org.springframework.core.NamedThreadLocal;
import org.springframework.core.ResolvableType;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.log.LogMessage;
import org.springframework.core.metrics.ApplicationStartup;
import org.springframework.core.metrics.StartupStep;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.StringValueResolver;
/**
* Abstract base class for {@link org.springframework.beans.factory.BeanFactory}
* implementations, providing the full capabilities of the
* {@link org.springframework.beans.factory.config.ConfigurableBeanFactory} SPI.
* Does <i>not</i> assume a listable bean factory: can therefore also be used
* as base class for bean factory implementations which obtain bean definitions
* from some backend resource (where bean definition access is an expensive operation).
*
* <p>This class provides a singleton cache (through its base class
* {@link org.springframework.beans.factory.support.DefaultSingletonBeanRegistry},
* singleton/prototype determination, {@link org.springframework.beans.factory.FactoryBean}
* handling, aliases, bean definition merging for child bean definitions,
* and bean destruction ({@link org.springframework.beans.factory.DisposableBean}
* interface, custom destroy methods). Furthermore, it can manage a bean factory
* hierarchy (delegating to the parent in case of an unknown bean), through implementing
* the {@link org.springframework.beans.factory.HierarchicalBeanFactory} interface.
*
* <p>The main template methods to be implemented by subclasses are
* {@link #getBeanDefinition} and {@link #createBean}, retrieving a bean definition
* for a given bean name and creating a bean instance for a given bean definition,
* respectively. Default implementations of those operations can be found in
* {@link DefaultListableBeanFactory} and {@link AbstractAutowireCapableBeanFactory}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Costin Leau
* @author Chris Beams
* @author Phillip Webb
* @author Sam Brannen
* @since 15 April 2001
* @see #getBeanDefinition
* @see #createBean
* @see AbstractAutowireCapableBeanFactory#createBean
* @see DefaultListableBeanFactory#getBeanDefinition
*/
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
/** Parent bean factory, for bean inheritance support. */
@Nullable
private BeanFactory parentBeanFactory;
/** ClassLoader to resolve bean class names with, if necessary. */
@Nullable
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
/** ClassLoader to temporarily resolve bean class names with, if necessary. */
@Nullable
private ClassLoader tempClassLoader;
/** Whether to cache bean metadata or rather reobtain it for every access. */
private boolean cacheBeanMetadata = true;
/** Resolution strategy for expressions in bean definition values. */
@Nullable
private BeanExpressionResolver beanExpressionResolver;
/** Spring ConversionService to use instead of PropertyEditors. */
@Nullable
private ConversionService conversionService;
/** Custom PropertyEditorRegistrars to apply to the beans of this factory. */
private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<>(4);
/** Custom PropertyEditors to apply to the beans of this factory. */
private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>(4);
/** A custom TypeConverter to use, overriding the default PropertyEditor mechanism. */
@Nullable
private TypeConverter typeConverter;
/** String resolvers to apply e.g. to annotation attribute values. */
private final List<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList<>();
/** BeanPostProcessors to apply. */
private final List<BeanPostProcessor> beanPostProcessors = new BeanPostProcessorCacheAwareList();
/** Cache of pre-filtered post-processors. */
@Nullable
private BeanPostProcessorCache beanPostProcessorCache;
/** Map from scope identifier String to corresponding Scope. */
private final Map<String, Scope> scopes = new LinkedHashMap<>(8);
/** Map from bean name to merged RootBeanDefinition. */
private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256);
/** Names of beans that have already been created at least once. */
private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256));
/** Names of beans that are currently in creation. */
private final ThreadLocal<Object> prototypesCurrentlyInCreation =
new NamedThreadLocal<>("Prototype beans currently in creation");
/** Application startup metrics. **/
private ApplicationStartup applicationStartup = ApplicationStartup.DEFAULT;
/**
* Create a new AbstractBeanFactory.
*/
public AbstractBeanFactory() {
}
/**
* Create a new AbstractBeanFactory with the given parent.
* @param parentBeanFactory parent bean factory, or {@code null} if none
* @see #getBean
*/
public AbstractBeanFactory(@Nullable BeanFactory parentBeanFactory) {
this.parentBeanFactory = parentBeanFactory;
}
//---------------------------------------------------------------------
// Implementation of BeanFactory interface
//---------------------------------------------------------------------
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return doGetBean(name, requiredType, null, false);
}
@Override
public Object getBean(String name, Object... args) throws BeansException {
return doGetBean(name, null, args, false);
}
/**
* Return an instance, which may be shared or independent, of the specified bean.
* @param name the name of the bean to retrieve
* @param requiredType the required type of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args)
throws BeansException {
return doGetBean(name, requiredType, args, false);
}
/**
* Return an instance, which may be shared or independent, of the specified bean.
* @param name the name of the bean to retrieve
* @param requiredType the required type of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @param typeCheckOnly whether the instance is obtained for a type check,
* not for actual use
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
@SuppressWarnings("unchecked")
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
String beanName = transformedBeanName(name);
Object beanInstance;
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory abf) {
return abf.doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
.tag("beanName", name);
try {
if (requiredType != null) {
beanCreation.tag("beanType", requiredType::toString);
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
if (!StringUtils.hasLength(scopeName)) {
throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");
}
Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new ScopeNotActiveException(beanName, scopeName, ex);
}
}
}
catch (BeansException ex) {
beanCreation.tag("exception", ex.getClass().toString());
beanCreation.tag("message", String.valueOf(ex.getMessage()));
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
finally {
beanCreation.end();
if (!isCacheBeanMetadata()) {
clearMergedBeanDefinition(beanName);
}
}
}
return adaptBeanInstance(name, beanInstance, requiredType);
}
@SuppressWarnings("unchecked")
<T> T adaptBeanInstance(String name, Object bean, @Nullable Class<?> requiredType) {
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
Object convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return (T) convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
@Override
public boolean containsBean(String name) {
String beanName = transformedBeanName(name);
if (containsSingleton(beanName) || containsBeanDefinition(beanName)) {
return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));
}
// Not found -> check parent.
BeanFactory parentBeanFactory = getParentBeanFactory();
return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));
}
@Override
public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null) {
if (beanInstance instanceof FactoryBean<?> factoryBean) {
return (BeanFactoryUtils.isFactoryDereference(name) || factoryBean.isSingleton());
}
else {
return !BeanFactoryUtils.isFactoryDereference(name);
}
}
// No singleton instance found -> check bean definition.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.isSingleton(originalBeanName(name));
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// In case of FactoryBean, return singleton status of created object if not a dereference.
if (mbd.isSingleton()) {
if (isFactoryBean(beanName, mbd)) {
if (BeanFactoryUtils.isFactoryDereference(name)) {
return true;
}
FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
return factoryBean.isSingleton();
}
else {
return !BeanFactoryUtils.isFactoryDereference(name);
}
}
else {
return false;
}
}
@Override
public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.isPrototype(originalBeanName(name));
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
if (mbd.isPrototype()) {
// In case of FactoryBean, return singleton status of created object if not a dereference.
return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd));
}
// Singleton or scoped - not a prototype.
// However, FactoryBean may still produce a prototype object...
if (BeanFactoryUtils.isFactoryDereference(name)) {
return false;
}
if (isFactoryBean(beanName, mbd)) {
FactoryBean<?> fb = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
return ((fb instanceof SmartFactoryBean<?> smartFactoryBean && smartFactoryBean.isPrototype()) ||
!fb.isSingleton());
}
else {
return false;
}
}
@Override
public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException {
return isTypeMatch(name, typeToMatch, true);
}
/**
* Internal extended variant of {@link #isTypeMatch(String, ResolvableType)}
* to check whether the bean with the given name matches the specified type. Allow
* additional constraints to be applied to ensure that beans are not created early.
* @param name the name of the bean to query
* @param typeToMatch the type to match against (as a
* {@code ResolvableType})
* @return {@code true} if the bean type matches, {@code false} if it
* doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 5.2
* @see #getBean
* @see #getType
*/
protected boolean isTypeMatch(String name, ResolvableType typeToMatch, boolean allowFactoryBeanInit)
throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
boolean isFactoryDereference = BeanFactoryUtils.isFactoryDereference(name);
// Check manually registered singletons.
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
if (beanInstance instanceof FactoryBean<?> factoryBean) {
if (!isFactoryDereference) {
Class<?> type = getTypeForFactoryBean(factoryBean);
return (type != null && typeToMatch.isAssignableFrom(type));
}
else {
return typeToMatch.isInstance(beanInstance);
}
}
else if (!isFactoryDereference) {
if (typeToMatch.isInstance(beanInstance)) {
// Direct match for exposed instance?
return true;
}
else if (typeToMatch.hasGenerics() && containsBeanDefinition(beanName)) {
// Generics potentially only match on the target class, not on the proxy...
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
Class<?> targetType = mbd.getTargetType();
if (targetType != null && targetType != ClassUtils.getUserClass(beanInstance)) {
// Check raw class match as well, making sure it's exposed on the proxy.
Class<?> classToMatch = typeToMatch.resolve();
if (classToMatch != null && !classToMatch.isInstance(beanInstance)) {
return false;
}
if (typeToMatch.isAssignableFrom(targetType)) {
return true;
}
}
ResolvableType resolvableType = mbd.targetType;
if (resolvableType == null) {
resolvableType = mbd.factoryMethodReturnType;
}
return (resolvableType != null && typeToMatch.isAssignableFrom(resolvableType));
}
}
return false;
}
else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
// null instance registered
return false;
}
// No singleton instance found -> check bean definition.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch);
}
// Retrieve corresponding bean definition.
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
// Set up the types that we want to match against
Class<?> classToMatch = typeToMatch.resolve();
if (classToMatch == null) {
classToMatch = FactoryBean.class;
}
Class<?>[] typesToMatch = (FactoryBean.class == classToMatch ?
new Class<?>[] {classToMatch} : new Class<?>[] {FactoryBean.class, classToMatch});
// Attempt to predict the bean type
Class<?> predictedType = null;
// We're looking for a regular reference, but we're a factory bean that has
// a decorated bean definition. The target bean should be the same type
// as FactoryBean would ultimately return.
if (!isFactoryDereference && dbd != null && isFactoryBean(beanName, mbd)) {
// We should only attempt if the user explicitly set lazy-init to true
// and we know the merged bean definition is for a factory bean.
if (!mbd.isLazyInit() || allowFactoryBeanInit) {
RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
Class<?> targetType = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);
if (targetType != null && !FactoryBean.class.isAssignableFrom(targetType)) {
predictedType = targetType;
}
}
}
// If we couldn't use the target type, try regular prediction.
if (predictedType == null) {
predictedType = predictBeanType(beanName, mbd, typesToMatch);
if (predictedType == null) {
return false;
}
}
// Attempt to get the actual ResolvableType for the bean.
ResolvableType beanType = null;
// If it's a FactoryBean, we want to look at what it creates, not the factory class.
if (FactoryBean.class.isAssignableFrom(predictedType)) {
if (beanInstance == null && !isFactoryDereference) {
beanType = getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit);
predictedType = beanType.resolve();
if (predictedType == null) {
return false;
}
}
}
else if (isFactoryDereference) {
// Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean
// type, but we nevertheless are being asked to dereference a FactoryBean...
// Let's check the original bean class and proceed with it if it is a FactoryBean.
predictedType = predictBeanType(beanName, mbd, FactoryBean.class);
if (predictedType == null || !FactoryBean.class.isAssignableFrom(predictedType)) {
return false;
}
}
// We don't have an exact type but if bean definition target type or the factory
// method return type matches the predicted type then we can use that.
if (beanType == null) {
ResolvableType definedType = mbd.targetType;
if (definedType == null) {
definedType = mbd.factoryMethodReturnType;
}
if (definedType != null && definedType.resolve() == predictedType) {
beanType = definedType;
}
}
// If we have a bean type use it so that generics are considered
if (beanType != null) {
return typeToMatch.isAssignableFrom(beanType);
}
// If we don't have a bean type, fallback to the predicted type
return typeToMatch.isAssignableFrom(predictedType);
}
@Override
public boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException {
return isTypeMatch(name, ResolvableType.forRawClass(typeToMatch));
}
@Override
@Nullable
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return getType(name, true);
}
@Override
@Nullable
public Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
// Check manually registered singletons.
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
if (beanInstance instanceof FactoryBean<?> factoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
return getTypeForFactoryBean(factoryBean);
}
else {
return beanInstance.getClass();
}
}
// No singleton instance found -> check bean definition.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.getType(originalBeanName(name));
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
Class<?> beanClass = predictBeanType(beanName, mbd);
if (beanClass != null) {
// Check bean class whether we're dealing with a FactoryBean.
if (FactoryBean.class.isAssignableFrom(beanClass)) {
if (!BeanFactoryUtils.isFactoryDereference(name)) {
// If it's a FactoryBean, we want to look at what it creates, not at the factory class.
beanClass = getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit).resolve();
}
}
else if (BeanFactoryUtils.isFactoryDereference(name)) {
return null;
}
}
if (beanClass == null) {
// Check decorated bean definition, if any: We assume it'll be easier
// to determine the decorated bean's type than the proxy's type.
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd);
if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
return targetClass;
}
}
}
return beanClass;
}
@Override
public String[] getAliases(String name) {
String beanName = transformedBeanName(name);
List<String> aliases = new ArrayList<>();
boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX);
String fullBeanName = beanName;
if (factoryPrefix) {
fullBeanName = FACTORY_BEAN_PREFIX + beanName;
}
if (!fullBeanName.equals(name)) {
aliases.add(fullBeanName);
}
String[] retrievedAliases = super.getAliases(beanName);
String prefix = (factoryPrefix ? FACTORY_BEAN_PREFIX : "");
for (String retrievedAlias : retrievedAliases) {
String alias = prefix + retrievedAlias;
if (!alias.equals(name)) {
aliases.add(alias);
}
}
if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null) {
aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName)));
}
}
return StringUtils.toStringArray(aliases);
}
//---------------------------------------------------------------------
// Implementation of HierarchicalBeanFactory interface
//---------------------------------------------------------------------
@Override
@Nullable
public BeanFactory getParentBeanFactory() {
return this.parentBeanFactory;
}
@Override
public boolean containsLocalBean(String name) {
String beanName = transformedBeanName(name);
return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) &&
(!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName)));
}
//---------------------------------------------------------------------
// Implementation of ConfigurableBeanFactory interface
//---------------------------------------------------------------------
@Override
public void setParentBeanFactory(@Nullable BeanFactory parentBeanFactory) {
if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) {
throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory);
}
if (this == parentBeanFactory) {
throw new IllegalStateException("Cannot set parent bean factory to self");
}
this.parentBeanFactory = parentBeanFactory;
}
@Override
public void setBeanClassLoader(@Nullable ClassLoader beanClassLoader) {
this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader());
}
@Override
@Nullable
public ClassLoader getBeanClassLoader() {
return this.beanClassLoader;
}
@Override
public void setTempClassLoader(@Nullable ClassLoader tempClassLoader) {
this.tempClassLoader = tempClassLoader;
}
@Override
@Nullable
public ClassLoader getTempClassLoader() {
return this.tempClassLoader;
}
@Override
public void setCacheBeanMetadata(boolean cacheBeanMetadata) {
this.cacheBeanMetadata = cacheBeanMetadata;
}
@Override
public boolean isCacheBeanMetadata() {
return this.cacheBeanMetadata;
}
@Override
public void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver) {
this.beanExpressionResolver = resolver;
}
@Override
@Nullable
public BeanExpressionResolver getBeanExpressionResolver() {
return this.beanExpressionResolver;
}
@Override
public void setConversionService(@Nullable ConversionService conversionService) {
this.conversionService = conversionService;
}
@Override
@Nullable
public ConversionService getConversionService() {
return this.conversionService;
}
@Override
public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) {
Assert.notNull(registrar, "PropertyEditorRegistrar must not be null");
this.propertyEditorRegistrars.add(registrar);
}
/**
* Return the set of PropertyEditorRegistrars.
*/
public Set<PropertyEditorRegistrar> getPropertyEditorRegistrars() {
return this.propertyEditorRegistrars;
}
@Override
public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) {
Assert.notNull(requiredType, "Required type must not be null");
Assert.notNull(propertyEditorClass, "PropertyEditor class must not be null");
this.customEditors.put(requiredType, propertyEditorClass);
}
@Override
public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) {
registerCustomEditors(registry);
}
/**
* Return the map of custom editors, with Classes as keys and PropertyEditor classes as values.
*/
public Map<Class<?>, Class<? extends PropertyEditor>> getCustomEditors() {
return this.customEditors;
}
@Override
public void setTypeConverter(TypeConverter typeConverter) {
this.typeConverter = typeConverter;
}
/**
* Return the custom TypeConverter to use, if any.
* @return the custom TypeConverter, or {@code null} if none specified
*/
@Nullable
protected TypeConverter getCustomTypeConverter() {
return this.typeConverter;
}
@Override
public TypeConverter getTypeConverter() {
TypeConverter customConverter = getCustomTypeConverter();
if (customConverter != null) {
return customConverter;
}
else {
// Build default TypeConverter, registering custom editors.
SimpleTypeConverter typeConverter = new SimpleTypeConverter();
typeConverter.setConversionService(getConversionService());
registerCustomEditors(typeConverter);
return typeConverter;
}
}
@Override
public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
Assert.notNull(valueResolver, "StringValueResolver must not be null");
this.embeddedValueResolvers.add(valueResolver);
}
@Override
public boolean hasEmbeddedValueResolver() {
return !this.embeddedValueResolvers.isEmpty();
}
@Override
@Nullable
public String resolveEmbeddedValue(@Nullable String value) {
if (value == null) {
return null;
}
String result = value;
for (StringValueResolver resolver : this.embeddedValueResolvers) {
result = resolver.resolveStringValue(result);
if (result == null) {
return null;
}
}
return result;
}
@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
synchronized (this.beanPostProcessors) {
// Remove from old position, if any
this.beanPostProcessors.remove(beanPostProcessor);
// Add to end of list
this.beanPostProcessors.add(beanPostProcessor);
}
}
/**
* Add new BeanPostProcessors that will get applied to beans created
* by this factory. To be invoked during factory configuration.
* @since 5.3
* @see #addBeanPostProcessor
*/
public void addBeanPostProcessors(Collection<? extends BeanPostProcessor> beanPostProcessors) {
synchronized (this.beanPostProcessors) {
// Remove from old position, if any
this.beanPostProcessors.removeAll(beanPostProcessors);
// Add to end of list
this.beanPostProcessors.addAll(beanPostProcessors);
}
}
@Override
public int getBeanPostProcessorCount() {
return this.beanPostProcessors.size();
}
/**
* Return the list of BeanPostProcessors that will get applied
* to beans created with this factory.
*/
public List<BeanPostProcessor> getBeanPostProcessors() {
return this.beanPostProcessors;
}
/**
* Return the internal cache of pre-filtered post-processors,
* freshly (re-)building it if necessary.
* @since 5.3
*/
BeanPostProcessorCache getBeanPostProcessorCache() {
synchronized (this.beanPostProcessors) {
BeanPostProcessorCache bppCache = this.beanPostProcessorCache;
if (bppCache == null) {
bppCache = new BeanPostProcessorCache();
for (BeanPostProcessor bpp : this.beanPostProcessors) {
if (bpp instanceof InstantiationAwareBeanPostProcessor instantiationAwareBpp) {
bppCache.instantiationAware.add(instantiationAwareBpp);
if (bpp instanceof SmartInstantiationAwareBeanPostProcessor smartInstantiationAwareBpp) {
bppCache.smartInstantiationAware.add(smartInstantiationAwareBpp);
}
}
if (bpp instanceof DestructionAwareBeanPostProcessor destructionAwareBpp) {
bppCache.destructionAware.add(destructionAwareBpp);
}
if (bpp instanceof MergedBeanDefinitionPostProcessor mergedBeanDefBpp) {
bppCache.mergedDefinition.add(mergedBeanDefBpp);
}
}
this.beanPostProcessorCache = bppCache;
}
return bppCache;
}
}
private void resetBeanPostProcessorCache() {
synchronized (this.beanPostProcessors) {
this.beanPostProcessorCache = null;
}
}
/**
* Return whether this factory holds a InstantiationAwareBeanPostProcessor
* that will get applied to singleton beans on creation.
* @see #addBeanPostProcessor
* @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
*/
protected boolean hasInstantiationAwareBeanPostProcessors() {
return !getBeanPostProcessorCache().instantiationAware.isEmpty();
}
/**
* Return whether this factory holds a DestructionAwareBeanPostProcessor
* that will get applied to singleton beans on shutdown.
* @see #addBeanPostProcessor
* @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor
*/
protected boolean hasDestructionAwareBeanPostProcessors() {
return !getBeanPostProcessorCache().destructionAware.isEmpty();
}
@Override
public void registerScope(String scopeName, Scope scope) {
Assert.notNull(scopeName, "Scope identifier must not be null");
Assert.notNull(scope, "Scope must not be null");
if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) {
throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'");
}
Scope previous = this.scopes.put(scopeName, scope);
if (previous != null && previous != scope) {
if (logger.isDebugEnabled()) {
logger.debug("Replacing scope '" + scopeName + "' from [" + previous + "] to [" + scope + "]");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Registering scope '" + scopeName + "' with implementation [" + scope + "]");
}
}
}
@Override
public String[] getRegisteredScopeNames() {
return StringUtils.toStringArray(this.scopes.keySet());
}
@Override
@Nullable
public Scope getRegisteredScope(String scopeName) {
Assert.notNull(scopeName, "Scope identifier must not be null");
return this.scopes.get(scopeName);
}
@Override
public void setApplicationStartup(ApplicationStartup applicationStartup) {
Assert.notNull(applicationStartup, "applicationStartup must not be null");
this.applicationStartup = applicationStartup;
}
@Override
public ApplicationStartup getApplicationStartup() {
return this.applicationStartup;
}
@Override
public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
Assert.notNull(otherFactory, "BeanFactory must not be null");
setBeanClassLoader(otherFactory.getBeanClassLoader());
setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());
setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());
setConversionService(otherFactory.getConversionService());
if (otherFactory instanceof AbstractBeanFactory otherAbstractFactory) {
this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);
this.customEditors.putAll(otherAbstractFactory.customEditors);
this.typeConverter = otherAbstractFactory.typeConverter;
this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);
this.scopes.putAll(otherAbstractFactory.scopes);
}
else {
setTypeConverter(otherFactory.getTypeConverter());
String[] otherScopeNames = otherFactory.getRegisteredScopeNames();
for (String scopeName : otherScopeNames) {
this.scopes.put(scopeName, otherFactory.getRegisteredScope(scopeName));
}
}
}
/**
* Return a 'merged' BeanDefinition for the given bean name,
* merging a child bean definition with its parent if necessary.
* <p>This {@code getMergedBeanDefinition} considers bean definition
* in ancestors as well.
* @param name the name of the bean to retrieve the merged definition for
* (may be an alias)
* @return a (potentially merged) RootBeanDefinition for the given bean
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @throws BeanDefinitionStoreException in case of an invalid bean definition
*/
@Override
public BeanDefinition getMergedBeanDefinition(String name) throws BeansException {
String beanName = transformedBeanName(name);
// Efficiently check whether bean definition exists in this factory.
if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory parent) {
return parent.getMergedBeanDefinition(beanName);
}
// Resolve merged bean definition locally.
return getMergedLocalBeanDefinition(beanName);
}
@Override
public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null) {
return (beanInstance instanceof FactoryBean);
}
// No singleton instance found -> check bean definition.
if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory cbf) {
// No bean definition found in this factory -> delegate to parent.
return cbf.isFactoryBean(name);
}
return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
}
@Override
public boolean isActuallyInCreation(String beanName) {
return (isSingletonCurrentlyInCreation(beanName) || isPrototypeCurrentlyInCreation(beanName));
}
/**
* Return whether the specified prototype bean is currently in creation
* (within the current thread).
* @param beanName the name of the bean
*/
protected boolean isPrototypeCurrentlyInCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
return (curVal != null &&
(curVal.equals(beanName) || (curVal instanceof Set<?> set && set.contains(beanName))));
}
/**
* Callback before prototype creation.
* <p>The default implementation registers the prototype as currently in creation.
* @param beanName the name of the prototype about to be created
* @see #isPrototypeCurrentlyInCreation
*/
@SuppressWarnings("unchecked")
protected void beforePrototypeCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
if (curVal == null) {
this.prototypesCurrentlyInCreation.set(beanName);
}
else if (curVal instanceof String strValue) {
Set<String> beanNameSet = new HashSet<>(2);
beanNameSet.add(strValue);
beanNameSet.add(beanName);
this.prototypesCurrentlyInCreation.set(beanNameSet);
}
else {
Set<String> beanNameSet = (Set<String>) curVal;
beanNameSet.add(beanName);
}
}
/**
* Callback after prototype creation.
* <p>The default implementation marks the prototype as not in creation anymore.
* @param beanName the name of the prototype that has been created
* @see #isPrototypeCurrentlyInCreation
*/
@SuppressWarnings("unchecked")
protected void afterPrototypeCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
if (curVal instanceof String) {
this.prototypesCurrentlyInCreation.remove();
}
else if (curVal instanceof Set<?> beanNameSet) {
beanNameSet.remove(beanName);
if (beanNameSet.isEmpty()) {
this.prototypesCurrentlyInCreation.remove();
}
}
}
@Override
public void destroyBean(String beanName, Object beanInstance) {
destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName));
}
/**
* Destroy the given bean instance (usually a prototype instance
* obtained from this factory) according to the given bean definition.
* @param beanName the name of the bean definition
* @param bean the bean instance to destroy
* @param mbd the merged bean definition
*/
protected void destroyBean(String beanName, Object bean, RootBeanDefinition mbd) {
new DisposableBeanAdapter(
bean, beanName, mbd, getBeanPostProcessorCache().destructionAware).destroy();
}
@Override
public void destroyScopedBean(String beanName) {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
if (mbd.isSingleton() || mbd.isPrototype()) {
throw new IllegalArgumentException(
"Bean name '" + beanName + "' does not correspond to an object in a mutable scope");
}
String scopeName = mbd.getScope();
Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope SPI registered for scope name '" + scopeName + "'");
}
Object bean = scope.remove(beanName);
if (bean != null) {
destroyBean(beanName, bean, mbd);
}
}
//---------------------------------------------------------------------
// Implementation methods
//---------------------------------------------------------------------
/**
* Return the bean name, stripping out the factory dereference prefix if necessary,
* and resolving aliases to canonical names.
* @param name the user-specified name
* @return the transformed bean name
*/
protected String transformedBeanName(String name) {
return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}
/**
* Determine the original bean name, resolving locally defined aliases to canonical names.
* @param name the user-specified name
* @return the original bean name
*/
protected String originalBeanName(String name) {
String beanName = transformedBeanName(name);
if (name.startsWith(FACTORY_BEAN_PREFIX)) {
beanName = FACTORY_BEAN_PREFIX + beanName;
}
return beanName;
}
/**
* Initialize the given BeanWrapper with the custom editors registered
* with this factory. To be called for BeanWrappers that will create
* and populate bean instances.
* <p>The default implementation delegates to {@link #registerCustomEditors}.
* Can be overridden in subclasses.
* @param bw the BeanWrapper to initialize
*/
protected void initBeanWrapper(BeanWrapper bw) {
bw.setConversionService(getConversionService());
registerCustomEditors(bw);
}
/**
* Initialize the given PropertyEditorRegistry with the custom editors
* that have been registered with this BeanFactory.
* <p>To be called for BeanWrappers that will create and populate bean
* instances, and for SimpleTypeConverter used for constructor argument
* and factory method type conversion.
* @param registry the PropertyEditorRegistry to initialize
*/
protected void registerCustomEditors(PropertyEditorRegistry registry) {
if (registry instanceof PropertyEditorRegistrySupport registrySupport) {
registrySupport.useConfigValueEditors();
}
if (!this.propertyEditorRegistrars.isEmpty()) {
for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
try {
registrar.registerCustomEditors(registry);
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException bce) {
String bceBeanName = bce.getBeanName();
if (bceBeanName != null && isCurrentlyInCreation(bceBeanName)) {
if (logger.isDebugEnabled()) {
logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
"] failed because it tried to obtain currently created bean '" +
ex.getBeanName() + "': " + ex.getMessage());
}
onSuppressedException(ex);
continue;
}
}
throw ex;
}
}
}
if (!this.customEditors.isEmpty()) {
this.customEditors.forEach((requiredType, editorClass) ->
registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)));
}
}
/**
* Return a merged RootBeanDefinition, traversing the parent bean definition
* if the specified bean corresponds to a child bean definition.
* @param beanName the name of the bean to retrieve the merged definition for
* @return a (potentially merged) RootBeanDefinition for the given bean
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @throws BeanDefinitionStoreException in case of an invalid bean definition
*/
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
// Quick check on the concurrent map first, with minimal locking.
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
if (mbd != null && !mbd.stale) {
return mbd;
}
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
/**
* Return a RootBeanDefinition for the given top-level bean, by merging with
* the parent if the given bean's definition is a child bean definition.
* @param beanName the name of the bean definition
* @param bd the original bean definition (Root/ChildBeanDefinition)
* @return a (potentially merged) RootBeanDefinition for the given bean
* @throws BeanDefinitionStoreException in case of an invalid bean definition
*/
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
throws BeanDefinitionStoreException {
return getMergedBeanDefinition(beanName, bd, null);
}
/**
* Return a RootBeanDefinition for the given bean, by merging with the
* parent if the given bean's definition is a child bean definition.
* @param beanName the name of the bean definition
* @param bd the original bean definition (Root/ChildBeanDefinition)
* @param containingBd the containing bean definition in case of inner bean,
* or {@code null} in case of a top-level bean
* @return a (potentially merged) RootBeanDefinition for the given bean
* @throws BeanDefinitionStoreException in case of an invalid bean definition
*/
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
throws BeanDefinitionStoreException {
synchronized (this.mergedBeanDefinitions) {
RootBeanDefinition mbd = null;
RootBeanDefinition previous = null;
// Check with full lock now in order to enforce the same merged instance.
if (containingBd == null) {
mbd = this.mergedBeanDefinitions.get(beanName);
}
if (mbd == null || mbd.stale) {
previous = mbd;
if (bd.getParentName() == null) {
// Use copy of given root bean definition.
if (bd instanceof RootBeanDefinition rootBeanDef) {
mbd = rootBeanDef.cloneBeanDefinition();
}
else {
mbd = new RootBeanDefinition(bd);
}
}
else {
// Child bean definition: needs to be merged with parent.
BeanDefinition pbd;
try {
String parentBeanName = transformedBeanName(bd.getParentName());
if (!beanName.equals(parentBeanName)) {
pbd = getMergedBeanDefinition(parentBeanName);
}
else {
if (getParentBeanFactory() instanceof ConfigurableBeanFactory parent) {
pbd = parent.getMergedBeanDefinition(parentBeanName);
}
else {
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without a ConfigurableBeanFactory parent");
}
}
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
// Deep copy with overridden values.
mbd = new RootBeanDefinition(pbd);
mbd.overrideFrom(bd);
}
// Set default singleton scope, if not configured before.
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(SCOPE_SINGLETON);
}
// A bean contained in a non-singleton bean cannot be a singleton itself.
// Let's correct this on the fly here, since this might be the result of
// parent-child merging for the outer bean, in which case the original inner bean
// definition will not have inherited the merged outer bean's singleton status.
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}
// Cache the merged bean definition for the time being
// (it might still get re-merged later on in order to pick up metadata changes)
if (containingBd == null && (isCacheBeanMetadata() || isBeanEligibleForMetadataCaching(beanName))) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
if (previous != null) {
copyRelevantMergedBeanDefinitionCaches(previous, mbd);
}
return mbd;
}
}
private void copyRelevantMergedBeanDefinitionCaches(RootBeanDefinition previous, RootBeanDefinition mbd) {
if (ObjectUtils.nullSafeEquals(mbd.getBeanClassName(), previous.getBeanClassName()) &&
ObjectUtils.nullSafeEquals(mbd.getFactoryBeanName(), previous.getFactoryBeanName()) &&
ObjectUtils.nullSafeEquals(mbd.getFactoryMethodName(), previous.getFactoryMethodName())) {
ResolvableType targetType = mbd.targetType;
ResolvableType previousTargetType = previous.targetType;
if (targetType == null || targetType.equals(previousTargetType)) {
mbd.targetType = previousTargetType;
mbd.isFactoryBean = previous.isFactoryBean;
mbd.resolvedTargetType = previous.resolvedTargetType;
mbd.factoryMethodReturnType = previous.factoryMethodReturnType;
mbd.factoryMethodToIntrospect = previous.factoryMethodToIntrospect;
}
if (previous.hasMethodOverrides()) {
mbd.setMethodOverrides(new MethodOverrides(previous.getMethodOverrides()));
}
}
}
/**
* Check the given merged bean definition,
* potentially throwing validation exceptions.
* @param mbd the merged bean definition to check
* @param beanName the name of the bean
* @param args the arguments for bean creation, if any
* @throws BeanDefinitionStoreException in case of validation failure
*/
protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, @Nullable Object[] args)
throws BeanDefinitionStoreException {
if (mbd.isAbstract()) {
throw new BeanIsAbstractException(beanName);
}
}
/**
* Remove the merged bean definition for the specified bean,
* recreating it on next access.
* @param beanName the bean name to clear the merged definition for
*/
protected void clearMergedBeanDefinition(String beanName) {
RootBeanDefinition bd = this.mergedBeanDefinitions.get(beanName);
if (bd != null) {
bd.stale = true;
}
}
/**
* Clear the merged bean definition cache, removing entries for beans
* which are not considered eligible for full metadata caching yet.
* <p>Typically triggered after changes to the original bean definitions,
* e.g. after applying a {@code BeanFactoryPostProcessor}. Note that metadata
* for beans which have already been created at this point will be kept around.
* @since 4.2
*/
public void clearMetadataCache() {
this.mergedBeanDefinitions.forEach((beanName, bd) -> {
if (!isBeanEligibleForMetadataCaching(beanName)) {
bd.stale = true;
}
});
}
/**
* Resolve the bean class for the specified bean definition,
* resolving a bean class name into a Class reference (if necessary)
* and storing the resolved Class in the bean definition for further use.
* @param mbd the merged bean definition to determine the class for
* @param beanName the name of the bean (for error handling purposes)
* @param typesToMatch the types to match in case of internal type matching purposes
* (also signals that the returned {@code Class} will never be exposed to application code)
* @return the resolved bean class (or {@code null} if none)
* @throws CannotLoadBeanClassException if we failed to load the class
*/
@Nullable
protected Class<?> resolveBeanClass(RootBeanDefinition mbd, String beanName, Class<?>... typesToMatch)
throws CannotLoadBeanClassException {
try {
if (mbd.hasBeanClass()) {
return mbd.getBeanClass();
}
return doResolveBeanClass(mbd, typesToMatch);
}
catch (ClassNotFoundException ex) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (LinkageError err) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);
}
}
@Nullable
private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch)
throws ClassNotFoundException {
ClassLoader beanClassLoader = getBeanClassLoader();
ClassLoader dynamicLoader = beanClassLoader;
boolean freshResolve = false;
if (!ObjectUtils.isEmpty(typesToMatch)) {
// When just doing type checks (i.e. not creating an actual instance yet),
// use the specified temporary class loader (e.g. in a weaving scenario).
ClassLoader tempClassLoader = getTempClassLoader();
if (tempClassLoader != null) {
dynamicLoader = tempClassLoader;
freshResolve = true;
if (tempClassLoader instanceof DecoratingClassLoader dcl) {
for (Class<?> typeToMatch : typesToMatch) {
dcl.excludeClass(typeToMatch.getName());
}
}
}
}
String className = mbd.getBeanClassName();
if (className != null) {
Object evaluated = evaluateBeanDefinitionString(className, mbd);
if (!className.equals(evaluated)) {
// A dynamically resolved expression, supported as of 4.2...
if (evaluated instanceof Class<?> clazz) {
return clazz;
}
else if (evaluated instanceof String name) {
className = name;
freshResolve = true;
}
else {
throw new IllegalStateException("Invalid class name expression result: " + evaluated);
}
}
if (freshResolve) {
// When resolving against a temporary class loader, exit early in order
// to avoid storing the resolved Class in the bean definition.
if (dynamicLoader != null) {
try {
return dynamicLoader.loadClass(className);
}
catch (ClassNotFoundException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Could not load class [" + className + "] from " + dynamicLoader + ": " + ex);
}
}
}
return ClassUtils.forName(className, dynamicLoader);
}
}
// Resolve regularly, caching the result in the BeanDefinition...
return mbd.resolveBeanClass(beanClassLoader);
}
/**
* Evaluate the given String as contained in a bean definition,
* potentially resolving it as an expression.
* @param value the value to check
* @param beanDefinition the bean definition that the value comes from
* @return the resolved value
* @see #setBeanExpressionResolver
*/
@Nullable
protected Object evaluateBeanDefinitionString(@Nullable String value, @Nullable BeanDefinition beanDefinition) {
if (this.beanExpressionResolver == null) {
return value;
}
Scope scope = null;
if (beanDefinition != null) {
String scopeName = beanDefinition.getScope();
if (scopeName != null) {
scope = getRegisteredScope(scopeName);
}
}
return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));
}
/**
* Predict the eventual bean type (of the processed bean instance) for the
* specified bean. Called by {@link #getType} and {@link #isTypeMatch}.
* Does not need to handle FactoryBeans specifically, since it is only
* supposed to operate on the raw bean type.
* <p>This implementation is simplistic in that it is not able to
* handle factory methods and InstantiationAwareBeanPostProcessors.
* It only predicts the bean type correctly for a standard bean.
* To be overridden in subclasses, applying more sophisticated type detection.
* @param beanName the name of the bean
* @param mbd the merged bean definition to determine the type for
* @param typesToMatch the types to match in case of internal type matching purposes
* (also signals that the returned {@code Class} will never be exposed to application code)
* @return the type of the bean, or {@code null} if not predictable
*/
@Nullable
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
Class<?> targetType = mbd.getTargetType();
if (targetType != null) {
return targetType;
}
if (mbd.getFactoryMethodName() != null) {
return null;
}
return resolveBeanClass(mbd, beanName, typesToMatch);
}
/**
* Check whether the given bean is defined as a {@link FactoryBean}.
* @param beanName the name of the bean
* @param mbd the corresponding bean definition
*/
protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) {
Boolean result = mbd.isFactoryBean;
if (result == null) {
Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class);
result = (beanType != null && FactoryBean.class.isAssignableFrom(beanType));
mbd.isFactoryBean = result;
}
return result;
}
/**
* Determine the bean type for the given FactoryBean definition, as far as possible.
* Only called if there is no singleton instance registered for the target bean
* already. The implementation is allowed to instantiate the target factory bean if
* {@code allowInit} is {@code true} and the type cannot be determined another way;
* otherwise it is restricted to introspecting signatures and related metadata.
* <p>If no {@link FactoryBean#OBJECT_TYPE_ATTRIBUTE} if set on the bean definition
* and {@code allowInit} is {@code true}, the default implementation will create
* the FactoryBean via {@code getBean} to call its {@code getObjectType} method.
* Subclasses are encouraged to optimize this, typically by inspecting the generic
* signature of the factory bean class or the factory method that creates it.
* If subclasses do instantiate the FactoryBean, they should consider trying the
* {@code getObjectType} method without fully populating the bean. If this fails,
* a full FactoryBean creation as performed by this implementation should be used
* as fallback.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @param allowInit if initialization of the FactoryBean is permitted if the type
* cannot be determined another way
* @return the type for the bean if determinable, otherwise {@code ResolvableType.NONE}
* @since 5.2
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
* @see #getBean(String)
*/
protected ResolvableType getTypeForFactoryBean(String beanName, RootBeanDefinition mbd, boolean allowInit) {
ResolvableType result = getTypeForFactoryBeanFromAttributes(mbd);
if (result != ResolvableType.NONE) {
return result;
}
if (allowInit && mbd.isSingleton()) {
try {
FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
Class<?> objectType = getTypeForFactoryBean(factoryBean);
return (objectType != null ? ResolvableType.forClass(objectType) : ResolvableType.NONE);
}
catch (BeanCreationException ex) {
if (ex.contains(BeanCurrentlyInCreationException.class)) {
logger.trace(LogMessage.format("Bean currently in creation on FactoryBean type check: %s", ex));
}
else if (mbd.isLazyInit()) {
logger.trace(LogMessage.format("Bean creation exception on lazy FactoryBean type check: %s", ex));
}
else {
logger.debug(LogMessage.format("Bean creation exception on eager FactoryBean type check: %s", ex));
}
onSuppressedException(ex);
}
}
// FactoryBean type not resolvable
return ResolvableType.NONE;
}
/**
* Mark the specified bean as already created (or about to be created).
* <p>This allows the bean factory to optimize its caching for repeated
* creation of the specified bean.
* @param beanName the name of the bean
*/
protected void markBeanAsCreated(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
synchronized (this.mergedBeanDefinitions) {
if (!isBeanEligibleForMetadataCaching(beanName)) {
// Let the bean definition get re-merged now that we're actually creating
// the bean... just in case some of its metadata changed in the meantime.
clearMergedBeanDefinition(beanName);
}
this.alreadyCreated.add(beanName);
}
}
}
/**
* Perform appropriate cleanup of cached metadata after bean creation failed.
* @param beanName the name of the bean
*/
protected void cleanupAfterBeanCreationFailure(String beanName) {
synchronized (this.mergedBeanDefinitions) {
this.alreadyCreated.remove(beanName);
}
}
/**
* Determine whether the specified bean is eligible for having
* its bean definition metadata cached.
* @param beanName the name of the bean
* @return {@code true} if the bean's metadata may be cached
* at this point already
*/
protected boolean isBeanEligibleForMetadataCaching(String beanName) {
return this.alreadyCreated.contains(beanName);
}
/**
* Remove the singleton instance (if any) for the given bean name,
* but only if it hasn't been used for other purposes than type checking.
* @param beanName the name of the bean
* @return {@code true} if actually removed, {@code false} otherwise
*/
protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
removeSingleton(beanName);
return true;
}
else {
return false;
}
}
/**
* Check whether this factory's bean creation phase already started,
* i.e. whether any bean has been marked as created in the meantime.
* @since 4.2.2
* @see #markBeanAsCreated
*/
protected boolean hasBeanCreationStarted() {
return !this.alreadyCreated.isEmpty();
}
/**
* Get the object for the given bean instance, either the bean
* instance itself or its created object in case of a FactoryBean.
* @param beanInstance the shared bean instance
* @param name the name that may include factory dereference prefix
* @param beanName the canonical bean name
* @param mbd the merged bean definition
* @return the object to expose for the bean
*/
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
// Don't let calling code try to dereference the factory if the bean isn't a factory.
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (beanInstance instanceof NullBean) {
return beanInstance;
}
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
if (mbd != null) {
mbd.isFactoryBean = true;
}
return beanInstance;
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
if (!(beanInstance instanceof FactoryBean<?> factoryBean)) {
return beanInstance;
}
Object object = null;
if (mbd != null) {
mbd.isFactoryBean = true;
}
else {
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factoryBean, beanName, !synthetic);
}
return object;
}
/**
* Determine whether the given bean name is already in use within this factory,
* i.e. whether there is a local bean or alias registered under this name or
* an inner bean created with this name.
* @param beanName the name to check
*/
public boolean isBeanNameInUse(String beanName) {
return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName);
}
/**
* Determine whether the given bean requires destruction on shutdown.
* <p>The default implementation checks the DisposableBean interface as well as
* a specified destroy method and registered DestructionAwareBeanPostProcessors.
* @param bean the bean instance to check
* @param mbd the corresponding bean definition
* @see org.springframework.beans.factory.DisposableBean
* @see AbstractBeanDefinition#getDestroyMethodName()
* @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor
*/
protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
return (bean.getClass() != NullBean.class && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) ||
(hasDestructionAwareBeanPostProcessors() && DisposableBeanAdapter.hasApplicableProcessors(
bean, getBeanPostProcessorCache().destructionAware))));
}
/**
* Add the given bean to the list of disposable beans in this factory,
* registering its DisposableBean interface and/or the given destroy method
* to be called on factory shutdown (if applicable). Only applies to singletons.
* @param beanName the name of the bean
* @param bean the bean instance
* @param mbd the bean definition for the bean
* @see RootBeanDefinition#isSingleton
* @see RootBeanDefinition#getDependsOn
* @see #registerDisposableBean
* @see #registerDependentBean
*/
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
registerDisposableBean(beanName, new DisposableBeanAdapter(
bean, beanName, mbd, getBeanPostProcessorCache().destructionAware));
}
else {
// A bean with a custom scope...
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(
bean, beanName, mbd, getBeanPostProcessorCache().destructionAware));
}
}
}
//---------------------------------------------------------------------
// Abstract methods to be implemented by subclasses
//---------------------------------------------------------------------
/**
* Check if this bean factory contains a bean definition with the given name.
* Does not consider any hierarchy this factory may participate in.
* Invoked by {@code containsBean} when no cached singleton instance is found.
* <p>Depending on the nature of the concrete bean factory implementation,
* this operation might be expensive (for example, because of directory lookups
* in external registries). However, for listable bean factories, this usually
* just amounts to a local hash lookup: The operation is therefore part of the
* public interface there. The same implementation can serve for both this
* template method and the public interface method in that case.
* @param beanName the name of the bean to look for
* @return if this bean factory contains a bean definition with the given name
* @see #containsBean
* @see org.springframework.beans.factory.ListableBeanFactory#containsBeanDefinition
*/
protected abstract boolean containsBeanDefinition(String beanName);
/**
* Return the bean definition for the given bean name.
* Subclasses should normally implement caching, as this method is invoked
* by this class every time bean definition metadata is needed.
* <p>Depending on the nature of the concrete bean factory implementation,
* this operation might be expensive (for example, because of directory lookups
* in external registries). However, for listable bean factories, this usually
* just amounts to a local hash lookup: The operation is therefore part of the
* public interface there. The same implementation can serve for both this
* template method and the public interface method in that case.
* @param beanName the name of the bean to find a definition for
* @return the BeanDefinition for this prototype name (never {@code null})
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
* if the bean definition cannot be resolved
* @throws BeansException in case of errors
* @see RootBeanDefinition
* @see ChildBeanDefinition
* @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBeanDefinition
*/
protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;
/**
* Create a bean instance for the given merged bean definition (and arguments).
* The bean definition will already have been merged with the parent definition
* in case of a child definition.
* <p>All bean retrieval methods delegate to this method for actual bean creation.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a new instance of the bean
* @throws BeanCreationException if the bean could not be created
*/
protected abstract Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException;
/**
* CopyOnWriteArrayList which resets the beanPostProcessorCache field on modification.
*
* @since 5.3
*/
@SuppressWarnings("serial")
private class BeanPostProcessorCacheAwareList extends CopyOnWriteArrayList<BeanPostProcessor> {
@Override
public BeanPostProcessor set(int index, BeanPostProcessor element) {
BeanPostProcessor result = super.set(index, element);
resetBeanPostProcessorCache();
return result;
}
@Override
public boolean add(BeanPostProcessor o) {
boolean success = super.add(o);
resetBeanPostProcessorCache();
return success;
}
@Override
public void add(int index, BeanPostProcessor element) {
super.add(index, element);
resetBeanPostProcessorCache();
}
@Override
public BeanPostProcessor remove(int index) {
BeanPostProcessor result = super.remove(index);
resetBeanPostProcessorCache();
return result;
}
@Override
public boolean remove(Object o) {
boolean success = super.remove(o);
if (success) {
resetBeanPostProcessorCache();
}
return success;
}
@Override
public boolean removeAll(Collection<?> c) {
boolean success = super.removeAll(c);
if (success) {
resetBeanPostProcessorCache();
}
return success;
}
@Override
public boolean retainAll(Collection<?> c) {
boolean success = super.retainAll(c);
if (success) {
resetBeanPostProcessorCache();
}
return success;
}
@Override
public boolean addAll(Collection<? extends BeanPostProcessor> c) {
boolean success = super.addAll(c);
if (success) {
resetBeanPostProcessorCache();
}
return success;
}
@Override
public boolean addAll(int index, Collection<? extends BeanPostProcessor> c) {
boolean success = super.addAll(index, c);
if (success) {
resetBeanPostProcessorCache();
}
return success;
}
@Override
public boolean removeIf(Predicate<? super BeanPostProcessor> filter) {
boolean success = super.removeIf(filter);
if (success) {
resetBeanPostProcessorCache();
}
return success;
}
@Override
public void replaceAll(UnaryOperator<BeanPostProcessor> operator) {
super.replaceAll(operator);
resetBeanPostProcessorCache();
}
}
/**
* Internal cache of pre-filtered post-processors.
*
* @since 5.3
*/
static class BeanPostProcessorCache {
final List<InstantiationAwareBeanPostProcessor> instantiationAware = new ArrayList<>();
final List<SmartInstantiationAwareBeanPostProcessor> smartInstantiationAware = new ArrayList<>();
final List<DestructionAwareBeanPostProcessor> destructionAware = new ArrayList<>();
final List<MergedBeanDefinitionPostProcessor> mergedDefinition = new ArrayList<>();
}
}
|
package camera.toandoan.com.cameraproject;
import android.net.Uri;
import android.os.Environment;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
/**
* Created by doan.van.toan on 4/9/18.
*/
public class FileUtils {
private static final String APP_FOLDER = "MyCameraApp";
private static final java.lang.String DATE_FOR_MAT_YYYY_MM_DD_HH_MM_SS = "yyyyMMdd_HHmmss";
private static final java.lang.String IMAGE_ATTENDTION = ".jpg";
private static final java.lang.String VIDEO_ATTENDTION = ".mp4";
private FileUtils() {
}
public static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
public static File getOutputMediaFile(int type) {
File mediaStorageDir =
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
APP_FOLDER);
if (!mediaStorageDir.exists()) {
boolean makeDir = mediaStorageDir.mkdir();
if (!makeDir) {
return null;
}
}
String timeStamp = new SimpleDateFormat(DATE_FOR_MAT_YYYY_MM_DD_HH_MM_SS).format(new Date());
File mediaFile;
switch (type) {
default:
case MEDIA_TYPE_IMAGE:
mediaFile = new File(mediaStorageDir.getPath()
+ File.separator + "IMG_ "
+ timeStamp + IMAGE_ATTENDTION);
break;
case MEDIA_TYPE_VIDEO:
mediaFile = new File(mediaStorageDir.getPath()
+ File.separator + "VID_ "
+ timeStamp + VIDEO_ATTENDTION);
break;
}
return mediaFile;
}
}
|
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/*
* @lc app=leetcode.cn id=78 lang=java
*
* [78] 子集
*/
// @lc code=start
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> current = new LinkedList<>();
dfs(res, current, nums);
return res;
}
public void dfs(List<List<Integer>> res, LinkedList<Integer> currentIndex, int[] nums) {
res.add(indexToList(currentIndex, nums));
int last = currentIndex.isEmpty() ? -1 : currentIndex.getLast();
for (int i = last + 1; i < nums.length; i++) {
currentIndex.add(i);
dfs(res,currentIndex,nums);
currentIndex.removeLast();
}
}
public List<Integer> indexToList(List<Integer> index, int[] nums) {
Iterator<Integer> it = index.iterator();
List<Integer> res = new LinkedList<>();
while (it.hasNext()) {
res.add(nums[it.next()]);
}
return res;
}
}
// @lc code=end
|
package com.xwolf.eop.util;
/**
* <p>
* 字符串处理工具类
* </p>
*
* @author xwolf
* @date 2017-01-07 12:47
* @since V1.0.0
*/
public class StringUtil {
private static final String UNDERLINE="_";
/**
* 将驼峰命名法转化为_链接的字符串
* @param param
* @return
*/
public static String camelToUnderline(String param){
if (param==null||"".equals(param.trim())){
return "";
}
int len=param.length();
StringBuilder sb=new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c=param.charAt(i);
if (Character.isUpperCase(c)){
sb.append(UNDERLINE);
sb.append(Character.toLowerCase(c));
}else{
sb.append(c);
}
}
return sb.toString();
}
/**
* 将下划线转化为驼峰命名
* @return
*/
public static String underlineToCamel(String param){
int index=param.indexOf(UNDERLINE);
StringBuilder builder=new StringBuilder(param);
if(index!=-1){
char a=param.charAt(index+1);
builder.replace(index,index+2,String.valueOf(Character.toUpperCase(a)));
return underlineToCamel(builder.toString());
} else{
return builder.toString();
}
}
/**
* 防止SQL注入
* @param sql 原始字符串
* @return 处理后的字符串
*/
public static String escapeSql(String sql){
return org.apache.commons.lang.StringEscapeUtils.escapeSql(sql);
}
}
|
package me.waco001.companies;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Logger;
import lib.Databases.Database;
import lib.Databases.SQLite;
import me.waco001.companies.includes.Metrics;
//import me.waco001.companies.listeners.CommandListener;
import me.waco001.companies.listeners.PlayerListener;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin{
private PlayerListener PlayerListener = new PlayerListener(this);
public static Permission permission = null;
public static Economy economy = null;
static FileConfiguration config;
public static SQLite sqlite;
public final Logger logger = Logger.getLogger("Minecraft");
public void registerListeners(){
PluginManager pm = getServer().getPluginManager();
// Register The Listeners
pm.registerEvents(this.PlayerListener, this);
}
public void onEnable(){
registerListeners();
pluginCheck();
getLogger().info("---Companies Enabled---");
//getCommand("basic").setExecutor(new CommandListener());
sqlConnection();
sqlDoesDatabaseExist();
}
public void onDisable(){
try
{
sqlite.close();
}
catch (Exception e)
{
logger.info(e.getMessage());
getPluginLoader().disablePlugin(this);
}
getLogger().info("---Companies Disabled---");
}
private void pluginCheck() {
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
// :{ Oh No!
}
if (!setupEconomy() ) {
getLogger().severe(String.format("[%s] - Disabled due to no Vault dependency found!", getDescription().getName()));
getServer().getPluginManager().disablePlugin(this);
return;
}
if (setupEconomy()){
getLogger().info("Vault Dependencies found!");
}
setupPermissions();
this.saveDefaultConfig();
}
private boolean setupPermissions()
{
RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null) {
permission = permissionProvider.getProvider();
}
return (permission != null);
}
private boolean setupEconomy()
{
RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
return (economy != null);
}
//SQLite
public void sqlConnection()
{
sqlite = new SQLite(logger, "Companies", getDataFolder().getAbsolutePath() + "/database", "database");
try
{
sqlite.open();
}
catch (Exception e)
{
logger.info(e.getMessage());
getPluginLoader().disablePlugin(this);
}
}
public void sqlDoesDatabaseExist()
{
try {
getdb().query("CREATE TABLE IF NOT EXISTS companies (id INTEGER PRIMARY KEY, name STRING, short STRING, owner STRING);");
} catch (SQLException e) {
// TODO Auto- generated catch block
e.printStackTrace();
}
System.out.println("[Companies] Database Loaded.");
}
public static Database getdb()
{
return sqlite;
}
}
|
package revolt.backend.service;
import revolt.backend.dto.LiquidDto;
import java.util.List;
public interface LiquidService {
List<LiquidDto> getLiquids();
LiquidDto createLiquid(LiquidDto liquidDto);
LiquidDto getLiquid(Long id);
LiquidDto updateLiquid(LiquidDto liquidDto, Long liquidId);
void deleteLiquid(Long id);
}
|
package DataStructures.linkedlists;
/**
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
* If n is greater than the size of the list, remove the first node of the list.
Try doing it using constant additional space.
*/
public class RemoveNthNodeFromEnd {
public static ListNode removeNthFromEnd(ListNode a, int b) {
if (a == null || b < 1) return a;
ListNode fast = a;
ListNode prev = new ListNode(-1);
prev.next = a;
ListNode result = prev;
for (int i = 0; i < b; i++) {
if (fast == null)
fast = a;
fast = fast.next;
}
while (fast != null) {
fast = fast.next;
prev = prev.next;
}
if (prev.next != null) prev.next = prev.next.next;
return result.next;
}
public static void main(String s[]) {
//ListNode root = new LinkedList().buildLinkedList(new int[]{1, 2, 13, 20, 25}, new ListNode());
//ListNode root = new LinkedList().buildLinkedList(new int[]{1}, new ListNode());
int A[] = new int[]{20, 380, 349, 322, 389, 424, 429, 120, 64, 691, 677, 58, 327, 631, 916, 203, 484, 918, 596, 252, 509, 644, 33, 460};
int b = 82;
int len = A.length;
int rounds = b % A.length;
ListNode root = new LinkedList().buildLinkedList(A, new ListNode());
ListNode result = removeNthFromEnd(root, 82);
System.out.println(result);
}
}
|
package aeroportSpringTest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import aeroportSpring.model.Aeroport;
import aeroportSpring.model.Ville;
import aeroportSpring.repository.AeroportRepository;
import aeroportSpring.repository.VilleRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/application-context.xml" })
@Rollback(true)
public class VilleRepositoryTest extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired
private VilleRepository villeRepository;
@Autowired
private AeroportRepository aeroportRepository;
@Test
// créer une entrée
public void testInsert() {
Ville ville = new Ville("Tokyo");
villeRepository.save(ville);
Optional<Ville> opt = villeRepository.findById(ville.getIdVille());
opt.isPresent();
assertTrue(opt.isPresent());
}
@Test
// on teste qu'on trouve bien la ville Tokyo
public void findByNomVille() {
Ville ville = new Ville("Tokyo");
villeRepository.save(ville);
assertNotNull(villeRepository.findByNomVille("Tokyo"));
}
@Test
// on teste que l'aéroport AeroTest appartient bien à la ville Tokyo
public void findByAeroport() {
Ville ville = new Ville("Tokyo");
villeRepository.save(ville);
Aeroport aeroport = new Aeroport("AeroTest");
aeroport.setVilleAeroport(ville);
aeroportRepository.save(aeroport);
Ville result = villeRepository.findByAeroport(aeroport);
assertNotNull(result);
assertEquals("Tokyo", result.getNomVille());
}
@Test
// on teste que les deux villes ressortent quand on chetrche l'aéroport
// AeroTest2
public void findByNomAeroport() {
// on crée deux villes différentes
Ville ville = new Ville("Tokyo");
villeRepository.save(ville);
Ville ville1 = new Ville("Paris");
villeRepository.save(ville1);
// on crée deux aéroports du même nom dans deux villes différentes
Aeroport aeroport = new Aeroport("AeroTest2");
aeroport.setVilleAeroport(ville);
aeroportRepository.save(aeroport);
Aeroport aeroport1 = new Aeroport("AeroTest2");
aeroport1.setVilleAeroport(ville1);
aeroportRepository.save(aeroport1);
List<Ville> villes = villeRepository.findByNomAeroport("AeroTest2");
assertEquals(2, villes.size());
}
}
|
package com.javarush.task.task14.task1409;
public class WaterBridge implements Bridge {
public static int cars = 3;
public int getCarsCount(){
return cars;
}
}
|
package edu.unm.cs.blites.co_lect;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.Collections;
import java.util.List;
/**
* Created by Brandon on 5/4/2015.
*/
public class PlatformItemListAdapter extends RecyclerView.Adapter<PlatformItemListAdapter.myViewHolder> {
public LayoutInflater inflater;
List<PlatformItem> platformItems = Collections.emptyList();
public final ImageLoader imageLoader;
public PlatformItemListAdapter(Context context, List<PlatformItem> platformItems, ImageLoader imageLoader) {
inflater = LayoutInflater.from(context);
this.platformItems = platformItems;
this.imageLoader = imageLoader;
}
@Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.platform_list_single, parent, false);
myViewHolder holder = new myViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(myViewHolder holder, int position) {
PlatformItem currentItem = platformItems.get(position);
String platformTitle = currentItem.getPlatformTitle();
String platformId = currentItem.getPlatformId();
int numberOfItems = currentItem.getNumOfItems();
String imageUrl = currentItem.getImageUrl();
holder.title.setText(platformTitle);
if (numberOfItems == 1) {
holder.numberOfItems.setText(numberOfItems + " item");
}
else holder.numberOfItems.setText(numberOfItems + " items");
holder.myImageView.setImageUrl(imageUrl, imageLoader);
}
@Override
public int getItemCount() {
return platformItems.size();
}
/******************************************************************
*
*/
class myViewHolder extends RecyclerView.ViewHolder {
NetworkImageView myImageView;
TextView title;
TextView numberOfItems;
public myViewHolder (View itemView) {
super(itemView);
myImageView = (NetworkImageView) itemView.findViewById(R.id.platform_image_frame);
myImageView.setDefaultImageResId(R.drawable.no_image);
title = (TextView) itemView.findViewById(R.id.platform_title);
numberOfItems = (TextView) itemView.findViewById(R.id.platform_number);
}
}
}
|
package wawi.datenhaltung.bestellungverwaltungs.service;
import java.util.List;
import javax.persistence.EntityManager;
import wawi.datenhaltung.wawidbmodel.entities.Produkt;
/**
*
* @author Oliver (Local)
*/
public interface IKundeService {
public void setEntityManager(EntityManager em);
public List<Produkt> getAktiveProdukte();
}
|
/*
* $Id$
*
* ### Copyright (C) 2006 Michael Fuchs ###
* ### All Rights Reserved. ###
*
* Author: Michael Fuchs
* E-Mail: michael.fuchs@unico-group.com
* URL: http://www.michael-a-fuchs.de
*/
package org.dbdoclet.tidbit.medium.javahelp;
import java.io.File;
import java.text.MessageFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dbdoclet.jive.dialog.ErrorBox;
import org.dbdoclet.service.ExecResult;
import org.dbdoclet.service.ExecServices;
import org.dbdoclet.service.FileServices;
import org.dbdoclet.service.ResourceServices;
import org.dbdoclet.tidbit.common.Output;
import org.dbdoclet.tidbit.common.StaticContext;
import org.dbdoclet.tidbit.medium.Generator;
public class JavaHelpGenerator extends Generator {
private static Log logger = LogFactory.getLog(JavaHelpGenerator.class);
public JavaHelpGenerator() {
super();
setTarget("dbdoclet.docbook.javahelp");
}
@Override
public void run() {
File tsFile = null;
try {
String path = project.getFileManager().getDocBookFileName();
File file = new File(path);
if (file.exists() == false) {
String msg = MessageFormat.format(ResourceServices.getString(
res, "C_ERROR_FILE_DOESNT_EXIST"), file
.getAbsolutePath());
ErrorBox.show(StaticContext.getDialogOwner(),
ResourceServices.getString(res, "C_ERROR"), msg);
return;
}
tsFile = File.createTempFile("dbd-javahelp", ".ts");
ExecResult result = executeAntTarget();
if (buildFailed(result)) {
return;
}
File baseDir = getBaseDir(project.getDriver(Output.javahelp));
relocateHtml(baseDir, Output.javahelp);
String hsPath = FileServices.appendPath(baseDir, "jhelpset.hs");
if (hsPath != null) {
final File hsFile = new File(hsPath);
if (hsFile.exists() == true
&& FileServices.newer(hsFile, tsFile)) {
File jdkHome = project.getJdkHome();
String javaCmd = FileServices.appendPath(jdkHome, "bin");
javaCmd = FileServices.appendFileName(javaCmd, "java");
String jarFileName = FileServices.appendPath(
StaticContext.getHome(), "jars");
jarFileName = FileServices.appendFileName(jarFileName,
"jhrun.jar");
String[] cmd = new String[4];
cmd[0] = javaCmd;
cmd[1] = "-jar";
cmd[2] = jarFileName;
cmd[3] = "--file=" + hsFile.getCanonicalPath();
ExecServices.exec(cmd, null, null, true, this);
} else {
logger.warn("Couldn't find helpSet " + hsPath);
}
}
} catch (Throwable oops) {
messageListener.fatal("JavaHelpGenerator", oops);
} finally {
if (tsFile != null) {
tsFile.delete();
}
finished();
}
}
}
|
/*
* 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 siralamaalgoritmalari;
/**
*
* @author minter
*/
public class SiralamaAlgoritmalari {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int[] array = {9, 7, 8, 1, 5, 4, 3, 2, 6};
selectionSort(array);
print(array);
}
//selection sort
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[minIndex] > array[j]) {
minIndex = j;
}
}
if (i != minIndex) {
int tmp = array[i];
array[i] = array[minIndex];
array[minIndex] = tmp;
}
}
}
//insertionSort
public static void insertionSort(int[] array) {
for (int i = 1; i < array.length; i++) {
int currentElement = array[i];
int j = i - 1;
while (j >= 0 && currentElement < array[j]) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = currentElement;
}
}
//bubleSort
public static void bubleSort(int[] array) {
for (int i = 1; i < array.length; i++) {
boolean isSwapped = false;
for (int j = 0; j < array.length - i; j++) {
if (array[j] > array[j + 1]) {
isSwapped = true;
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
System.out.print(i + ". pass : ");
print(array);
if (!isSwapped) {
System.out.println(array.length + " numbers sorted in " + i + " passes");
break;
}
}
}
public static void print(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
|
package com.auto.pages;
public interface BasePage {
}
|
package tech.liujin.drawable.progress.load;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import tech.liujin.drawable.progress.ProgressDrawable;
/**
* @author wuxio 2018-05-12:23:15
*/
public class CirclePathDrawable extends ProgressDrawable {
private Path mSrcPath;
private PathMeasure mPathMeasure;
private Path mDstPath;
private int mSize;
private float mLength;
public CirclePathDrawable ( ) {
super();
mPaint.setStyle( Paint.Style.STROKE );
mSrcPath = new Path();
mDstPath = new Path();
mPathMeasure = new PathMeasure();
}
@Override
protected void onBoundsChange ( Rect bounds ) {
mSize = Math.min( bounds.width(), bounds.height() );
float strokeWidth = mSize / 20;
mPaint.setStrokeWidth( strokeWidth );
RectF rectF = new RectF();
rectF.set(
strokeWidth / 2,
strokeWidth / 2,
mSize - strokeWidth / 2,
mSize - strokeWidth / 2
);
mSrcPath.reset();
mSrcPath.addArc( rectF, -90, 359.9f );
mPathMeasure.setPath( mSrcPath, true );
mLength = mPathMeasure.getLength();
super.onBoundsChange( bounds );
}
@Override
public void draw ( @NonNull Canvas canvas ) {
int width = getWidth();
int height = getHeight();
int dX = ( width - mSize ) >> 1;
int dY = ( height - mSize ) >> 1;
canvas.translate( dX, dY );
canvas.drawPath( mDstPath, mPaint );
}
@Override
public void onProcessChange ( float progress ) {
mProgress = progress;
mDstPath.reset();
mDstPath.moveTo( mSize >> 1, 0 );
final float middle = 0.5f;
if( progress <= middle ) {
mPathMeasure.getSegment(
0,
mLength * progress * 2,
mDstPath,
true
);
} else {
mPathMeasure.getSegment(
mLength * ( progress - 0.5f ) * 2,
mLength,
mDstPath,
true
);
}
invalidateSelf();
}
}
|
public class LC167 {
static int[] twoSum(int[] numbers, int target) {
/*方法一:暴力改进法
int[] res=new int[2];
for(int i=numbers.length-1;i>= 0;i--){
if(target>=numbers[i]){
for(int j=0;j<numbers.length;j++){
if(numbers[i]+numbers[j]==target){
res[0]=i<j?i+1:j+1;
res[1]=i>j?i+1:j+1;
}
}
}
}
return res;*/
int[] res=new int[2];
int rt=0,lf=numbers.length-1;
while(rt<lf){
int tmp=numbers[rt]+numbers[lf];
if(tmp==target){
res[0]=rt+1;res[1]=lf+1;
break;
}
if(tmp<target){
rt++;
}
if(tmp>target){
lf--;
}
}
return res;
}
public static void main(String[] args) {
int[] nums1= {2, 7, 11, 15};
int n=9;
int[] num=twoSum(nums1,n);
System.out.print(num[0]+" "+num[1]);
}
}
|
package ch.zhaw.prog2.io.picturedb;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
/**
* Implements the PictureDatasource Interface storing the data in
* Character Separated Values (CSV) format, where each line consists of a record
* whose fields are separated by the DELIMITER ";"
* See example file: db/picture-data.csv
*/
public class FilePictureDatasource implements PictureDatasource {
private static final String DELIMITER = ";";
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final DateFormat DF = new SimpleDateFormat(DATE_FORMAT);
private static final Charset CHARSET = StandardCharsets.UTF_8;
private String filePath;
/**
* Creates the FilePictureDatasource with the given file as datafile.
*
* @param filepath of the file to use as database file.
* @throws IOException if accessing or creating the file failes
*/
public FilePictureDatasource(String filepath) throws IOException {
this.filePath = filepath;
}
@Override
public void insert(Picture picture) {
}
@Override
public void update(Picture picture) throws RecordNotFoundException {
}
@Override
public void delete(Picture picture) throws RecordNotFoundException {
}
@Override
public int count() {
return 0;
}
@Override
public Picture findById(int id) {
return null;
}
@Override
public Collection<Picture> findAll() {
return null;
}
@Override
public Collection<Picture> findByPosition(float longitude, float latitude, float deviation) {
return null;
}
}
|
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.border.EmptyBorder;
import javax.swing.*;
import java.awt.Color;
import java.awt.Font;
public class PlanWindow extends JFrame {
private JPanel contentPane = new JPanel();
private ArrayList<Plan> planList = new ArrayList<Plan>();
private ArrayList<JButton> buttonList = new ArrayList<JButton>();
private User user = new User( "","","","");
private Plan plan = new Plan("","","");
private String cityName;
private String userSName;
PlanViewer planView = new PlanViewer("","","");
private String description = "";
private JLabel planLabel;
private ImageIcon planImage = new ImageIcon(getClass().getResource("beach.jpg"));
/**
* Launch the application.
*/
public void planWindow(String text, String text2) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PlanWindow planWindow = new PlanWindow();
cityName = text;
userSName = text2;
user = user.getUserByScan(userSName);
planList = plan.getPlanList(cityName);
organiseButtons();
lblNewLabel.setText(text);
setVisible(true);
revalidate();
repaint();
planList.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
private JLabel lblNewLabel;
public PlanWindow() {
setTitle("Plans");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 747, 525);
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(0, 0, 600, 500));
setContentPane(contentPane);
contentPane.setLayout(null);
lblNewLabel = new JLabel("New label");
lblNewLabel.setBackground(Color.WHITE);
lblNewLabel.setBounds(34, 167, 93, 50);
contentPane.add(lblNewLabel);
JButton btnNewButton = new JButton("New button");
btnNewButton.setForeground(new Color(102, 0, 153));
btnNewButton.setBackground(Color.WHITE);
btnNewButton.setBounds(466, 304, 174, 57);
btnNewButton.setVisible(false);
contentPane.add(btnNewButton);
buttonList.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setForeground(new Color(102, 0, 153));
btnNewButton_1.setBackground(Color.WHITE);
btnNewButton_1.setVisible(false);
btnNewButton_1.setBounds(34, 307, 170, 50);
contentPane.add(btnNewButton_1);
buttonList.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("New button");
btnNewButton_2.setForeground(new Color(102, 0, 153));
btnNewButton_2.setBackground(Color.WHITE);
btnNewButton_2.setVisible(false);
btnNewButton_2.setBounds(466, 227, 174, 57);
contentPane.add(btnNewButton_2);
buttonList.add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("New button");
btnNewButton_3.setForeground(new Color(102, 0, 153));
btnNewButton_3.setBackground(Color.WHITE);
btnNewButton_3.setVisible(false);
btnNewButton_3.setBounds(34, 227, 174, 57);
contentPane.add(btnNewButton_3);
buttonList.add(btnNewButton_3);
JButton btnNewButton_4 = new JButton("New button");
btnNewButton_4.setForeground(new Color(102, 0, 153));
btnNewButton_4.setBackground(Color.WHITE);
btnNewButton_4.setVisible(false);
btnNewButton_4.setBounds(70, 409, 89, 23);
contentPane.add(btnNewButton_4);
buttonList.add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("New button");
btnNewButton_5.setForeground(new Color(102, 0, 153));
btnNewButton_5.setBackground(Color.WHITE);
btnNewButton_5.setVisible(false);
btnNewButton_5.setBounds(70, 376, 89, 23);
contentPane.add(btnNewButton_5);
buttonList.add(btnNewButton_5);
JButton btnNewButton_6 = new JButton("New button");
btnNewButton_6.setForeground(new Color(102, 0, 153));
btnNewButton_6.setBackground(Color.WHITE);
btnNewButton_6.setVisible(false);
btnNewButton_6.setBounds(516, 409, 89, 23);
contentPane.add(btnNewButton_6);
buttonList.add(btnNewButton_6);
JButton btnNewButton_7 = new JButton("New button");
btnNewButton_7.setForeground(new Color(102, 0, 153));
btnNewButton_7.setBackground(Color.WHITE);
btnNewButton_7.setVisible(false);
btnNewButton_7.setBounds(516, 376, 89, 23);
contentPane.add(btnNewButton_7);
buttonList.add(btnNewButton_7);
JTextPane txtpnHereAreThe = new JTextPane();
txtpnHereAreThe.setFont(new Font("Arial", Font.BOLD, 15));
txtpnHereAreThe.setEditable(false);
txtpnHereAreThe.setForeground(Color.WHITE);
txtpnHereAreThe.setBackground(new Color(102, 0, 153));
txtpnHereAreThe.setText("Here are the plans we prepared for you. With the plans you will be able to evaluate your time in the most beatiful way.");
txtpnHereAreThe.setBounds(253, 227, 170, 134);
contentPane.add(txtpnHereAreThe);
JButton btnMainMenu = new JButton("Main Menu");
btnMainMenu.setForeground(new Color(102, 0, 153));
btnMainMenu.setBackground(Color.WHITE);
btnMainMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
MainMenu main = new MainMenu();
setVisible(false);
main.newScreen(main.getUserName());
}
});
btnMainMenu.setBounds(10, 456, 132, 23);
contentPane.add(btnMainMenu);
JButton btnMyProfile = new JButton("My Profile");
btnMyProfile.setForeground(new Color(102, 0, 153));
btnMyProfile.setBackground(Color.WHITE);
btnMyProfile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
MyProfile profile = new MyProfile();
MainMenu main = new MainMenu();
setVisible(false);
profile.newScreen(main.getUserName());
}
});
btnMyProfile.setBounds(163, 456, 141, 23);
contentPane.add(btnMyProfile);
JPanel panel = new JPanel();
panel.setBackground(new Color(102, 0, 153));
panel.setBounds(0, 0, 742, 39);
contentPane.add(panel);
JLabel label = new JLabel("Trippin'");
label.setForeground(Color.WHITE);
label.setFont(new Font("Arial", Font.BOLD, 24));
panel.add(label);
planLabel = new JLabel(planImage);
planLabel.setBounds(91, 28, 570, 159);
contentPane.add(planLabel);
}
public void setPlanText( String str)
{
lblNewLabel.setText(str);
}
public void addButton(JButton button)
{
contentPane.add(button);
}
public JPanel getContentPane()
{
return contentPane;
}
public void organiseButtons()
{
for(int x = 0;x < planList.size();x++)
{
System.out.println("for: " + description);
description = planList.get(x).getDescription();
buttonList.get(x).setText(planList.get(x).getPlanName());
buttonList.get(x).addActionListener(new PlanGo());
buttonList.get(x).setVisible(true);
}
}
public String getDescription()
{
return description;
}
public class PlanGo implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton dupeButton = (JButton)e.getSource();
if(plan.planExist(dupeButton.getText()))
{
Plan plan2 = plan.getPlanByName(dupeButton.getText());
planView.PlanView( plan2.getDescription(), user.getUserName(), dupeButton.getText());
}
else
{
planView.PlanView("We are working on new plans!", "", "");
}
}
public PlanGo()
{
planView.setPlanText(getDescription());
}
}
}
|
package com.example.zeal.rxjava;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* @作者 廖伟健
* @创建时间 2017/3/27 15:23
* @描述 通过 createService() 创建 HttpService
*/
public class ServiceGenerator {
private static String API_BASE_URL = "http://app.pjob.net/";
// private static HttpLoggingInterceptor logging = new
// HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
// /*
// 每一个请求都需要带一个请求参数:platform=Android
// 这样服务器就可以辨别该接口是由Android调用的,而不是iOS调用的。
// */
// private static Interceptor commonQueryParamsInterceptor = new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
//
// Request original = chain.request();
//
// HttpUrl httpUrl = original.url().newBuilder().addQueryParameter("platform",
// "Android").build();
//
// Request.Builder requestBuilder = original.newBuilder().url(httpUrl);
//
// Request request = requestBuilder.build();
// return chain.proceed(request);
// }
// };
//
// //统一添加自定义header不成功
// private static Interceptor commonIntercept = new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// //header():表示若先前存在同一样的key的header将会被覆盖
// //addHeader:表示若是先前存在同一样的key的header也不会有关系,不会将其覆盖
// Request request = chain.request().newBuilder()//
// .addHeader("Cache-Control", "no-cache")//
// .header("Cache-Control", "no-store")//
// .build();
//
// return chain.proceed(request);
// }
// };
//
// private static Interceptor networkStateIntercept = new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
//
// if(! NetworkUtil.isNetworkAvailable(SmartDoApplication.getContext())) {
// return chain.proceed(chain.request());
// } else {
// throw new NetworkException();
// }
//
// }
// };
//
//
// private static OkHttpClient.Builder okhttpClient = new OkHttpClient.Builder()//
// .addInterceptor(commonIntercept)//
// .addInterceptor(logging)//
// .addInterceptor(networkStateIntercept)//
// .addInterceptor(commonQueryParamsInterceptor);
//
//
// private static Retrofit.Builder retrofitBuilder =//
// new Retrofit.Builder()//
// .baseUrl(API_BASE_URL)//
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create());
// private static Retrofit retrofit = retrofitBuilder.client(okhttpClient
// .build()
// ).build();
// public static HttpService createService() {
// // if(! okhttpClient.interceptors().contains(logging)) {
// // okhttpClient.addInterceptor(logging);
// // retrofitBuilder.client(okhttpClient.build());
// // retrofit = retrofitBuilder.client(okhttpClient.build()).build();
// // }
// // if(! okhttpClient.interceptors().contains(commonIntercept)) {
// // okhttpClient.addInterceptor(commonIntercept);
// // retrofitBuilder.client(okhttpClient.build());
// // retrofit = retrofitBuilder.client(okhttpClient.build()).build();
// // }
// // if(! okhttpClient.interceptors().contains(commonQueryParamsInterceptor)) {
// // okhttpClient.addInterceptor(commonQueryParamsInterceptor);
// // retrofitBuilder.client(okhttpClient.build());
// // retrofit = retrofitBuilder.client(okhttpClient.build()).build();
// // }
// HttpService httpService = retrofit.create(HttpService.class);
// return retrofit.create(HttpService.class);
// }
//---
private static Retrofit sInstance;
private ServiceGenerator() {}
private static Retrofit getInstance() {
if(sInstance == null) {
synchronized (ServiceGenerator.class) {
sInstance = new Retrofit.Builder()//
.baseUrl(API_BASE_URL)//基地址
.client(buildOkHttpClient())
// Gson 处理解析
.addConverterFactory(GsonConverterFactory.create())
//集成 RxJava 处理
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
}
}
// Gson gson = new Gson();
// Type type = new TypeToken<List<Demo>>(){}.getType();
// return gson.fromJson(jsonString, type);
return sInstance;
}
/**
* 构建 OkHttpClient 对象
* 拦截器配置
* 超时事件配置
* 缓存配置
*/
private static OkHttpClient buildOkHttpClient() {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
//日志显示级别,这里需要根据是否为 debug 版本进行判断是否要显示 TODO
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Map<String, String> params = new HashMap<>();
//TODO 添加公共参数
return new OkHttpClient.Builder()//
//日志拦截器
.addInterceptor(httpLoggingInterceptor)//
//添加动态参数
.addInterceptor(new DynamicParamsIntercptor(params))//
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
})
//自动重连
.retryOnConnectionFailure(true)//
//超时配置
.readTimeout(15, TimeUnit.SECONDS)//
.readTimeout(15, TimeUnit.SECONDS)//
.connectTimeout(15, TimeUnit.SECONDS)//
.build();
}
public static HttpService createService() {
return getInstance().create(HttpService.class);
}
}
|
//
// Decompiled by Procyon v0.5.36
//
package com.davivienda.sara.procesos.reintegros.filtro.host.session;
import java.io.FileNotFoundException;
import com.davivienda.sara.base.exception.EntityServicioExcepcion;
import java.util.Calendar;
import javax.ejb.Local;
@Local
public interface ProcesoHostSessionLocal
{
Integer CargarArchivo(final Calendar p0) throws EntityServicioExcepcion, FileNotFoundException, IllegalArgumentException;
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.serpientesescaleras.excepciones;
import javax.swing.JOptionPane;
/**
*
* @author nroda
*/
public class ManejadorExcepciones {
//Metodos
//Verifica que se ingresaron los dos iD
public static void evaluarCampoVacioId(String uno, String dos) throws ExceptionVacio{
if (uno.isBlank()) {
throw new ExceptionVacio("Ingresa el id del primer Jugador");
} else if (dos.isBlank()){
throw new ExceptionVacio("Ingresa el id del segundo Jugador");
}
}
//Verifica que se ingresaron los tres id
public static void evaluarCampoVacioId(String uno, String dos, String tres) throws ExceptionVacio{
if (uno.isBlank()) {
throw new ExceptionVacio("Ingresa el id del primer Jugador");
} else if (dos.isBlank()){
throw new ExceptionVacio("Ingresa el id del segundo Jugador");
} else if (tres.isBlank()) {
throw new ExceptionVacio("Ingresa el id del tercer Jugador");
}
}
//Verifica que se ingresaron los cuatro id
public static void evaluarCampoVacioId(String uno, String dos, String tres, String cuatro) throws ExceptionVacio{
if (uno.isBlank()) {
throw new ExceptionVacio("Ingresa el id del primer Jugador");
} else if (dos.isBlank()){
throw new ExceptionVacio("Ingresa el id del segundo Jugador");
} else if (tres.isBlank()) {
throw new ExceptionVacio("Ingresa el id del tercer Jugador");
} else if (cuatro.isBlank()) {
throw new ExceptionVacio("Ingresa el id del cuarto Jugador");
}
}
//Verifica si ingreso sus datos
public static void evaluarSiEstaVacio(String nombre, String apellido) throws ExceptionVacio{
if (nombre.isEmpty()) {
throw new ExceptionVacio("Ingresa el nombre del Jugador");
} else if (apellido.isEmpty()) {
throw new ExceptionVacio("Ingresa el apellido Jugador");
}
}
}
|
package cn.novelweb.tool.upload.fastdfs.protocol.storage.callback;
import java.io.IOException;
import java.io.InputStream;
/**
* <p>文件下载回调接口</p>
* <p>2020-02-03 16:48</p>
*
* @author LiZW
**/
public interface DownloadCallback<T> {
/**
* 注意不能直接返回入参的InputStream,因为此方法返回后将关闭原输入流<br/>
* 不能关闭inputStream? TODO 验证是否可以关闭
*
* @param inputStream 返回数据输入流
* @return receive
* @throws IOException IO异常
*/
T receive(InputStream inputStream) throws IOException;
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context.request.async;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.async.DeferredResult.DeferredResultHandler;
/**
* The central class for managing asynchronous request processing, mainly intended
* as an SPI and not typically used directly by application classes.
*
* <p>An async scenario starts with request processing as usual in a thread (T1).
* Concurrent request handling can be initiated by calling
* {@link #startCallableProcessing(Callable, Object...) startCallableProcessing} or
* {@link #startDeferredResultProcessing(DeferredResult, Object...) startDeferredResultProcessing},
* both of which produce a result in a separate thread (T2). The result is saved
* and the request dispatched to the container, to resume processing with the saved
* result in a third thread (T3). Within the dispatched thread (T3), the saved
* result can be accessed via {@link #getConcurrentResult()} or its presence
* detected via {@link #hasConcurrentResult()}.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.2
* @see org.springframework.web.context.request.AsyncWebRequestInterceptor
* @see org.springframework.web.servlet.AsyncHandlerInterceptor
* @see org.springframework.web.filter.OncePerRequestFilter#shouldNotFilterAsyncDispatch
* @see org.springframework.web.filter.OncePerRequestFilter#isAsyncDispatch
*/
public final class WebAsyncManager {
private static final Object RESULT_NONE = new Object();
private static final AsyncTaskExecutor DEFAULT_TASK_EXECUTOR =
new SimpleAsyncTaskExecutor(WebAsyncManager.class.getSimpleName());
private static final Log logger = LogFactory.getLog(WebAsyncManager.class);
private static final CallableProcessingInterceptor timeoutCallableInterceptor =
new TimeoutCallableProcessingInterceptor();
private static final DeferredResultProcessingInterceptor timeoutDeferredResultInterceptor =
new TimeoutDeferredResultProcessingInterceptor();
@Nullable
private AsyncWebRequest asyncWebRequest;
private AsyncTaskExecutor taskExecutor = DEFAULT_TASK_EXECUTOR;
@Nullable
private volatile Object concurrentResult = RESULT_NONE;
@Nullable
private volatile Object[] concurrentResultContext;
/*
* Whether the concurrentResult is an error. If such errors remain unhandled, some
* Servlet containers will call AsyncListener#onError at the end, after the ASYNC
* and/or the ERROR dispatch (Boot's case), and we need to ignore those.
*/
private volatile boolean errorHandlingInProgress;
private final Map<Object, CallableProcessingInterceptor> callableInterceptors = new LinkedHashMap<>();
private final Map<Object, DeferredResultProcessingInterceptor> deferredResultInterceptors = new LinkedHashMap<>();
/**
* Package-private constructor.
* @see WebAsyncUtils#getAsyncManager(jakarta.servlet.ServletRequest)
* @see WebAsyncUtils#getAsyncManager(org.springframework.web.context.request.WebRequest)
*/
WebAsyncManager() {
}
/**
* Configure the {@link AsyncWebRequest} to use. This property may be set
* more than once during a single request to accurately reflect the current
* state of the request (e.g. following a forward, request/response
* wrapping, etc). However, it should not be set while concurrent handling
* is in progress, i.e. while {@link #isConcurrentHandlingStarted()} is
* {@code true}.
* @param asyncWebRequest the web request to use
*/
public void setAsyncWebRequest(AsyncWebRequest asyncWebRequest) {
Assert.notNull(asyncWebRequest, "AsyncWebRequest must not be null");
this.asyncWebRequest = asyncWebRequest;
this.asyncWebRequest.addCompletionHandler(() -> asyncWebRequest.removeAttribute(
WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST));
}
/**
* Configure an AsyncTaskExecutor for use with concurrent processing via
* {@link #startCallableProcessing(Callable, Object...)}.
* <p>By default a {@link SimpleAsyncTaskExecutor} instance is used.
*/
public void setTaskExecutor(AsyncTaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Whether the selected handler for the current request chose to handle the
* request asynchronously. A return value of "true" indicates concurrent
* handling is under way and the response will remain open. A return value
* of "false" means concurrent handling was either not started or possibly
* that it has completed and the request was dispatched for further
* processing of the concurrent result.
*/
public boolean isConcurrentHandlingStarted() {
return (this.asyncWebRequest != null && this.asyncWebRequest.isAsyncStarted());
}
/**
* Whether a result value exists as a result of concurrent handling.
*/
public boolean hasConcurrentResult() {
return (this.concurrentResult != RESULT_NONE);
}
/**
* Provides access to the result from concurrent handling.
* @return an Object, possibly an {@code Exception} or {@code Throwable} if
* concurrent handling raised one.
* @see #clearConcurrentResult()
*/
public Object getConcurrentResult() {
return this.concurrentResult;
}
/**
* Provides access to additional processing context saved at the start of
* concurrent handling.
* @see #clearConcurrentResult()
*/
@Nullable
public Object[] getConcurrentResultContext() {
return this.concurrentResultContext;
}
/**
* Get the {@link CallableProcessingInterceptor} registered under the given key.
* @param key the key
* @return the interceptor registered under that key, or {@code null} if none
*/
@Nullable
public CallableProcessingInterceptor getCallableInterceptor(Object key) {
return this.callableInterceptors.get(key);
}
/**
* Get the {@link DeferredResultProcessingInterceptor} registered under the given key.
* @param key the key
* @return the interceptor registered under that key, or {@code null} if none
*/
@Nullable
public DeferredResultProcessingInterceptor getDeferredResultInterceptor(Object key) {
return this.deferredResultInterceptors.get(key);
}
/**
* Register a {@link CallableProcessingInterceptor} under the given key.
* @param key the key
* @param interceptor the interceptor to register
*/
public void registerCallableInterceptor(Object key, CallableProcessingInterceptor interceptor) {
Assert.notNull(key, "Key is required");
Assert.notNull(interceptor, "CallableProcessingInterceptor is required");
this.callableInterceptors.put(key, interceptor);
}
/**
* Register a {@link CallableProcessingInterceptor} without a key.
* The key is derived from the class name and hashcode.
* @param interceptors one or more interceptors to register
*/
public void registerCallableInterceptors(CallableProcessingInterceptor... interceptors) {
Assert.notNull(interceptors, "A CallableProcessingInterceptor is required");
for (CallableProcessingInterceptor interceptor : interceptors) {
String key = interceptor.getClass().getName() + ":" + interceptor.hashCode();
this.callableInterceptors.put(key, interceptor);
}
}
/**
* Register a {@link DeferredResultProcessingInterceptor} under the given key.
* @param key the key
* @param interceptor the interceptor to register
*/
public void registerDeferredResultInterceptor(Object key, DeferredResultProcessingInterceptor interceptor) {
Assert.notNull(key, "Key is required");
Assert.notNull(interceptor, "DeferredResultProcessingInterceptor is required");
this.deferredResultInterceptors.put(key, interceptor);
}
/**
* Register one or more {@link DeferredResultProcessingInterceptor DeferredResultProcessingInterceptors} without a specified key.
* The default key is derived from the interceptor class name and hash code.
* @param interceptors one or more interceptors to register
*/
public void registerDeferredResultInterceptors(DeferredResultProcessingInterceptor... interceptors) {
Assert.notNull(interceptors, "A DeferredResultProcessingInterceptor is required");
for (DeferredResultProcessingInterceptor interceptor : interceptors) {
String key = interceptor.getClass().getName() + ":" + interceptor.hashCode();
this.deferredResultInterceptors.put(key, interceptor);
}
}
/**
* Clear {@linkplain #getConcurrentResult() concurrentResult} and
* {@linkplain #getConcurrentResultContext() concurrentResultContext}.
*/
public void clearConcurrentResult() {
synchronized (WebAsyncManager.this) {
this.concurrentResult = RESULT_NONE;
this.concurrentResultContext = null;
}
}
/**
* Start concurrent request processing and execute the given task with an
* {@link #setTaskExecutor(AsyncTaskExecutor) AsyncTaskExecutor}. The result
* from the task execution is saved and the request dispatched in order to
* resume processing of that result. If the task raises an Exception then
* the saved result will be the raised Exception.
* @param callable a unit of work to be executed asynchronously
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
* @throws Exception if concurrent processing failed to start
* @see #getConcurrentResult()
* @see #getConcurrentResultContext()
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public void startCallableProcessing(Callable<?> callable, Object... processingContext) throws Exception {
Assert.notNull(callable, "Callable must not be null");
startCallableProcessing(new WebAsyncTask(callable), processingContext);
}
/**
* Use the given {@link WebAsyncTask} to configure the task executor as well as
* the timeout value of the {@code AsyncWebRequest} before delegating to
* {@link #startCallableProcessing(Callable, Object...)}.
* @param webAsyncTask a WebAsyncTask containing the target {@code Callable}
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
* @throws Exception if concurrent processing failed to start
*/
public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object... processingContext)
throws Exception {
Assert.notNull(webAsyncTask, "WebAsyncTask must not be null");
Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null");
Long timeout = webAsyncTask.getTimeout();
if (timeout != null) {
this.asyncWebRequest.setTimeout(timeout);
}
AsyncTaskExecutor executor = webAsyncTask.getExecutor();
if (executor != null) {
this.taskExecutor = executor;
}
List<CallableProcessingInterceptor> interceptors = new ArrayList<>();
interceptors.add(webAsyncTask.getInterceptor());
interceptors.addAll(this.callableInterceptors.values());
interceptors.add(timeoutCallableInterceptor);
final Callable<?> callable = webAsyncTask.getCallable();
final CallableInterceptorChain interceptorChain = new CallableInterceptorChain(interceptors);
this.asyncWebRequest.addTimeoutHandler(() -> {
if (logger.isDebugEnabled()) {
logger.debug("Async request timeout for " + formatRequestUri());
}
Object result = interceptorChain.triggerAfterTimeout(this.asyncWebRequest, callable);
if (result != CallableProcessingInterceptor.RESULT_NONE) {
setConcurrentResultAndDispatch(result);
}
});
this.asyncWebRequest.addErrorHandler(ex -> {
if (!this.errorHandlingInProgress) {
if (logger.isDebugEnabled()) {
logger.debug("Async request error for " + formatRequestUri() + ": " + ex);
}
Object result = interceptorChain.triggerAfterError(this.asyncWebRequest, callable, ex);
result = (result != CallableProcessingInterceptor.RESULT_NONE ? result : ex);
setConcurrentResultAndDispatch(result);
}
});
this.asyncWebRequest.addCompletionHandler(() ->
interceptorChain.triggerAfterCompletion(this.asyncWebRequest, callable));
interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, callable);
startAsyncProcessing(processingContext);
try {
Future<?> future = this.taskExecutor.submit(() -> {
Object result = null;
try {
interceptorChain.applyPreProcess(this.asyncWebRequest, callable);
result = callable.call();
}
catch (Throwable ex) {
result = ex;
}
finally {
result = interceptorChain.applyPostProcess(this.asyncWebRequest, callable, result);
}
setConcurrentResultAndDispatch(result);
});
interceptorChain.setTaskFuture(future);
}
catch (RejectedExecutionException ex) {
Object result = interceptorChain.applyPostProcess(this.asyncWebRequest, callable, ex);
setConcurrentResultAndDispatch(result);
throw ex;
}
}
private String formatRequestUri() {
HttpServletRequest request = this.asyncWebRequest.getNativeRequest(HttpServletRequest.class);
return request != null ? request.getRequestURI() : "servlet container";
}
private void setConcurrentResultAndDispatch(@Nullable Object result) {
synchronized (WebAsyncManager.this) {
if (this.concurrentResult != RESULT_NONE) {
return;
}
this.concurrentResult = result;
this.errorHandlingInProgress = (result instanceof Throwable);
}
if (this.asyncWebRequest.isAsyncComplete()) {
if (logger.isDebugEnabled()) {
logger.debug("Async result set but request already complete: " + formatRequestUri());
}
return;
}
if (logger.isDebugEnabled()) {
boolean isError = result instanceof Throwable;
logger.debug("Async " + (isError ? "error" : "result set") + ", dispatch to " + formatRequestUri());
}
this.asyncWebRequest.dispatch();
}
/**
* Start concurrent request processing and initialize the given
* {@link DeferredResult} with a {@link DeferredResultHandler} that saves
* the result and dispatches the request to resume processing of that
* result. The {@code AsyncWebRequest} is also updated with a completion
* handler that expires the {@code DeferredResult} and a timeout handler
* assuming the {@code DeferredResult} has a default timeout result.
* @param deferredResult the DeferredResult instance to initialize
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
* @throws Exception if concurrent processing failed to start
* @see #getConcurrentResult()
* @see #getConcurrentResultContext()
*/
public void startDeferredResultProcessing(
final DeferredResult<?> deferredResult, Object... processingContext) throws Exception {
Assert.notNull(deferredResult, "DeferredResult must not be null");
Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null");
Long timeout = deferredResult.getTimeoutValue();
if (timeout != null) {
this.asyncWebRequest.setTimeout(timeout);
}
List<DeferredResultProcessingInterceptor> interceptors = new ArrayList<>();
interceptors.add(deferredResult.getInterceptor());
interceptors.addAll(this.deferredResultInterceptors.values());
interceptors.add(timeoutDeferredResultInterceptor);
final DeferredResultInterceptorChain interceptorChain = new DeferredResultInterceptorChain(interceptors);
this.asyncWebRequest.addTimeoutHandler(() -> {
try {
interceptorChain.triggerAfterTimeout(this.asyncWebRequest, deferredResult);
}
catch (Throwable ex) {
setConcurrentResultAndDispatch(ex);
}
});
this.asyncWebRequest.addErrorHandler(ex -> {
if (!this.errorHandlingInProgress) {
try {
if (!interceptorChain.triggerAfterError(this.asyncWebRequest, deferredResult, ex)) {
return;
}
deferredResult.setErrorResult(ex);
}
catch (Throwable interceptorEx) {
setConcurrentResultAndDispatch(interceptorEx);
}
}
});
this.asyncWebRequest.addCompletionHandler(()
-> interceptorChain.triggerAfterCompletion(this.asyncWebRequest, deferredResult));
interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, deferredResult);
startAsyncProcessing(processingContext);
try {
interceptorChain.applyPreProcess(this.asyncWebRequest, deferredResult);
deferredResult.setResultHandler(result -> {
result = interceptorChain.applyPostProcess(this.asyncWebRequest, deferredResult, result);
setConcurrentResultAndDispatch(result);
});
}
catch (Throwable ex) {
setConcurrentResultAndDispatch(ex);
}
}
private void startAsyncProcessing(Object[] processingContext) {
synchronized (WebAsyncManager.this) {
this.concurrentResult = RESULT_NONE;
this.concurrentResultContext = processingContext;
this.errorHandlingInProgress = false;
}
this.asyncWebRequest.startAsync();
if (logger.isDebugEnabled()) {
logger.debug("Started async request");
}
}
}
|
package kz.greetgo.file_storage.impl;
import java.util.Date;
import java.util.Map;
import org.bson.types.Binary;
public class MongoUtil {
public static String toStr(Object objectValue) {
if (objectValue == null) {
return null;
}
if (objectValue instanceof String) {
return (String) objectValue;
}
throw new IllegalArgumentException("Cannot convert to string the value of "
+ objectValue.getClass() + " = " + objectValue);
}
public static Date toDate(Object objectValue) {
if (objectValue == null) {
return null;
}
if (objectValue instanceof Date) {
return (Date) objectValue;
}
throw new IllegalArgumentException("Cannot convert to Date the value of "
+ objectValue.getClass() + " = " + objectValue);
}
public static byte[] toByteArray(Object objectValue) {
if (objectValue == null) {
return null;
}
if (objectValue instanceof String) {
String base64 = (String) objectValue;
return Base64Util.base64ToBytes(base64);
}
if (objectValue instanceof Binary) {
Binary bin = (Binary) objectValue;
return bin.getData();
}
throw new IllegalArgumentException("Cannot convert to byte[] the value of "
+ objectValue.getClass() + " = " + objectValue);
}
@SuppressWarnings("unchecked")
public static Map<String, String> toMap(Object objectValue){
if (objectValue == null) {
return null;
}
if(objectValue instanceof Map){
return (Map<String, String>) objectValue;
}
throw new IllegalArgumentException("Cannot convert to Map<String, String> the value of "
+ objectValue.getClass() + " = " + objectValue);
}
}
|
package com.trump.auction.activity.dao;
import com.trump.auction.activity.domain.ActivityUser;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
* 活动用户相关
* @author wangbo 2018/1/11.
*/
@Repository
public interface ActivityUserDao {
/**
* 插入一条活动用户记录
* @param activityUser 活动用户信息
* @return 受影响的行数
*/
int insertActivityUser(ActivityUser activityUser);
/**
* 根据userId查询活动用户信息
* @param userId 用户id
* @return 活动用户信息
*/
ActivityUser selectActivityUserByUserId(@Param("userId")Integer userId);
/**
* 更新用户的免费抽奖次数
* @param userId 用户id
* @param freeLotteryTimes 免费抽奖次数
* @param freeLotteryTimesOld 更新前的免费抽奖次数
* @return 受影响的行数
*/
int updateFreeLotteryTimes(@Param("userId")Integer userId,@Param("freeLotteryTimes")int freeLotteryTimes,
@Param("freeLotteryTimesOld")int freeLotteryTimesOld);
}
|
// **********************************************************
// 1. 제 목:
// 2. 프로그램명: ExamBean.java
// 3. 개 요:
// 4. 환 경: JDK 1.3
// 5. 버 젼: 0.1
// 6. 작 성: Administrator 2003-08-29
// 7. 수 정:
//
// **********************************************************
package com.ziaan.exam;
/**
* @author Administrator
*
* To change the template for this generated type comment go to
* Window > Preferences > Java > Code Generation > Code and Comments
*/
public class ExamBean {
public final static String SPLIT_COMMA = ",";
public final static String SPLIT_COLON = ":";
public final static String PTYPE = "0012"; // 평가분류
public final static String MIDDLE_EXAM = "M"; // 중간평가
public final static String FINAL_EXAM = "T"; // 최종평가
public final static String ONLINE_EXAM = "O"; // 온라인테스트
public final static String EXAM_TYPE = "0013"; // 평가문제분류
public final static String OBJECT_QUESTION = "1"; // 객관식
public final static String SUBJECT_QUESTION = "2"; // 주관식
public final static String OX_QUESTION = "3"; // OX식 ( add 2005.8.20 )
public final static String MULTI_QUESTION = "4"; // 다답식
public final static String EXAM_LEVEL = "0014"; // 문제난이도
public final static String TOP = "1"; // 상
public final static String MIDDLE = "2"; // 중
public final static String LOW = "3"; // 하
public final static String PAPER_GUBUN = "0015"; // 문제지유형
public final static String GENERAL = "1"; // 일반평가
public final static String REALTIME = "2"; // 실시간평가
public final static String PAPER_CREATE = "0016"; // 시험지생성방법
public final static String AUTO = "1"; // 자동생성
public final static String BEFORE_PAPER = "2"; // 기존기수문제지승계
public final static String MANUAL = "3"; // 수동생성
public final static String EXAM_TIME = "0094"; // 평가시간
public ExamBean() { }
}
|
package net.rafaeltoledo.vidabeta;
import java.util.ArrayList;
import java.util.List;
import net.rafaeltoledo.vidabeta.model.Podcast;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class ListaPodcastsActivity extends Activity implements
AdapterView.OnItemClickListener, OnCancelListener {
private ListView lista;
private Button botaoVoltar;
List<Podcast> podcasts = new ArrayList<Podcast>();
ArrayAdapter<Podcast> adaptador = null;
public static ProgressDialog dialog = null;
private StatusInstancia status = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_podcasts);
lista = (ListView) findViewById(R.id.lista_casts);
lista.setOnItemClickListener(this);
botaoVoltar = (Button) findViewById(R.id.botao_voltar);
botaoVoltar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
dialog = ProgressDialog.show(this, "Baixando Lista de Podcasts",
"Por favor, aguarde... Isso vai levar só alguns segundos...", true, true, this);
status = (StatusInstancia) getLastNonConfigurationInstance();
String feed = getIntent().getExtras().getString("FEED_LOCATION");
if (feed.contains("mini")) {
TextView titulo = (TextView) findViewById(R.id.titulo);
titulo.setText(getString(R.string.minicasts));
}
Log.i("VidaBeta", feed);
if (status == null) {
status = new StatusInstancia();
status.handler = new HandlerSincronizacao(this);
Intent i = new Intent(this, ListaPodcastService.class);
i.putExtra(ListaPodcastService.MESSENGER_EXTRA, new Messenger(status.handler));
i.putExtra(ListaPodcastService.FEED_LOCATION, feed);
startService(i);
} else {
if (status.handler != null) {
status.handler.anexar(this);
}
if (status.podcasts != null) {
preencherLista(status.podcasts);
}
}
}
@Override
protected void onStart() {
super.onStart();
if (!podcasts.isEmpty()) {
}
}
private void preencherLista(List<Podcast> podcasts) {
this.podcasts = podcasts;
adaptador = new ArrayAdapter<Podcast>(this,
android.R.layout.simple_list_item_1, podcasts);
lista.setAdapter(adaptador);
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent i = new Intent(this, PodcastActivity.class);
i.putExtra("cast", podcasts.get((int) id));
startActivity(i);
}
private void atirarErro(Throwable t) {
Builder builder = new Builder(this);
builder.setTitle("Erro!").setMessage("Falha na conexão! Não foi possível baixar a lista de episódios!").setPositiveButton("OK", null).show();
}
@Override
public Object onRetainNonConfigurationInstance() {
if (status.handler != null) {
status.handler.desanexar();
}
return status;
}
private static class StatusInstancia {
List<Podcast> podcasts = null;
HandlerSincronizacao handler = null;
}
private static class HandlerSincronizacao extends Handler {
private ListaPodcastsActivity activity = null;
HandlerSincronizacao(ListaPodcastsActivity activity) {
anexar(activity);
}
void anexar(ListaPodcastsActivity activity) {
this.activity = activity;
}
void desanexar() {
activity = null;
}
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
ListaPodcastsActivity.dialog.dismiss();
if (msg.arg1 == RESULT_OK) {
activity.preencherLista((List<Podcast>) msg.obj);
} else {
activity.atirarErro((Exception) msg.obj);
}
}
}
public void onCancel(DialogInterface dialog) {
finish();
}
}
|
package com.example.attest.validator;
import brave.Tracer;
import com.example.attest.dao.TransactionRepository;
import com.example.attest.exception.ServiceException;
import com.example.attest.model.api.TransactionApi;
import com.example.attest.model.domain.Transaction;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
@Service
public class TransactionValidatorImpl implements TransactionValidator {
private TransactionRepository transactionRepository;
private Tracer tracer;
public TransactionValidatorImpl(TransactionRepository transactionRepository,
Tracer tracer) {
this.transactionRepository = transactionRepository;
this.tracer = tracer;
}
@Override
public void validateUniqueReference(String reference) {
Optional<Transaction> optionalTransaction = transactionRepository.findByReference(reference);
if (optionalTransaction.isPresent()) {
throw new ServiceException.Builder(ServiceException.ERROR_TRANSACTION_DUPLICATED)
.withMessage(String.format("It exists a transaction with the same reference %s",
optionalTransaction.get()
.getReference()))
.withHttpStatus(HttpStatus.UNPROCESSABLE_ENTITY)
.build();
}
}
@Override
public void validateOptionalsToCreate(TransactionApi transactionApi) {
if (transactionApi.getReference() == null) {
transactionApi.setReference(String.format("%s-%s",
tracer.currentSpan()
.context()
.traceIdString(),
tracer.currentSpan()
.context()
.spanIdString()));
}
if (transactionApi.getDate() == null) {
transactionApi.setDate(LocalDateTime.now());
}
if (transactionApi.getFee() == null) {
transactionApi.setFee(BigDecimal.ZERO);
}
}
}
|
package com.beike.entity.user;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* Title:用户扩展信息
* </p>
* <p>
* Description:
* </p>
* <p>
* Copyright: Copyright (c) 2011
* </p>
* <p>
* Company: Sinobo
* </p>
*
* @date May 5, 2011
* @author ye.tian
* @version 1.0
*/
public class UserProfile implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String value;
private String profiletype;
private Long userid;
private Date profiledate;
public Date getProfiledate() {
return profiledate;
}
public void setProfiledate(Date profiledate) {
this.profiledate = profiledate;
}
public UserProfile() {
}
public UserProfile(Long id, String name, String value, String profiletype,
Long userid) {
this.id = id;
this.name = name;
this.value = value;
this.profiletype = profiletype;
this.userid = userid;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getProfiletype() {
return profiletype;
}
public void setProfiletype(String profiletype) {
this.profiletype = profiletype;
}
public Long getUserid() {
return userid;
}
public void setUserid(Long userid) {
this.userid = userid;
}
}
|
package com.example.haoch.wocao;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.haoch.wocao.file_api.Fileview_experiment;
/**
* A simple {@link Fragment} subclass.
*/
public class AccountFragment extends Fragment {
private ImageView docuemnt_login, account_setting, management_login, gps_location;
private Button logout;
private TextView tv_name;
private String m_Text = "";
private String USER_NAME;
private Thread thread;
private SharedPreferences getPassName;
private SharedPreferences.Editor getPassNameEditor;
private static final String PREF_NAME = "prefs";
public AccountFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_account, container, false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
docuemnt_login = (ImageView)getActivity().findViewById(R.id.docuemnt_login);
account_setting = (ImageView)getActivity().findViewById(R.id.account_setting);
management_login = (ImageView)getActivity().findViewById(R.id.management_system);
gps_location = (ImageView)getActivity().findViewById(R.id.gps_location);
logout = (Button)getActivity().findViewById(R.id.appLogout);
tv_name = (TextView)getActivity().findViewById(R.id.TV_NAE123);
getPassName = getActivity().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
getPassNameEditor = getPassName.edit();
tv_name.setText(getPassName.getString("account", ""));
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getPassNameEditor.putBoolean("remember_password", false);
getPassNameEditor.commit();
startActivity(new Intent().setClass(getActivity(), LoginActivity.class));
getActivity().finish();
}
});
management_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
enterPass();
}
});
docuemnt_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
thread = new Thread(new Runnable() {
@Override
public void run() {
startActivity(new Intent().setClass(getActivity(), Fileview_experiment.class));
}
});
thread.start();
}
});
}
private void enterPass(){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Enter Management password");
View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.text_input_password, null);
// Set up the input
// final EditText input666 = new EditText(getActivity());
final EditText input666 = (EditText)viewInflated.findViewById(R.id.input_pass);
input666.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(viewInflated);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//successful
if (input666.getText().toString().trim().equals("666")){
// input正确
startActivity(new Intent().setClass(getActivity(), userManageActivity.class));
} else {
enterPass();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
|
package learn.sprsec.ssia0204provider.security;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = String.valueOf(authentication.getCredentials());
if ("jane".equals(username) && "1234".equals(password)) {
return new UsernamePasswordAuthenticationToken(username, password, List.of());
} else {
throw new AuthenticationCredentialsNotFoundException("Error in authentication!");
}
}
@Override
public boolean supports(Class<?> authenticationType) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authenticationType);
}
}
|
public class DengklekTryingToSleep {
public int minDucks(int[] ducks) {
int min = Integer.MAX_VALUE;
int max = 0;
for(int i = 0; i < ducks.length; i++) {
if(ducks[i] < min) {
min = ducks[i];
}
if(max < ducks[i]) {
max = ducks[i];
}
}
if(max == min) {
return 0;
}
return max - min - ducks.length + 1;
}
}
|
package com.smyc.kaftanis.lookingfortable;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Created by kaftanis on 11/13/16.
*/
public class BugReport extends DialogFragment implements View.OnClickListener {
EditText editText;
Button button;
RequestQueue requestQueue;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.set_radius, null);
getDialog().setTitle("Αναφορά σφάλματος");
editText = (EditText) view.findViewById(R.id.editText);
editText.setHint("Περιγράψτε μας το σφάλμα που εντοπίσατε");
button = (Button) view.findViewById(R.id.button4);
button.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.button4) {
if (editText.getText().toString().equals("")) {
Toast.makeText( getActivity() , "Πληκτρολογίστε κάτι" , Toast.LENGTH_SHORT).show();
}
else {
try {
String s = URLEncoder.encode(editText.getText().toString(), "utf-8");
// String p = URLEncoder.encode(insertPhone, "utf-8");
if (s.contains(" "))
s=s.replace(" ", "%20");
JSONproccess("--"BUG:"+s);
} catch (UnsupportedEncodingException e) {}
}
}
}
private void JSONproccess ( String loginURL ) {
requestQueue = Volley.newRequestQueue(getActivity());
// output = (TextView) findViewById(R.id.jsonData);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, loginURL, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
requestQueue.add(jor);
dismiss();
Toast.makeText( getActivity() , "Ευχαριστούμε για τη συνεισφορά σας! " , Toast.LENGTH_SHORT).show();
}
}
|
/**
*
* @author ntnrc
*/
public class Ventilador {
public String color, tipoAspa;
public int potencia;
//metodos
@Override
public String toString(){
return "El color del ventilador es: "+color+"\nel tipo de aspa es: "+tipoAspa+"\nla potencia es de: "+potencia;
}
}
|
package actions.ajax;
import com.opensymphony.xwork2.ActionSupport;
import facade.GestionStratego;
import modele.Joueur;
import modele.Partie;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.SessionAware;
import java.util.Map;
/**
* Created by reda on 24/11/2016.
*/
public class AjaxCheckDeuxiemeJoueur extends ActionSupport implements ApplicationAware,SessionAware{
private Map<String, Object> applicationMap;
private Map<String,Object> sessionMap;
public boolean isJoueurArefuser() {
return joueurArefuser;
}
public void setJoueurArefuser(boolean joueurArefuser) {
this.joueurArefuser = joueurArefuser;
}
boolean joueurArefuser=false;
public void setPartie(Partie partie) {
this.partie = partie;
}
Partie partie;
private Joueur joueur;
private String pseudo;
private String pseudo2="";
public void setJoueur(Joueur joueur) {
this.joueur = joueur;
}
public Joueur getJoueur() {
return joueur;
}
public void setPseudo2(String pseudo2) {
this.pseudo2 = pseudo2;
}
public String getPseudo2() {
return pseudo2;
}
public String getPseudo() {
return pseudo;
}
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
public Map<String, Object> getApplicationMap() {
return applicationMap;
}
public void setApplication(Map<String, Object> map) {
this.applicationMap = map;
}
public Map<String, Object> getSessionMap() {
return sessionMap;
}
public void setSession(Map<String, Object> map) {
this.sessionMap = map;
}
public final String execute() throws NullPointerException {
GestionStratego facade = (GestionStratego) this.applicationMap.get("facade");
partie = facade.getJoueur(pseudo).getPartie();
try {
if(facade.getJoueur(pseudo).equals(partie.getJoueurCreateur())) {
pseudo2 = partie.getJoueur2().getPseudo();
}
else if(facade.getJoueur(pseudo).equals(partie.getJoueur2())){
pseudo2 = partie.getJoueurCreateur().getPseudo();
}
}
catch (NullPointerException e){
pseudo2="null";
if(partie.getJoueurCreateur().getLesInvitationsEnvoyees().isEmpty()&&!partie.isPartiePublique()){
joueurArefuser=true;
}
}
this.sessionMap.put("pseudo",pseudo);
this.sessionMap.put("pseudo2",pseudo2);
return SUCCESS;}
}
|
package controller;
import dao.ProductoDAO;
import dao.ProductoImplementadoDAO;
import model.Producto;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class ProductoController extends HttpServlet {
private static final long serialVersionUID = 1L;
RequestDispatcher dispatcher = null;
ProductoDAO productoDAO = null;
public ProductoController() {
productoDAO = new ProductoImplementadoDAO();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
switch(Integer.parseInt(request.getParameter("action"))) {
case 1:
mostrarProductos(request, response);
break;
case 2:
obtenerProducto(request, response);
break;
case 3:
eliminarProducto(request, response);
break;
case 4:
vender(request, response);
break;
default:
mostrarProductos(request, response);
break;
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id_producto");
Producto p = new Producto();
p.setNombre(request.getParameter("nombre"));
p.setDescripcion(request.getParameter("descripcion"));
if(request.getParameter("cantidad") != null)
p.setCantidad(Integer.parseInt(request.getParameter("cantidad")));
if(request.getParameter("precio") != null)
p.setPrecio(Double.parseDouble(request.getParameter("precio")));
if(id.isEmpty() || id == null) {
if(productoDAO.guardar(p)) {
request.setAttribute("ALERTA", "Producto Guardado!");
}
}else {
if(id.equals("0")){
int id_combo_producto = Integer.parseInt(request.getParameter("combo_productos"));
int cantidad = Integer.parseInt(request.getParameter("cantidad_productos"));
if(productoDAO.vender(id_combo_producto,cantidad))
request.setAttribute("ALERTA", "Venta Realizada!");
else
request.setAttribute("ALERTA", "No existe stock del producto!");
}else{
p.setId(Integer.parseInt(id));
if(productoDAO.actualizar(p)) {
request.setAttribute("ALERTA", "Producto Actualizado!");
}
}
}
mostrarProductos(request, response);
}
private void mostrarProductos(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Producto> lista_productos = productoDAO.obtener();
request.setAttribute("list", lista_productos);
dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}
private void obtenerProducto(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String id_producto = request.getParameter("id_producto");
Producto producto = productoDAO.obtener(Integer.parseInt(id_producto));
request.setAttribute("producto", producto);
dispatcher = request.getRequestDispatcher("/views/editarProducto.jsp");
dispatcher.forward(request, response);
}
private void eliminarProducto(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id_producto = request.getParameter("id_producto");
if(productoDAO.eliminar(Integer.parseInt(id_producto)))
request.setAttribute("ALERTA", "Producto Eliminado!");
mostrarProductos(request, response);
}
private void vender(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Producto> lista_productos = productoDAO.obtener();
request.setAttribute("list", lista_productos);
dispatcher = request.getRequestDispatcher("/views/venderProducto.jsp");
dispatcher.forward(request, response);
}
}
|
package bean;
/**
* 会员实体类
* @author computer
*
*/
public class Member {
private int id; //会员编号,与登陆表中的id相同,是它的外键
private String memberName; //会员姓名
private String memberSex; //会员性别
private String memberPhone; //会员电话
private double totalConsumption; //消费总额
private double balance; //账户余额
public Member(int id) {
super();
this.id = id;
}
public Member() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getMemberSex() {
return memberSex;
}
public void setMemberSex(String memberSex) {
this.memberSex = memberSex;
}
public String getMemberPhone() {
return memberPhone;
}
public void setMemberPhone(String memberPhone) {
this.memberPhone = memberPhone;
}
public double getTotalConsumption() {
return totalConsumption;
}
public void setTotalConsumption(double totalConsumption) {
this.totalConsumption = totalConsumption;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
|
package algorithms.fundamentals.sub3_collection.exercises.linkedlist;
import java.util.Iterator;
import java.util.function.Consumer;
/**
* Created by Chen Li on 2017/4/28.
*/
public class CircularLinkedListQueueImpl<Item> implements Iterable<Item> {
private Node last;
private int size;
public CircularLinkedListQueueImpl() {
last = null;
size = 0;
}
public int size() {
return size();
}
public boolean isEmpty() {
return size == 0;
}
public void enqueue(Item item) {
Node node = new Node();
node.item = item;
node.next = node;
if (last == null) {
size++;
last = node;
return;
}
node.next = last.next;
last.next = node;
last = node;
size++;
}
public Item dequeue() {
if (size == 0) {
throw new IllegalStateException("can not dequeue from an empty queue!");
}
if (size == 1) {
Item item = last.item;
size = 0;
last = null;
return item;
}
size--;
Node deletedNode = last.next;
last.next = deletedNode.next;
deletedNode.next = null;
return deletedNode.item;
}
@Override
public Iterator<Item> iterator() {
return new QueueIterator();
}
private class QueueIterator implements Iterator<Item> {
private Node current = last == null ? null : last.next;
private int read = 0;
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void forEachRemaining(Consumer<? super Item> action) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasNext() {
return read < size;
}
@Override
public Item next() {
if (!hasNext()) {
throw new IllegalStateException("no more elements!");
}
Item item = current.item;
current = current.next;
read++;
return item;
}
}
private class Node {
private Item item;
private Node next;
}
}
|
package com.egame.beans;
import org.json.JSONObject;
import com.egame.utils.ui.IconBeanImpl;
/**
* @desc 游戏包内的游戏(图片和名称)
*
* @Copyright lenovo
*
* @Project EGame4th
*
* @Author zhangrh@lenovo-cw.com
*
* @timer 2012-1-12
*
* @Version 1.0.0
*
* @JDK version used 6.0
*
* @Modification history none
*
* @Modified by none
*/
public class GameInPackageBean extends IconBeanImpl {
private String gameName;
// private String gamePic;
public GameInPackageBean(JSONObject json){
super(json.optString("gamePic"));
this.gameName=json.optString("gameName");
// this.gamePic=json.optString("gamePic");
}
/**
* @return 返回 gameName
*/
public String getGameName() {
return gameName;
}
/**
* @param 对gameName进行赋值
*/
public void setGameName(String gameName) {
this.gameName = gameName;
}
// /**
// * @return 返回 gamePic
// */
// public String getGamePic() {
// return gamePic;
// }
//
// /**
// * @param 对gamePic进行赋值
// */
// public void setGamePic(String gamePic) {
// this.gamePic = gamePic;
// }
}
|
package com.shangdao.phoenix.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import com.shangdao.phoenix.handler.LoginSuccessHandler;
import com.shangdao.phoenix.service.UserService;
import com.shangdao.phoenix.util.CommonUtils;
import com.shangdao.phoenix.filter.PublicWeixinAuthenticationFilter;
import com.shangdao.phoenix.filter.WebAuthenticationFilter;
import com.shangdao.phoenix.filter.WorkWeixinAuthenticationFilter;
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=186400)
public class Config extends WebSecurityConfigurerAdapter {
@Value("${salt}")
private String salt;
@Value("${work.weixin.filter.pattern}")
private String workPattern;
@Value("${public.weixin.filter.pattern}")
private String publicPattern;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().disable();
http.addFilterAt(webAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);
http.addFilterAfter(workAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
http.addFilterAfter(publicAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
http.csrf().disable()
.formLogin()
.loginPage("/login").permitAll()
.successHandler(successHandler())
.and().authorizeRequests().antMatchers("/entity/user/create","/wxpublic/api","/wxwork/api/**").permitAll()
.and().authorizeRequests().antMatchers("/browser/**","electron/**","wxpublic-desk/**","wxpublic-mobile/**","wxwork-desk/**","wxpublic-mobile/**").permitAll()
.and().authorizeRequests().antMatchers("/backend").permitAll() //后台登录界面
.and().authorizeRequests().anyRequest().authenticated() //拦截
.and().rememberMe().tokenValiditySeconds(60 * 60 * 24 * 30);
}
@Bean
public UserDetailsService customUserService() {
return new UserService();
}
@Bean
public LoginSuccessHandler successHandler(){
return new LoginSuccessHandler();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService()).passwordEncoder(new PasswordEncoder(){
@Override
public String encode(CharSequence rawPassword) {
return CommonUtils.MD5Encode((String)rawPassword,salt);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(CommonUtils.MD5Encode((String)rawPassword, salt));
}});
}
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(3600*24*10);
return cacheManager;
}
@Bean
public WebAuthenticationFilter webAuthenticationFilter() throws Exception {
WebAuthenticationFilter authenticationFilter = new WebAuthenticationFilter();
authenticationFilter.setAuthenticationManager(authenticationManagerBean());
return authenticationFilter;
}
@Override
@Bean // share AuthenticationManager for web and oauth
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public WorkWeixinAuthenticationFilter workAuthenticationFilter() {
WorkWeixinAuthenticationFilter authenticationFilter = new WorkWeixinAuthenticationFilter(workPattern);
authenticationFilter.setAuthenticationManager( new AuthenticationManager() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return authentication;
}
});
return authenticationFilter;
}
@Bean
public PublicWeixinAuthenticationFilter publicAuthenticationFilter() {
PublicWeixinAuthenticationFilter authenticationFilter = new PublicWeixinAuthenticationFilter(publicPattern);
authenticationFilter.setAuthenticationManager( new AuthenticationManager() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return authentication;
}
});
return authenticationFilter;
}
}
|
package com.sample.problem.writer;
public enum WriterType {
CONSOLE_WRITER, DB_WRITER
}
|
package xhu.wncg.firesystem.system.controller;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import xhu.wncg.common.utils.Fire;
import xhu.wncg.common.utils.ShiroUtils;
import xhu.wncg.firesystem.system.pojo.SysUser;
import xhu.wncg.firesystem.system.service.SysUserService;
import xhu.wncg.firesystem.system.service.SysUserTokenService;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
/**
* @author BZhao
* @version 2017/10/24.
*/
@RestController
public class SysLoginController extends AbstractController {
@Autowired
private Producer producer;
@Autowired
private SysUserService sysUserService;
@Autowired
private SysUserTokenService sysUserTokenService;
/**
* 获取验证码
*
* @param response
* @throws IOException
*/
@GetMapping("/captcha.jpg")
public void captcha(HttpServletResponse response) throws IOException {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
//生成文字验证码
String text = producer.createText();
//生成图片验证码
BufferedImage image = producer.createImage(text);
//保存到shiro session
ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(image, "jpg", outputStream);
IOUtils.closeQuietly(outputStream);
}
/**
* 系统用户登录
*
* @param username 用户名
* @param password 密码
* @param captcha 验证码
* @return token
*/
@PostMapping("/sys/login")
public Map<String, Object> login(String username, String password, String captcha) {
String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
if (!captcha.equalsIgnoreCase(kaptcha)) {
return Fire.error("验证码不正确!");
}
//用户信息
SysUser user = sysUserService.queryByUsername(username);
if (user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
return Fire.error("账号或密码不正确");
}
//账号锁定
if (user.getStatus() == 0) {
return Fire.error("账号已被锁定,请联系管理员");
}
//生成token,并保存到数据库
return sysUserTokenService.createToken(user.getUserId());
}
/**
* 退出登录
*
* @return
*/
@PostMapping("/sys/logout")
public Fire logout() {
sysUserTokenService.logout(getUserId());
return Fire.ok();
}
}
|
// package com.document.feed;
//
// import static org.apache.commons.lang3.StringUtils.reverse;
// import static org.apache.commons.lang3.StringUtils.strip;
//
// import com.document.feed.model.Article;
// import com.document.feed.model.ArticleReactiveRepository;
// import com.document.feed.model.ArticleRepositoryMultiIndexImpl;
// import com.document.feed.util.ESMaintenance;
// import com.kwabenaberko.newsapilib.NewsApiClient;
// import com.kwabenaberko.newsapilib.models.request.TopHeadlinesRequest;
// import com.kwabenaberko.newsapilib.models.response.ArticleResponse;
// import java.io.IOException;
// import org.junit.jupiter.api.Test;
// import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.boot.test.context.SpringBootTest;
//
// @SpringBootTest
// class FeedApplicationTests {
//
// @Autowired ArticleReactiveRepository repository;
//
// @Autowired ArticleRepositoryMultiIndexImpl articleRepositoryCustom;
//
// @Autowired ESMaintenance esMaintenance;
//
// @Test
// public void testListAll() throws InterruptedException {
// var a = repository.findAll().buffer().blockLast();
// Thread.sleep(10000);
// }
//
// @Test
// public void testNewsAPI() throws InterruptedException {
// var newsApiClient = new NewsApiClient("7bca7fe0b1cf411082fc45d8d78b4dd4");
//
// newsApiClient.getTopHeadlines(
// new
// TopHeadlinesRequest.Builder().country("in").category("business").language("en").build(),
// new NewsApiClient.ArticlesResponseCallback() {
// @Override
// public void onSuccess(ArticleResponse response) {
// response
// .getArticles()
// .forEach(
// article -> {
// var v = article;
// var a = new Article();
// a.setArticle(article);
// a.setId(reverse(strip(article.getUrl(), "/")));
// var x = repository.save(a).block();
// System.out.println(article.getTitle());
// });
// }
//
// @Override
// public void onFailure(Throwable throwable) {
// System.out.println(throwable.getMessage());
// }
// });
// Thread.sleep(10000);
// }
//
// // tomicI@Test
// //// public void testFindAll() throws InterruptedException {
// //// AtomicInteger found = new AtomicInteger();
// // articleRepositoryCustom
// // .findAll(Pageable.unpaged())
// // .subscribe(
// // searchHits -> {
// // searchHits.forEach(
// // articleSearchHit -> {
// // System.out.println("found:" + found.incrementAndGet());
// // System.out.println(articleSearchHit.getContent().getArticle().getTitle());
// // });
// // });
// // Thread.sleep(5000);
// // }
// @Test
// public void testDelete() throws IOException {
// esMaintenance.deleteOldIndexes();
// }
// }
|
package com.citi.yourbank;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class YourBankApplication {
public static void main(String[] args) {
SpringApplication.run(YourBankApplication.class, args);
}
}
|
package hw3.ch3.q2.math;
import java.text.DecimalFormat;
/**
* Represents a complex number with two doubles:
* one to represent the real part, and the other
* to represent the imaginary part (the coefficient of i).
*/
public class Complex implements ComplexNumber {
private double real, imaginary;
private final DecimalFormat format = new DecimalFormat("0.###");
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public Complex(double real) {
this.real = real;
this.imaginary = 0.0;
}
/**
* Computes the complex conjugate of the instantiated Complex.
* @return a Complex with the same real part and a negative
* imaginary part.
*/
public Complex conj() {
return new Complex(real, -imaginary);
}
/**
* Computes the sum of two complex numbers.
* @param c2 The second Complex in the equation.
* @return a Complex representing the sum of two
* Complexes.
*/
public Complex add(Complex c2) {
return new Complex(this.real+c2.real, this.imaginary+c2.imaginary);
}
/**
* Computes the difference between two complex numbers.
* @param c2 a Complex representing the subtrahend.
* @return a Complex representing the difference.
*/
public Complex sub(Complex c2) {
return new Complex(this.real-c2.real, this.imaginary-c2.imaginary);
}
/**
* Computes the product of two complex numbers.
* @param c2 a Complex representing the multiplier.
* @return a Complex representing the product.
*/
public Complex mult(Complex c2) {
double newReal = (real * c2.r()) - (imaginary * c2.i()),
newImag = (real * c2.i()) + (imaginary * c2.r());
return new Complex(newReal, newImag);
}
/**
* Computes the quotient of two complex numbers.
* @param c2 a Complex representing the divisor.
* @return a Complex representing the quotient.
* @throws IllegalArgumentException if the divisor
* is zero.
*/
public Complex div(Complex c2) {
if (c2.r() == 0.0 && c2.i() == 0.0) {
throw new IllegalArgumentException("Attempted to divide by zero.");
}
Complex denominatorConjugate = c2.conj(),
numerator = mult(denominatorConjugate),
denominator = c2.mult(denominatorConjugate);
double newReal = numerator.r() / denominator.r(),
newImag = numerator.i() / denominator.r();
return new Complex(newReal, newImag);
}
/**
* Computes the real part of a complex number.
* @return a double representing the real part.
*/
public double r() {
return real;
}
/**
* Computes the imaginary part of a complex number.
* @return a double representing the coefficient of i.
*/
public double i() {
return imaginary;
}
/**
* Helper function that converts the real part of
* a complex number into a String
* @return a String containing the real number if
* it is not zero, or an empty String if the real
* number is zero.
*/
private String realString() {
return (real!=0) ? format.format(real) : "";
}
/**
* Helper function that returns a '+', '-', or an
* empty String based on the contents of this.real
* and this.imaginary.
* @return a String containing an operator, or an empty String.
*/
private String sepString() {
return (imaginary != 0 && real != 0) ? ((imaginary > 0) ? " + " : " - ") : "";
}
/**
* Helper function that formats the imaginary part
* of a complex number into a readable String.
* @return a String representing the imaginary
* part of a complex number.
*/
private String imaginaryString() {
if (imaginary == 0.0) {
return "";
} else if (real == 0.0) {
return format.format(imaginary) + "i";
} else {
return ((imaginary > 0) ? format.format(imaginary) : format.format(-imaginary)) + "i";
}
}
/**
* Converts a Complex into a human-readable String.
* @return String representing this.
*/
public String toString() {
return realString() + sepString() + imaginaryString();
}
/**
* Determines whether two Complexes are equivalent.
* @param c2 The second Complex to compare to this.
* @return True if they are equal, False if they are
* unequal.
*/
public boolean equals(Complex c2) {
return real == c2.real && imaginary == c2.imaginary;
}
public static void main(String[] args) {
Complex c1 = new Complex(3, 2),
c2 = new Complex(3, -2);
Complex sum = c1.add(c2),
difference = c1.sub(c2),
product = c1.mult(c2),
quotient = c1.div(c2),
conjugate = c1.conj();
String[] strings = {
String.format("(%s) + (%s) = %s", c1.toString(), c2.toString(), sum.toString()),
String.format("(%s) - (%s) = %s", c1.toString(), c2.toString(), difference.toString()),
String.format("(%s) * (%s) = %s", c1.toString(), c2.toString(), product.toString()),
String.format("(%s) / (%s) = %s", c1.toString(), c2.toString(), quotient.toString()),
String.format("Conjugate of (%s) is (%s)", c1.toString(), conjugate.toString())
};
for (String s : strings) {
System.out.println(s);
}
}
}
|
package com.appspot.smartshop.mock;
import com.appspot.smartshop.dom.CategoryInfo;
public class MockCategory {
public static CategoryInfo getInstance() {
String[] parentCategory = { "Áo quần", "Giày dép", "Mỹ phẩm",
"Váy dự tiệc" };
String[][] childrenCategory = { { "Nam", "Nữ" },
{ "Mỹ", "Trung Quốc", "Việt Nam" }, { "Son môi", "Tào Lao" },
{ "Đầm bầu", "Váy hiệu", "Hàng Fake" } };
CategoryInfo category = new CategoryInfo(parentCategory,
childrenCategory);
return category;
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations;
import org.giddap.dreamfactory.leetcode.onlinejudge.EditDistance;
import java.util.Arrays;
public class EditDistanceBottomUpDpImpl implements EditDistance {
@Override
public int minDistance(String word1, String word2) {
final int n1 = word1.length();
final int n2 = word2.length();
if (n1 == 0 || n2 == 0) {
return Math.max(n1, n2);
}
int[] prev = new int[n1 + 1];
int[] curr = new int[n1 + 1];
for (int i = 0; i < prev.length; i++) {
prev[i] = i;
}
for (int i = 0; i < n2; i++) {
curr[0] = prev[0] + 1;
char c2 = word2.charAt(i);
for (int j = 0; j < n1; j++) {
char c1 = word1.charAt(j);
curr[j + 1] = Math.min(prev[j + 1], curr[j]) + 1;
curr[j + 1] = Math.min(
curr[j + 1], prev[j] + (c1 == c2 ? 0 : 1));
}
prev = Arrays.copyOf(curr, curr.length);
}
return prev[prev.length - 1];
}
}
|
package org.sitenv.xdrmessagesender.services.enums;
/**
* Created by Brian on 2/23/2017.
*/
public enum XdrMessageType {
MINIMAL,FULL
}
|
package com.example.mp3player;
public class GetSet {
String songName="",artistName="", songURL="", duration="";
//Bitmap image;
public GetSet(String songName, String artistName, String songURL, String duration){
this.songName=songName;
this.artistName=artistName;
this.songURL=songURL;
this.duration=duration;
}
public String getSongName() {
return songName;
}
public String getArtistName() {
return artistName;
}
public String getSongURL() {
return songURL;
}
public String getDuration() {
return duration;
}
}
|
package rafaxplayer.cheftools.stocks;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import rafaxplayer.cheftools.Globalclasses.BaseActivity;
import rafaxplayer.cheftools.R;
import rafaxplayer.cheftools.stocks.fragment.StocksDetalle_Fragment;
import rafaxplayer.cheftools.stocks.fragment.StocksList_Fragment;
public class Stocks_Activity extends BaseActivity implements StocksList_Fragment.OnSelectedCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, new StocksList_Fragment(), "stokslist");
ft.commit();
}
}
@Override
protected int getLayoutResourceId() {
if (getResources().getBoolean(R.bool.dual_pane)) {
return R.layout.activity_stocks;
} else {
return R.layout.activity_template_for_all;
}
}
@Override
protected String getCustomTitle() {
return getString(R.string.activity_stoks);
}
public void showMenuEdit(int num) {
Intent in = new Intent(getApplicationContext(), StocksNewEdit_Activity.class);
in.putExtra("id", num);
startActivity(in);
}
@Override
public void onSelect(int id) {
StocksDetalle_Fragment frDetalle = (StocksDetalle_Fragment) getSupportFragmentManager().findFragmentById(R.id.detallestocks);
if (frDetalle != null && frDetalle.isInLayout()) {
frDetalle.displayWithId(id);
} else {
Intent i = new Intent(this, StocksDetalle_Activity.class);
i.putExtra("id", id);
startActivity(i);
}
}
}
|
package br.com.fatec.tcc.rotasegura.roadMap;
import java.util.HashMap;
import java.util.Map;
public class Polyline {
private String points;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return
* The points
*/
public String getPoints() {
return points;
}
/**
*
* @param points
* The points
*/
public void setPoints(String points) {
this.points = points;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
package com.beike.common.entity.discountcoupon;
import java.util.Date;
import com.beike.common.enums.trx.DiscountCouponStatus;
/**
* @title: DiscountCoupon.java
* @package com.beike.common.entity.discountcoupon
* @description: 线下优惠券
* @author wangweijie
* @date 2012-7-11 下午06:05:19
* @version v1.0
*/
public class DiscountCoupon {
private Long id; //主键
private String couponNo; //优惠券编号
private String couponPwd; //优惠券密码
private int couponValue; //优惠券面值
private int couponType; //优惠券类型
private DiscountCouponStatus couponStatus; //优惠券状态
private String batchNo; //所属批次
private String topupChannel; //充值渠道
private Long userId=0L; //用户ID
private Long createOperatorId=0L; //创建操作员ID
private Long activeOperatorId=0L; //激活操作员ID
private Long vmAccountId=0L; //所属虚拟款项ID
private Long bizId=0L; //业务ID
private Long version = 0L; //乐观锁版本号
private String description; //备注信息
private Date createDate; //创建时间
private Date modifyDate; //更新时间
private Date activeDate; //激活时间
private Date loseDate; //失效时间
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCouponNo() {
return couponNo;
}
public void setCouponNo(String couponNo) {
this.couponNo = couponNo;
}
public String getCouponPwd() {
return couponPwd;
}
public void setCouponPwd(String couponPwd) {
this.couponPwd = couponPwd;
}
public int getCouponValue() {
return couponValue;
}
public void setCouponValue(int couponValue) {
this.couponValue = couponValue;
}
public int getCouponType() {
return couponType;
}
public void setCouponType(int couponType) {
this.couponType = couponType;
}
public DiscountCouponStatus getCouponStatus() {
return couponStatus;
}
public void setCouponStatus(DiscountCouponStatus couponStatus) {
this.couponStatus = couponStatus;
}
public String getBatchNo() {
return batchNo;
}
public void setBatchNo(String batchNo) {
this.batchNo = batchNo;
}
public String getTopupChannel() {
return topupChannel;
}
public void setTopupChannel(String topupChannel) {
this.topupChannel = topupChannel;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getCreateOperatorId() {
return createOperatorId;
}
public void setCreateOperatorId(Long createOperatorId) {
this.createOperatorId = createOperatorId;
}
public Long getActiveOperatorId() {
return activeOperatorId;
}
public void setActiveOperatorId(Long activeOperatorId) {
this.activeOperatorId = activeOperatorId;
}
public Long getVmAccountId() {
return vmAccountId;
}
public void setVmAccountId(Long vmAccountId) {
this.vmAccountId = vmAccountId;
}
public Long getBizId() {
return bizId;
}
public void setBizId(Long bizId) {
this.bizId = bizId;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
public Date getLoseDate() {
return loseDate;
}
public void setLoseDate(Date loseDate) {
this.loseDate = loseDate;
}
public Date getActiveDate() {
return activeDate;
}
public void setActiveDate(Date activeDate) {
this.activeDate = activeDate;
}
}
|
package pom;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class JobPageObjects {
@FindBy(id="menu_admin_viewAdminModule")
public static WebElement adminButton;
@FindBy(id="menu_admin_Job")
public static WebElement job;
@FindBy(id="menu_admin_viewJobTitleList")
public static WebElement jobTitles;
@FindBy(name="btnAdd")
public static WebElement add;
@FindBy(id="jobTitle_jobTitle")
public static WebElement jobTitle;
@FindBy(id="jobTitle_jobDescription")
public static WebElement Description ;
@FindBy(id="jobTitle_jobSpec")
public static WebElement specification;
@FindBy(id="jobTitle_note")
public static WebElement Note ;
@FindBy(id="btnSave")
public static WebElement Save ;
@FindBy(id="menu_admin_viewPayGrades")
public static WebElement payGrades ;
@FindBy(id="btnAdd")
public static WebElement Add ;
@FindBy(id="payGrade_name")
public static WebElement payname ;
@FindBy(id="btnSave")
public static WebElement savebtn ;
@FindBy(id="btnAddCurrency")
public static WebElement AddCurrency;
@FindBy(id="payGradeCurrency_currencyName")
public static WebElement currency;
@FindBy(id="btnSaveCurrency")
public static WebElement SaveCurrency;
@FindBy(xpath="//*[@id=\"menu_admin_employmentStatus\"]")
public static WebElement empstatus;
@FindBy(id="btnAdd")
public static WebElement add1 ;
@FindBy(id="empStatus_name")
public static WebElement empnme ;
@FindBy(id="btnSave")
public static WebElement save1 ;
}
|
package application;
import java.io.IOException;
import java.util.List;
import application.controller.MainController;
import application.model.Artist;
import application.model.Tuple;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Main extends Application {
private MainController controller;
private BorderPane root;
@Override
public void start(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/application/view/Main.fxml"));
root = loader.load();
controller = loader.getController();
controller.setMainWindow(this);
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
public void showAllView(List<Artist> db) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/application/view/showAllv2.fxml"));
BorderPane ap = loader.load();
SplitPane sp = (SplitPane) root.getCenter();
sp.getItems().set(1, ap);
ListView<HBox> theListView = (ListView) ap.getCenter();
ObservableList<HBox> list = FXCollections.observableArrayList();
for(Artist artist: db) {
list.add(new Tuple(artist.getId()+"",artist.getFirstName(),artist.getLastName(),artist.getAge()+"").getTuple());
}
theListView.setItems(list);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void showAddView() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/application/view/AddView.fxml"));
Node node = loader.load();
SplitPane sp = (SplitPane) root.getCenter();
sp.getItems().set(1, node);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void showDeleteView() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/application/view/DeleteView.fxml"));
Node node = loader.load();
SplitPane sp = (SplitPane) root.getCenter();
sp.getItems().set(1, node);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void showUpdateView() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/application/view/UpdateView.fxml"));
Node node = loader.load();
SplitPane sp = (SplitPane) root.getCenter();
sp.getItems().set(1, node);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void clear() {
// SplitPane sp = (SplitPane) root.getCenter();
// sp.getItems().set(1, null);
}
}
|
package cn.v5cn.v5cms.filter;
import cn.v5cn.v5cms.service.SiteService;
import cn.v5cn.v5cms.entity.Site;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import static cn.v5cn.v5cms.util.SystemConstant.SITES_SESSION_KEY;
import static cn.v5cn.v5cms.util.SystemConstant.SITE_SESSION_KEY;
/**
* Created by ZYW on 2014/6/10.
*/
public class GlobalInterceptor extends HandlerInterceptorAdapter {
@Autowired
private SiteService siteService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
if(StringUtils.contains(request.getRequestURI(),"/manager/login")) return true;
HttpSession session = request.getSession();
if(session.getAttribute(SITES_SESSION_KEY) != null) return true;
ImmutableList<Site> resultBiz = siteService.findByIsclosesite(1);
Site temp = resultBiz.size() == 0 ? new Site(): resultBiz.get(0);
session.setAttribute(SITES_SESSION_KEY,resultBiz);
session.setAttribute(SITE_SESSION_KEY,temp);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
// if(modelAndView == null) return;
// modelAndView.addObject(BASE_PATH,getBasePath(request));
// modelAndView.addObject(CONTEXT_PATH,getContextPath(request));
// modelAndView.getModel().put(BASE_PATH,getBasePath(request));
// modelAndView.getModel().put(CONTEXT_PATH,getContextPath(request));
// request.setAttribute(BASE_PATH,getBasePath(request));
// request.setAttribute(CONTEXT_PATH,getContextPath(request));
}
}
|
package net.gdsspt.app.ui.fragment;
import com.smartydroid.android.starter.kit.app.StarterFragment;
/**
* Created by LittleHans on 2016/8/2.
*/
public class BaseFragment extends StarterFragment {
@Override protected int getFragmentLayout() {
return 0;
}
}
|
package com.eshop.controller;
import com.eshop.domain.Client;
import com.eshop.domain.Product;
import com.eshop.service.BasketService;
import com.eshop.service.ClientService;
import com.eshop.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* Controller class for basket requests handling.
*/
@Controller
public class BasketController {
@Autowired
private BasketService basketService;
@Autowired
private OrderService orderService;
@Autowired
private ClientService clientService;
private Logger logger = Logger.getLogger("logger");
/**
* Handle the request to "/basket" URL to go to the basket page.
* @param model model for view displaying
* @return name of the corresponding view
*/
@GetMapping("/basket")
public String getBasket(HttpServletRequest request, Model model) {
Map<Product, Integer> productsInBasket = basketService.getProductsInBasket(request);
model.addAttribute("items", productsInBasket);
try {
Client clientForView = clientService.getClientForView();
model.addAttribute("addresses", clientForView.getAddressList());
model.addAttribute("client", clientForView);
model.addAttribute("addressesSelf", orderService.getAllShops());
} catch (ClassCastException ex) {
logger.info("Not authorized attempt to go to the basket page");
}
logger.info("Go to basket page");
return "basket";
}
/**
* Handle the AJAX request to "/basket" URL to add one item of the particular product
* to the basket.
* @param id id of the product to add
* @param session current HTTP session
* @return total amount of all product items in a basket
*/
@GetMapping(value = "/basket", produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public ResponseEntity<Integer> addToBasketAjax(@RequestParam(name = "item") int id,
HttpSession session) {
Integer shop_basket = basketService.prepareProductsForBasket(id, session);
return new ResponseEntity<>(shop_basket, HttpStatus.OK);
}
/**
* Handle the AJAX request to "/delete" URL to remove all items of the particular product
* from the basket.
* @param id id of the product to remove
* @param session current HTTP session
* @return total price of all products in a basket
*/
@GetMapping(value = "/delete", produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public ResponseEntity<Double> deleteFromBasketAjax(@RequestParam(name = "delete") int id,
HttpSession session) {
Double totalPrice = basketService.deleteFromBAsket(id, session);
logger.info("Product deleted from basket completely");
return new ResponseEntity<>(totalPrice, HttpStatus.OK);
}
/**
* Handle the AJAX request to "/editOrderMinus" URL to remove one item of the particular product
* from the basket.
* @param id id of the product to remove
* @param session current HTTP session
* @return list of numbers that contains new total price and new amount of particular product in the basket
*/
@GetMapping(value = "/editOrderMinus", produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public ResponseEntity<List> editOrderFromBasketMinusAjax(@RequestParam(name = "editOrderMinus") int id,
HttpSession session) {
List<Number> result = basketService.editOrderMinus(id, session);
logger.info("Item of product removed from basket");
return new ResponseEntity<>(result, HttpStatus.OK);
}
/**
* Handle the AJAX request to "/editOrderMinus" URL to add one item of the particular product
* to the basket.
* @param id id of the product to remove
* @param session current HTTP session
* @return list of numbers that contains new total price and new amount of particular product in the basket
*/
@GetMapping(value = "/editOrderPlus", produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public ResponseEntity<List> editOrderFromBasketPlusAjax(@RequestParam(name = "editOrderPlus") int id,
HttpSession session) {
List<Number> result = basketService.editOrderPlus(id, session);
logger.info("Item of product added to basket");
return new ResponseEntity<>(result, HttpStatus.OK);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.