text
stringlengths
10
2.72M
package com.jw.BoardDAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.jw.BoardDTO.JWBoardDTO; public class JWBoardDAO { private static JWBoardDAO dao = new JWBoardDAO(); static public JWBoardDAO getBoardDAO() { return dao; } private JWBoardDAO() {} public List<JWBoardDTO> List(Connection conn) throws SQLException{ List<JWBoardDTO> list = new ArrayList<>(); StringBuilder sql = new StringBuilder(); ResultSet rs = null; sql.append(" select * from adboard "); try(PreparedStatement pstmt = conn.prepareStatement(sql.toString())) { rs = pstmt.executeQuery(); while(rs.next()) { JWBoardDTO dto = new JWBoardDTO(); dto.setBno(rs.getInt("bno")); dto.setBtitle(rs.getString("btitle")); dto.setBcontent(rs.getString("bcontent")); dto.setBwritedate(rs.getString("bwritedate")); dto.setBcategory(rs.getString("bcategory")); dto.setBhit(rs.getInt("bhit")); dto.setBup(rs.getInt("bup")); dto.setBimg(rs.getString("bimg")); dto.setId(rs.getString("id")); list.add(dto); } }catch(SQLException e) { System.out.println(e); } return list; } public void Insert(Connection conn, JWBoardDTO dto) throws SQLException { StringBuilder sql = new StringBuilder(); sql.append(" insert into adboard "); sql.append(" values(null, ?, ? "); sql.append(" , now(), ?, 0 "); sql.append(" , 0, ?,'master') "); try (PreparedStatement pstmt = conn.prepareStatement(sql.toString())){ pstmt.setString(1, dto.getBtitle()); pstmt.setString(2, dto.getBcontent()); pstmt.setString(3, dto.getBcategory()); pstmt.setString(4, dto.getBimg()); pstmt.executeUpdate(); } }; }
package edu.nyu.xyz.parser; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class ParserUtil { public static String getSelfDefinedJSONString (JSONArray jsonArray) { if (jsonArray == null || !(jsonArray instanceof JSONArray)) { throw new IllegalArgumentException("Input should be JSONArray typed!"); } StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < jsonArray.size(); i++) { if (i % 10000 == 0) { System.out.println("Item number " + i); } JSONObject object = (JSONObject) jsonArray.get(i); if(i == jsonArray.size() - 1) { stringBuilder.append(object.toJSONString()); } else { stringBuilder.append(object.toJSONString() + "\n"); } } return stringBuilder.toString(); } }
package org.sang.bean; import java.util.Date; public class Folder { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column folder.id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ private Integer id; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column folder.folder_name * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ private String folderName; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column folder.company_id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ private Integer companyId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column folder.staff_id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ private Integer staffId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column folder.parent_id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ private Integer parentId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column folder.create_time * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ private Date createTime; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column folder.id * * @return the value of folder.id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column folder.id * * @param id the value for folder.id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column folder.folder_name * * @return the value of folder.folder_name * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public String getFolderName() { return folderName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column folder.folder_name * * @param folderName the value for folder.folder_name * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public void setFolderName(String folderName) { this.folderName = folderName == null ? null : folderName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column folder.company_id * * @return the value of folder.company_id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public Integer getCompanyId() { return companyId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column folder.company_id * * @param companyId the value for folder.company_id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public void setCompanyId(Integer companyId) { this.companyId = companyId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column folder.staff_id * * @return the value of folder.staff_id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public Integer getStaffId() { return staffId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column folder.staff_id * * @param staffId the value for folder.staff_id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public void setStaffId(Integer staffId) { this.staffId = staffId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column folder.parent_id * * @return the value of folder.parent_id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public Integer getParentId() { return parentId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column folder.parent_id * * @param parentId the value for folder.parent_id * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public void setParentId(Integer parentId) { this.parentId = parentId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column folder.create_time * * @return the value of folder.create_time * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public Date getCreateTime() { return createTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column folder.create_time * * @param createTime the value for folder.create_time * * @mbg.generated Wed Jun 05 16:32:28 CST 2019 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } }
package poly.basic2; public class MainClass { public static void main(String[] args) { Child c= new Child(); c.method01(); c.method02(); c.method03(); Parent p = c; p.method01(); p.method02(); // p.method03(); System.out.println(p); System.out.println(c); System.out.println(p==c);//동일한 주소값 System.out.println("==================클래스 캐스팅 ==============="); /* * 다형성 적용시 자식이 원래 가지고 있던 멤버에 접근 할 수 없는 문제가 발생하는데 * 클래스 캐스팅으로 본래의 형태로 변경이 가능합니다 * 단, 다형성이 일어나지 않은 객체를 대상으로 캐스팅을 실행하면 * 에러가 발생합니다. */ Child cc = (Child)p; cc.method01(); cc.method02(); cc.method03(); //Parent pp = (Parent)new Object(); //(x) } }
package by.ez.smm.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import javax.ws.rs.*; import javax.ws.rs.core.Response; import by.ez.smm.service.UserService; @Controller @Path("/user") public class UserController extends AbstractController { @Autowired UserService userService; @GET @Path("/get") public Response getCurrentUser() { return Response.ok(userService.getById(1)).build(); } }
package com.george.springcloud.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.Mapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; /** * @author enchaolee */ @RestController @Slf4j public class ConfigClientController { @PostMapping("/configInfo") public void getConfigInfo() { System.out.println("===============github push 回调测试成功==========="); } }
package com.mycompany.cesar; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class Main { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/university?useTimezone=true&serverTimezone=GMT%2B8"; public static void main(String[] args) { Connection conn = createdataBaseConnection(); List<Instructor> instructores = BaseInstructor(conn); List<Advisor> advisor = BaseAdvisor(conn); List<Classroom> classrom = BaseClassroom(conn); List<Course> course = BaseCourse(conn); List<Department> department = BaseDepartment(conn); List<PreReq> prereq = BasePreReq(conn); List<Section> section = BaseSection(conn); List<Student> student = BaseStudent(conn); List<Takes> takes = BaseTakes(conn); List<Teaches> teaches = BaseTeaches(conn); List<Time_Slot> time_Slot = BaseTime_Slot(conn); System.out.println(instructores); System.out.println(advisor); System.out.println(classrom); System.out.println(course); System.out.println(department); System.out.println(prereq); System.out.println(section); System.out.println(student); System.out.println(takes); System.out.println(teaches); System.out.println(time_Slot); MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase db_uni = mongoClient.getDatabase("university"); //MONGO // collection 6 is missing bec MongoCollection collection1 = db_uni.getCollection("instructor"); MongoCollection collection2 = db_uni.getCollection("advisor"); MongoCollection collection3 = db_uni.getCollection("classroom"); MongoCollection collection4 = db_uni.getCollection("course"); MongoCollection collection5 = db_uni.getCollection("department"); MongoCollection collection6 = db_uni.getCollection("prereq"); MongoCollection collection7 = db_uni.getCollection("section"); MongoCollection collection8 = db_uni.getCollection("student"); MongoCollection collection9 = db_uni.getCollection("takes"); MongoCollection collection10= db_uni.getCollection("teaches"); MongoCollection collection11= db_uni.getCollection("time_slot"); collection1.drop(); collection2.drop(); collection3.drop(); collection4.drop(); collection5.drop(); collection6.drop(); collection7.drop(); collection8.drop(); collection9.drop(); collection10.drop(); collection11.drop(); db_uni.createCollection("instructor"); db_uni.createCollection("advisor"); db_uni.createCollection("classroom"); db_uni.createCollection("course"); db_uni.createCollection("department"); db_uni.createCollection("prereq"); db_uni.createCollection("section"); db_uni.createCollection("student"); db_uni.createCollection("takes"); db_uni.createCollection("teaches"); db_uni.createCollection("time_slot"); //Generacion de variables por extraccion de lista for (int i = 0; i < instructores.size(); i++) { Instructor instructIterable = instructores.get(i); //int ID = instructIterable String nombre = instructIterable.getNombre(); String deptName = instructIterable.getDeptName(); Double salary = instructIterable.getSalary(); Document instructorDoc = new Document().append("salary", salary) .append("nombre", nombre).append("deptName", deptName); collection1.insertOne(instructorDoc); } for (int i = 0; i < advisor.size(); i++) { Advisor advIterable = advisor.get(i); int i_ID = advIterable.getI_ID(); int s_ID = advIterable.getS_ID(); Document advisorDoc = new Document().append("i_ID", i_ID) .append("s_ID", s_ID); collection2.insertOne(advisorDoc); } for (int i = 0; i < classrom.size(); i++) { Classroom classIterable = classrom.get(i); String building = classIterable.getBuilding(); int room_building = classIterable.getRoom_number(); int capacity = classIterable.getCapacity(); Document classroomDoc = new Document() .append("building", building) .append("room_building", room_building) .append("capacity", capacity); collection3.insertOne(classroomDoc); } for (int i = 0; i < course.size(); i++) { Course courseIterable = course.get(i); String course_id =courseIterable.getCourse_id(); String title = courseIterable.getTitle(); String dept_name = courseIterable.getDept_name(); int credits = courseIterable.getCredits(); Document DocToInsert = new Document() .append("course_id", course_id) .append("title", title) .append("dept_name", dept_name) .append("credits", credits); collection4.insertOne(DocToInsert); } for (int i = 0; i < department.size(); i++) { Department Iterable = department.get(i); String dept_name = Iterable.getDept_name(); String building = Iterable.getBuilding(); Document DocToInsert = new Document() .append("dept_name", dept_name) .append("building", building); collection5.insertOne(DocToInsert); } for (int i = 0; i < prereq.size(); i++) { PreReq Iterable = prereq.get(i); String course_id =Iterable.getCourse_id(); String prereq_id =Iterable.getPrereq_id(); Document DocToInsert = new Document() .append("course_id", course_id) .append("prereq_id", prereq_id); collection6.insertOne(DocToInsert); } for (int i = 0; i < section.size(); i++) { Section Iterable = section.get(i); String course_id =Iterable.getCourse_id(); int sec_id =Iterable.getSec_id(); String semester = Iterable.getSemester(); int year= Iterable.getYear(); String building= Iterable.getBuilding(); int room_number = Iterable.getRoom_number(); String time_slot_id= Iterable.getTime_slot_id(); Document DocToInsert = new Document() .append("course_id",course_id) .append("sec_id",sec_id) .append("semester",semester) .append("semester",semester) .append("year",year) .append("building",building) .append("room_number",room_number) .append("time_slot_id",time_slot_id); collection7.insertOne(DocToInsert); } for (int i = 0; i < student.size(); i++) { Student Iterable = student.get(i); int ID = Iterable.getID(); String name = Iterable.getName(); String dept_name = Iterable.getDept_name(); int tot_cred = Iterable.getTot_cred(); Document DocToInsert = new Document() .append("ID",ID) .append("name",name) .append("dept_name",dept_name) .append("tot_cred",tot_cred); collection8.insertOne(DocToInsert); } for (int i = 0; i < department.size(); i++) { Department Iterable = department.get(i); Document DocToInsert = new Document(); collection10.insertOne(DocToInsert); } } static private Connection createdataBaseConnection() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL, "rodrigo", "rodrigo"); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return conn; } private static List<Instructor> BaseInstructor(Connection conn) { List<Instructor> instructores = new LinkedList<>(); try { Statement stm = conn.createStatement(); String sql = "SELECT * from instructor"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { String name = rs.getString("name"); String deptName = rs.getString("dept_name"); Double salary = rs.getDouble("salary"); Instructor inst = new Instructor(name, deptName, salary); instructores.add(inst); } } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return instructores; } private static List<Advisor> BaseAdvisor(Connection conn) { List<Advisor> advisor = new LinkedList<>(); try { Statement stm = conn.createStatement(); String sql = "SELECT * from advisor"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { int s_ID = rs.getInt("s_ID"); int i_ID = rs.getInt("i_ID"); Advisor adv = new Advisor(s_ID,i_ID); advisor.add(adv); } } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return advisor; } private static List<Classroom> BaseClassroom(Connection conn) { List<Classroom> classroom = new LinkedList<>(); try { Statement stm = conn.createStatement(); String sql = "SELECT * from classroom"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { String building = rs.getString("building"); int room_building = rs.getInt("room_number"); int capacity = rs.getInt("capacity"); Classroom classrom = new Classroom(building,room_building,capacity);; classroom.add(classrom); } } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return classroom; } private static List<Course> BaseCourse(Connection conn) { List<Course> course = new LinkedList<>(); try { Statement stm = conn.createStatement(); String sql = "SELECT * from course"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { String course_id =rs.getString("course_id"); String title = rs.getNString("title"); String dept_name = rs.getString("dept_name"); int credits = rs.getInt("credits"); Course cours = new Course(course_id,title,dept_name,credits); course.add(cours); } } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return course; } private static List<Department> BaseDepartment(Connection conn) { List<Department> department = new LinkedList<>(); try { Statement stm = conn.createStatement(); String sql = "SELECT * from department"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { String dept_name = rs.getString("dept_name"); String building = rs.getString("building"); int budget = rs.getInt("budget"); Department departmen = new Department(dept_name,building,budget); department.add(departmen); } } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return department; } private static List<PreReq> BasePreReq(Connection conn) { List<PreReq> preReq = new LinkedList<>(); try { Statement stm = conn.createStatement(); String sql = "SELECT * from prereq"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { String course_id =rs.getString("course_id"); String prereq_id =rs.getString("prereq_id"); PreReq preRe = new PreReq(course_id,prereq_id); preReq.add(preRe); } } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return preReq; } private static List<Section> BaseSection(Connection conn) { List<Section> section = new LinkedList<>(); try { Statement stm = conn.createStatement(); String sql = "SELECT * from section"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { String course_id =rs.getString("course_id"); int sec_id =rs.getInt("sec_id"); String semester =rs.getString("semester"); int year =rs.getInt("year"); String building =rs.getString("building"); int room_number =rs.getInt("room_number"); String time_slot_id =rs.getString("time_slot_id"); Section sectio = new Section(course_id,sec_id, semester,year,building, room_number, time_slot_id); section.add(sectio); } } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return section; } private static List<Student> BaseStudent(Connection conn) { List<Student> student = new LinkedList<>(); try { Statement stm = conn.createStatement(); String sql = "SELECT * from student"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { int ID = rs.getInt("ID"); String name = rs.getString("name"); String dept_name = rs.getString("dept_name"); int tot_cred = rs.getInt("tot_cred"); Student studen = new Student(ID,name, dept_name,tot_cred); student.add(studen); } } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return student; } private static List<Takes> BaseTakes(Connection conn) { List<Takes> takes = new LinkedList<>(); try { Statement stm = conn.createStatement(); String sql = "SELECT * from takes"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { int ID=rs.getInt("ID"); String course_id=rs.getString("course_id"); String sec_id=rs.getString("sec_id"); String semester=rs.getString("semester"); int year=rs.getInt("year"); String grade=rs.getString("grade"); Takes take = new Takes(ID,course_id, sec_id,semester,year,grade); takes.add(take); } } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return takes; } private static List<Teaches> BaseTeaches(Connection conn) { List<Teaches> teaches = new LinkedList<>(); try { Statement stm = conn.createStatement(); String sql = "SELECT * from teaches"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { int ID =rs.getInt("ID"); String course_id=rs.getString("course_id"); int sec_id=rs.getInt("sec_id"); String semester=rs.getString("semester"); int year=rs.getInt("year"); Teaches teache = new Teaches(ID,course_id, sec_id,semester,year); teaches.add(teache); } } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return teaches; } private static List<Time_Slot> BaseTime_Slot(Connection conn) { List<Time_Slot> time_Slot = new LinkedList<>(); try { Statement stm = conn.createStatement(); String sql = "SELECT * from time_Slot"; ResultSet rs = stm.executeQuery(sql); while (rs.next()) { String time_slot_id=rs.getString("time_slot_id"); String day=rs.getString("day"); int start_hr =rs.getInt("start_hr"); int start_min=rs.getInt("start_min"); int end_hr=rs.getInt("end_hr"); int end_min=rs.getInt("end_min"); Time_Slot time_Slo = new Time_Slot(time_slot_id,day, start_hr,start_min,end_hr,end_min); time_Slot.add(time_Slo); } } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return time_Slot; } }
public class SetPrice1 extends SetPrice { public SetPrice1(Data data) { d=data; } @Override public void SetPrice(int g) { if(g==1){ ((Data1)d).setPrice(((Data1)d).getRprice()); System.out.println("Regular gas has been selected"); } else if(g==2) { ((Data1)d).setPrice(((Data1)d).getSprice()); System.out.println("Super gas has been selected"); } } }
package com.tencent.mm.plugin.account.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; class RegByMobileSendSmsUI$10 implements OnMenuItemClickListener { final /* synthetic */ RegByMobileSendSmsUI eVm; RegByMobileSendSmsUI$10(RegByMobileSendSmsUI regByMobileSendSmsUI) { this.eVm = regByMobileSendSmsUI; } public final boolean onMenuItemClick(MenuItem menuItem) { RegByMobileSendSmsUI.d(this.eVm); return true; } }
package br.com.unopar.delivery.controller; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import br.com.unopar.delivery.model.Cliente; import br.com.unopar.delivery.model.Estabelecimento; import br.com.unopar.delivery.model.Usuario; import br.com.unopar.delivery.service.ClienteService; import br.com.unopar.delivery.service.EstabelecimentoService; import br.com.unopar.delivery.service.UsuarioService; import br.com.unopar.delivery.util.Role; @Controller public class UsuarioController { @Autowired private UsuarioService usuarioService; @Autowired private EstabelecimentoService estabelecimentoService; @Autowired private ClienteService clienteService; @RequestMapping(value="/login", method=RequestMethod.POST) public String login(@RequestParam("login") String login, @RequestParam("senha") String senha, HttpSession session, ModelMap map) { if (login == null || login.isEmpty() || senha == null || senha.isEmpty()) { map.addAttribute("error", "Preencha todos os campos"); return "welcome"; } List<Usuario> usuarios = usuarioService.getUsuarioByLogin(login, senha); if (usuarios == null || usuarios.isEmpty()) { map.addAttribute("error", "login ou senha inválidos"); return "welcome"; } Usuario usuario = usuarios.get(0); if (usuario.getRole().equals(Role.CLIENTE)) { Cliente cliente = clienteService.getByUsuarioId(usuario.getId()); session.setAttribute("usuario", cliente); List<Estabelecimento> estabelecimentos = estabelecimentoService.getAll(); map.addAttribute("estabelecimentos", estabelecimentos); return "cliente/pedidos"; } else { Estabelecimento estabelecimento = estabelecimentoService.getByUsuarioId(usuario.getId()); session.setAttribute("usuario", estabelecimento); return "redirect:/estabelecimento/pedidos"; } } @RequestMapping(value="/logout", method=RequestMethod.GET) public String logout(HttpSession session) { session.invalidate(); return "welcome"; } }
package com.challenge.controller; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.challenge.constant.AssignmentConstant; import com.challenge.dto.Statistics; import com.challenge.dto.Transaction; import com.challenge.service.IStatisticsService; /** * All operations related to indexes this controller. * */ @RestController public class TransactionController { @Autowired IStatisticsService statisticsService; private static final Logger LOG = LoggerFactory.getLogger(TransactionController.class); /** * * Every time new tick arrives, it store it in allStatisticMap, update * overAllStatsMap and latestStatsByInstrument * * @return */ @PostMapping("/ticks") public void createTransaction(@Valid @RequestBody Transaction transaction, HttpServletResponse response) { // Validate Transaction if (transaction == null || transaction.getPrice() < 0.0 || transaction.getInstrument() == null || transaction.getInstrument().length() <= 0 || transaction.getTimeStamp() <= 0) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } long currentTimeStamp = Instant.now(Clock.systemUTC()).getEpochSecond(); long transactionTimestamp = Instant.ofEpochMilli(transaction.getTimeStamp()).atOffset(ZoneOffset.UTC) .toEpochSecond(); long diff = currentTimeStamp - transactionTimestamp; // Discard ticks older than 60 seconds if (diff > AssignmentConstant.TRANSACTION_EXPIRED_DURATION) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } transaction.setTimeStamp(transactionTimestamp); if (currentTimeStamp >= transactionTimestamp) { // Ticks which are in range (60 seconds) statisticsService.addTransaction(transaction); LOG.debug("Transaction added."); } else { // All Future ticks will be store in separate map and period job // will put it in actual map. statisticsService.addFutureTransaction(transaction); LOG.debug("Future Transaction added."); } response.setStatus(HttpServletResponse.SC_CREATED); } /** * returns aggregated statistics for all ticks across all instrument * * @return */ @GetMapping("/statistics") public Statistics getStatistics() { return statisticsService.getStatistics(); } /** * returns aggregated statistics for all ticks across single instrument * * @return */ @GetMapping("/statistics/{instrument}") public Statistics getStatisticsByInstrument(@Valid @PathVariable String instrument) { return statisticsService.getStatisticsByInstrument(instrument); } }
package ch21.ex21_04; import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; public class OtherShortStrings implements ListIterator<String>{ private ListIterator<String> strings; private String prevShort; private int prevIndex; private String nextShort; private int nextIndex; private int maxLen; public OtherShortStrings(ListIterator<String> strings, int maxLen) { this.strings = strings; this.maxLen = maxLen; } public void add(String e) { throw new UnsupportedOperationException(); } public boolean hasNext() { if(nextShort != null) { return true; } while(strings.hasNext()) { nextIndex = strings.nextIndex(); nextShort = strings.next(); if(nextShort.length() <= maxLen) { return true; } } nextShort = null; return false; } public String next() { if(nextShort == null && !hasNext()) { throw new NoSuchElementException(); } String n = nextShort; nextShort = null; nextIndex = -1; return n; } public void remove() { throw new UnsupportedOperationException(); } public boolean hasPrevious() { if(prevShort != null){ return true; } while(strings.hasPrevious()) { prevIndex = strings.previousIndex(); prevShort = strings.previous(); if(prevShort.length() <= maxLen) { return true; } } prevShort = null; return false; } public int nextIndex() { if(nextIndex == -1 && !hasPrevious()) { return -1; } return nextIndex; } public String previous() { if(prevShort == null && !hasPrevious()) { throw new NoSuchElementException(); } String n = prevShort; prevShort = null; prevIndex = -1; return n; } public int previousIndex() { if(prevIndex == -1 && !hasPrevious()) { return -1; } return prevIndex; } public void set(String e) { throw new UnsupportedOperationException(); } }
package it.basestation.cmdline; import java.util.Hashtable; // non utilizzata public class DeltaCounter { private Hashtable<String, Double> lastRecordedValues = new Hashtable<String, Double>(); public DeltaCounter() { // TODO Auto-generated constructor stub } public void elabDelta(CapabilityInstance cI){ if(!this.lastRecordedValues.containsKey(cI.getName())){ this.lastRecordedValues.put(cI.getName(), cI.getValue()); cI.setValue(0); }else{ double lastValue = this.lastRecordedValues.get(cI.getName()); double newValue = cI.getValue(); if(lastValue <= newValue){ // nessun reboot del nodo double delta = newValue - lastValue; cI.setValue(delta); this.lastRecordedValues.put(cI.getName(), newValue); }else{ // reboot del nodo this.lastRecordedValues.put(cI.getName(), cI.getValue()); } } } }
package com.project.service.taxi.exception; public class LoginAndPasswordException extends RuntimeException { }
package com.onplan.adviser; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import java.util.Collection; import java.util.Map; /** * Contains information about a strategy. */ public final class StrategyInfo extends TemplateInfo { private String id; private Map<String, String> executionParameters; private Collection<String> registeredInstruments; private StrategyStatisticsSnapshot strategyStatisticsSnapshot; public String getId() { return id; } public Map<String, String> getExecutionParameters() { return executionParameters; } public Collection<String> getRegisteredInstruments() { return registeredInstruments; } public void setId(String id) { this.id = id; } public void setExecutionParameters(Map<String, String> executionParameters) { this.executionParameters = executionParameters; } public void setRegisteredInstruments(Collection<String> registeredInstruments) { this.registeredInstruments = registeredInstruments; } public StrategyStatisticsSnapshot getStrategyStatisticsSnapshot() { return strategyStatisticsSnapshot; } public void setStrategyStatisticsSnapshot(StrategyStatisticsSnapshot strategyStatisticsSnapshot) { this.strategyStatisticsSnapshot = strategyStatisticsSnapshot; } public StrategyInfo() { // Intentionally empty. } public StrategyInfo(String displayName, String className, Iterable<String> availableParameters, String id, Map<String, String> executionParameters, Collection<String> registeredInstruments, StrategyStatisticsSnapshot strategyStatisticsSnapshot) { super(displayName, className, availableParameters); this.id = id; this.executionParameters = executionParameters; this.registeredInstruments = registeredInstruments; this.strategyStatisticsSnapshot = strategyStatisticsSnapshot; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StrategyInfo strategyInfo = (StrategyInfo) o; return Objects.equal(this.id, strategyInfo.id) && Objects.equal(this.displayName, strategyInfo.displayName) && Objects.equal(this.className, strategyInfo.className) && Objects.equal(this.availableParameters, strategyInfo.availableParameters) && Objects.equal(this.executionParameters, strategyInfo.executionParameters) && Objects.equal(this.registeredInstruments, strategyInfo.registeredInstruments) && Objects.equal(this.strategyStatisticsSnapshot, strategyInfo.strategyStatisticsSnapshot); } @Override public int hashCode() { return Objects.hashCode(id, displayName, className, availableParameters, executionParameters, registeredInstruments, strategyStatisticsSnapshot); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("id", id) .add("displayName", displayName) .add("className", className) .add("availableParameters", availableParameters) .add("executionParameters", executionParameters) .add("registeredInstruments", registeredInstruments) .add("strategyStatisticsSnapshot", strategyStatisticsSnapshot) .toString(); } }
package com.song.mvchttpencapsulation.model; /** * Created by 宋。 on 2018/8/2. */ public interface HttpCallback { public void onSuccess(Object obj,int tag); public void onError(String msg); }
package com.sunbing.demo.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.extension.activerecord.Model; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * 车辆表 * </p> * * @author sunbing * @since 2021-03-17 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class Vehicle extends Model<Vehicle> { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 识别码 */ private String vin; /** * 生产年份 */ private Integer year; /** * 生产国家 */ private String make; /** * 车型 */ private String model; /** * 颜色 */ private String color; /** * 车辆类型 */ private Integer vehicleType; // /** // * 车门数 // */ // private Integer doorCount; /** * 内包装尺寸 */ private Integer boxSize; /** * 扩展驾驶室 */ private Integer extendedCab; /** * 是否推拉门 */ private Integer powerSlidingDoor; /** * 是否全轮驱动 */ private Integer allWheelDrive; @Override protected Serializable pkVal() { return this.id; } }
package com.eres.waiter.waiter.retrofit; import android.content.Context; import com.eres.waiter.waiter.preferance.SettingPreferances; import com.readystatesoftware.chuck.ChuckInterceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class ApiClient { private static final String BASE_URL = SettingPreferances.preferances.getUrl(); private static Retrofit retrofit = null; public static Retrofit getRetrofit(Context context) { if (retrofit == null) { OkHttpClient.Builder builder = new OkHttpClient().newBuilder(); OkHttpClient client = builder .addInterceptor(new ChuckInterceptor(context)).addInterceptor(chain -> { Request request = chain.request().newBuilder().addHeader("token", SettingPreferances.preferances.getIme()).addHeader("Authorization","bearer "+SettingPreferances.preferances.getAuthorization()).build(); return chain.proceed(request); }).build(); retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }
package uk.gov.hmcts.befta; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import io.restassured.RestAssured; import uk.gov.hmcts.befta.data.RecentExecutionsInfo; import uk.gov.hmcts.befta.util.BeftaUtils; import uk.gov.hmcts.befta.util.JsonUtils; import static java.lang.String.format; import static uk.gov.hmcts.befta.util.BeftaUtils.defaultLog; public class DefaultBeftaTestDataLoader implements BeftaTestDataLoader { private boolean isTestDataLoadedForCurrentRound = false; @Override public synchronized boolean isTestDataLoadedForCurrentRound() { return this.isTestDataLoadedForCurrentRound; } @Override public synchronized void loadTestDataIfNecessary() { if (!isTestDataLoadedForCurrentRound && !shouldSkipDataLoad()) { try { RestAssured.useRelaxedHTTPSValidation(); doLoadTestData(); updateDataLoadDetailsInRecentExecutionsInfo(); } catch (Exception e) { throw e; } finally { isTestDataLoadedForCurrentRound = true; } } } protected void doLoadTestData() { } private boolean shouldSkipDataLoad() { try { //declaring with a dummy last execution time String recentExecutionTime = "2020-01-01T00:00:00.001"; File recentExecutionFile = new File(TestAutomationAdapter.EXECUTION_INFO_FILE); double testDataLoadSkipPeriod = BeftaMain.getConfig().getTestDataLoadSkipPeriod(); defaultLog(format("testDataLoadSkipPeriod from the config: %s minutes", testDataLoadSkipPeriod)); if(recentExecutionFile.exists()) { RecentExecutionsInfo recentExecutionsInfo = JsonUtils .readObjectFromJsonFile(TestAutomationAdapter.EXECUTION_INFO_FILE, RecentExecutionsInfo.class); recentExecutionTime = recentExecutionsInfo.getLastExecutionTime(); defaultLog(format("recent exec file exists and timestamp is : %s", recentExecutionTime)); if (isWithinSkipPeriod( recentExecutionTime, testDataLoadSkipPeriod) && wasMostRecentDataForSameTests(recentExecutionsInfo)) { defaultLog("Should skip loading data."); return true; } } } catch (Exception e) { defaultLog("Should NOT skip loading data.", e); return false; } return false; } private void updateDataLoadDetailsInRecentExecutionsInfo() { String recentExecutionsInfoFilePath = TestAutomationAdapter.EXECUTION_INFO_FILE; String dateTimeFormat = BeftaUtils.getDateTimeFormatRequested("now"); String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateTimeFormat)); RecentExecutionsInfo recentExecutionsInfo = new RecentExecutionsInfo(); recentExecutionsInfo.setLastExecutionTime(currentTime); recentExecutionsInfo.setLastExecutionProjectRepo(getCurrentGitRepo()); recentExecutionsInfo.setLastExecutionProjectBranch(getCurrentGitBranch()); try { JsonUtils.writeJsonToFile(recentExecutionsInfoFilePath, recentExecutionsInfo); } catch (Exception e) { e.printStackTrace(); } } private String getCurrentGitBranch() { String branchName = ""; try { Process process = Runtime.getRuntime().exec("git rev-parse --abbrev-ref HEAD"); process.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); branchName = reader.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } return branchName; } public String getCurrentGitRepo() { String repoName = System.getProperty("user.dir"); repoName = repoName.substring(repoName.lastIndexOf("/") + 1); try { Process process = Runtime.getRuntime().exec("git remote -v"); process.waitFor(); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); repoName = reader.readLine(); if (null != repoName && repoName.contains(".git")) { repoName = repoName.substring(repoName.indexOf(":hmcts/") + 7, repoName.lastIndexOf(".git")); } } catch (Exception e) { e.printStackTrace(); } return repoName.trim(); } private boolean isWithinSkipPeriod( String recentExecutionTime, double testDataLoadSkipPeriod) { LocalDateTime currentTime = LocalDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"); LocalDateTime givenDateTIme = LocalDateTime.parse(recentExecutionTime, format); Long timeDifference = Duration.between(givenDateTIme, currentTime).toMinutes(); defaultLog(format("Reload test data if last test execution time (%s minutes ago) is " + "greater than skip period value (%s minutes)", timeDifference, testDataLoadSkipPeriod)); return timeDifference < testDataLoadSkipPeriod; } private boolean wasMostRecentDataForSameTests(RecentExecutionsInfo recentExecutionsInfo) { String repoName = recentExecutionsInfo.getLastExecutionProjectRepo(); String branchName = recentExecutionsInfo.getLastExecutionProjectBranch(); String recentRepoSubString = repoName.substring(repoName.lastIndexOf("/") + 1); if (getCurrentGitRepo().contains(recentRepoSubString) && getCurrentGitBranch().equalsIgnoreCase(branchName)) { defaultLog(format("the repository (%s) and the branch (%s) from the recent execution" + " of %s matched", getCurrentGitRepo(), branchName, recentRepoSubString)); return true; } else { defaultLog(format("The repository (%s) and the branch (%s) do not match: ", getCurrentGitRepo(), branchName)); } return false; } }
package levels; public class Level_Demo { public static void main(String[] args) { // TODO Auto-generated method stub } }
package com.tencent.mm.plugin.voip.b; import android.app.Notification; import android.app.Notification.Builder; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Build.VERSION; import android.os.Environment; import android.widget.Toast; import com.tencent.mm.g.a.au; import com.tencent.mm.g.a.ax; import com.tencent.mm.g.a.bg; import com.tencent.mm.g.a.su; import com.tencent.mm.k.g; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public final class d { public static Context oSX = null; private static final String oSY; private static final Uri oSZ = Uri.parse("content://com.lbe.security.miui.permmgr/active"); static { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("VERSION.RELEASE:[" + VERSION.RELEASE); stringBuilder.append("] VERSION.CODENAME:[" + VERSION.CODENAME); stringBuilder.append("] VERSION.INCREMENTAL:[" + VERSION.INCREMENTAL); stringBuilder.append("] BOARD:[" + Build.BOARD); stringBuilder.append("] DEVICE:[" + Build.DEVICE); stringBuilder.append("] DISPLAY:[" + Build.DISPLAY); stringBuilder.append("] FINGERPRINT:[" + Build.FINGERPRINT); stringBuilder.append("] HOST:[" + Build.HOST); stringBuilder.append("] MANUFACTURER:[" + Build.MANUFACTURER); stringBuilder.append("] MODEL:[" + Build.MODEL); stringBuilder.append("] PRODUCT:[" + Build.PRODUCT); stringBuilder.append("] TAGS:[" + Build.TAGS); stringBuilder.append("] TYPE:[" + Build.TYPE); stringBuilder.append("] USER:[" + Build.USER + "]"); oSY = stringBuilder.toString(); } public static boolean bLP() { return true; } public static int bLQ() { return VERSION.SDK_INT; } private static boolean bLR() { boolean z = false; FileInputStream fileInputStream; try { Properties properties = new Properties(); fileInputStream = new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")); try { properties.load(fileInputStream); String property = properties.getProperty("ro.miui.ui.version.name", null); if (property != null && property.equals("V6")) { z = true; } } catch (IOException e) { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e2) { } } x.d("VoipUtil", "isMIUIv6 " + z); return z; } } catch (IOException e3) { fileInputStream = null; if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e22) { } } x.d("VoipUtil", "isMIUIv6 " + z); return z; } x.d("VoipUtil", "isMIUIv6 " + z); return z; } public static boolean em(Context context) { boolean z = false; if (bLR()) { z = ep(context); } x.d("VoipUtil", "isLbePermissionEnable ret:" + z); return z; } public static boolean en(Context context) { boolean z = false; if (bLR()) { z = eo(context); } x.d("VoipUtil", "setLbePermissionEnable ret:" + z); return z; } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ private static boolean eo(android.content.Context r12) { /* r11 = 2; r9 = 0; r10 = 131072; // 0x20000 float:1.83671E-40 double:6.47582E-319; r7 = 1; r8 = 0; r6 = -1; r0 = r12.getContentResolver(); Catch:{ Throwable -> 0x00a9, all -> 0x00cc } r1 = oSZ; Catch:{ Throwable -> 0x00f1, all -> 0x00cc } r2 = 1; r2 = new java.lang.String[r2]; Catch:{ Throwable -> 0x00f1, all -> 0x00cc } r3 = 0; r4 = "userAccept"; r2[r3] = r4; Catch:{ Throwable -> 0x00f1, all -> 0x00cc } r3 = "pkgName='com.tencent.mm'"; r4 = 0; r5 = 0; r2 = r0.query(r1, r2, r3, r4, r5); Catch:{ Throwable -> 0x00f1, all -> 0x00cc } if (r2 == 0) goto L_0x00fb; L_0x0021: r1 = r2.getCount(); Catch:{ Throwable -> 0x00f4 } if (r1 <= 0) goto L_0x00fb; L_0x0027: r1 = r2.moveToLast(); Catch:{ Throwable -> 0x00f4 } if (r1 == 0) goto L_0x00fb; L_0x002d: r1 = 0; r6 = r2.getInt(r1); Catch:{ Throwable -> 0x00f4 } r1 = r6; L_0x0033: if (r2 == 0) goto L_0x0038; L_0x0035: r2.close(); L_0x0038: r2 = "VoipUtil"; r3 = "setLbePermissionEnable query ua: "; r4 = 3; r4 = new java.lang.Object[r4]; r5 = java.lang.Integer.valueOf(r1); r4[r8] = r5; r5 = " flag: "; r4[r7] = r5; r5 = java.lang.Integer.valueOf(r10); r4[r11] = r5; com.tencent.mm.sdk.platformtools.x.d(r2, r3, r4); r2 = -1; r3 = -1; if (r1 == r3) goto L_0x00f6; L_0x0059: if (r0 == 0) goto L_0x00f6; L_0x005b: r1 = r1 | r10; r3 = new android.content.ContentValues; Catch:{ Throwable -> 0x00d4 } r3.<init>(); Catch:{ Throwable -> 0x00d4 } r4 = "userAccept"; r5 = java.lang.Integer.valueOf(r1); Catch:{ Throwable -> 0x00d4 } r3.put(r4, r5); Catch:{ Throwable -> 0x00d4 } r4 = oSZ; Catch:{ Throwable -> 0x00d4 } r5 = "pkgName='com.tencent.mm'"; r6 = 0; r0 = r0.update(r4, r3, r5, r6); Catch:{ Throwable -> 0x00d4 } r2 = "VoipUtil"; r3 = "serLbePermissionEnable update ua: "; r4 = 5; r4 = new java.lang.Object[r4]; Catch:{ Throwable -> 0x00ec } r5 = 0; r1 = java.lang.Integer.valueOf(r1); Catch:{ Throwable -> 0x00ec } r4[r5] = r1; Catch:{ Throwable -> 0x00ec } r1 = 1; r5 = " flag: "; r4[r1] = r5; Catch:{ Throwable -> 0x00ec } r1 = 2; r5 = 131072; // 0x20000 float:1.83671E-40 double:6.47582E-319; r5 = java.lang.Integer.valueOf(r5); Catch:{ Throwable -> 0x00ec } r4[r1] = r5; Catch:{ Throwable -> 0x00ec } r1 = 3; r5 = " ret: "; r4[r1] = r5; Catch:{ Throwable -> 0x00ec } r1 = 4; r5 = java.lang.Integer.valueOf(r0); Catch:{ Throwable -> 0x00ec } r4[r1] = r5; Catch:{ Throwable -> 0x00ec } com.tencent.mm.sdk.platformtools.x.d(r2, r3, r4); Catch:{ Throwable -> 0x00ec } L_0x00a4: r2 = r0; L_0x00a5: if (r2 <= 0) goto L_0x00ea; L_0x00a7: r0 = r7; L_0x00a8: return r0; L_0x00a9: r1 = move-exception; r2 = r9; r0 = r9; L_0x00ac: r3 = "VoipUtil"; r4 = "isLbePermissionEnable query "; r5 = 2; r5 = new java.lang.Object[r5]; Catch:{ all -> 0x00ef } r9 = 0; r5[r9] = r1; Catch:{ all -> 0x00ef } r1 = 1; r9 = 131072; // 0x20000 float:1.83671E-40 double:6.47582E-319; r9 = java.lang.Integer.valueOf(r9); Catch:{ all -> 0x00ef } r5[r1] = r9; Catch:{ all -> 0x00ef } com.tencent.mm.sdk.platformtools.x.w(r3, r4, r5); Catch:{ all -> 0x00ef } if (r2 == 0) goto L_0x00f8; L_0x00c6: r2.close(); r1 = r6; goto L_0x0038; L_0x00cc: r0 = move-exception; r2 = r9; L_0x00ce: if (r2 == 0) goto L_0x00d3; L_0x00d0: r2.close(); L_0x00d3: throw r0; L_0x00d4: r0 = move-exception; r1 = r0; L_0x00d6: r0 = "VoipUtil"; r3 = "isLbePermissionEnable update "; r4 = new java.lang.Object[r11]; r4[r8] = r1; r1 = java.lang.Integer.valueOf(r10); r4[r7] = r1; com.tencent.mm.sdk.platformtools.x.w(r0, r3, r4); goto L_0x00a5; L_0x00ea: r0 = r8; goto L_0x00a8; L_0x00ec: r1 = move-exception; r2 = r0; goto L_0x00d6; L_0x00ef: r0 = move-exception; goto L_0x00ce; L_0x00f1: r1 = move-exception; r2 = r9; goto L_0x00ac; L_0x00f4: r1 = move-exception; goto L_0x00ac; L_0x00f6: r0 = r2; goto L_0x00a4; L_0x00f8: r1 = r6; goto L_0x0038; L_0x00fb: r1 = r6; goto L_0x0033; */ throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.plugin.voip.b.d.eo(android.content.Context):boolean"); } private static boolean ep(Context context) { Throwable th; Cursor query; try { query = context.getContentResolver().query(oSZ, new String[]{"suggestAccept", "userAccept", "userPrompt", "userReject"}, "pkgName='com.tencent.mm'", null, null); if (query != null) { try { if (query.getCount() > 0 && query.moveToLast()) { boolean z = ((query.getInt(0) & 131072) == 131072 && (query.getInt(2) & 131072) == 0 && (query.getInt(3) & 131072) == 0) || (query.getInt(1) & 131072) == 131072; if (query == null) { return z; } query.close(); return z; } } catch (Throwable th2) { th = th2; try { x.w("gray", "isLbePermissionEnable", new Object[]{th, Integer.valueOf(131072)}); if (query != null) { query.close(); } return false; } catch (Throwable th3) { th = th3; if (query != null) { query.close(); } throw th; } } } if (query != null) { query.close(); } } catch (Throwable th4) { th = th4; query = null; if (query != null) { query.close(); } throw th; } return false; } public static void O(Context context, int i) { Toast.makeText(context, i, 0).show(); } public static int oH(String str) { int i = 0; try { return bi.getInt(g.AT().getValue(str), 0); } catch (Exception e) { x.e("VoipUtil", "getIntValFromDynamicConfig parseInt failed, val: " + str); return i; } } public static boolean bLS() { ax axVar = new ax(); a.sFg.m(axVar); return axVar.bIs.bwu; } public static boolean bLT() { su suVar = new su(); suVar.cdE.bOh = 2; a.sFg.m(suVar); return suVar.cdF.cdG; } public static boolean bLU() { bg bgVar = new bg(); a.sFg.m(bgVar); return bgVar.bIM.bwu; } public static boolean bLV() { au auVar = new au(); a.sFg.m(auVar); return auVar.bIm.bIn; } public static Notification a(Builder builder) { if (com.tencent.mm.compatible.util.d.fS(16)) { return builder.getNotification(); } return builder.build(); } }
package lesson04; import lesson04.DayOfWeek04_4_1; import java.util.Scanner; public class DayOfWeek04_4_2 { public static void main(String[] args) { var input = new Scanner(System.in); System.out.println("Nhập thứ trong tuần bằng tiếng việt: "); var VieName = input.nextLine(); VieName = VieName.toLowerCase(); getDay(VieName); System.out.println(VieName + " -> " + getDay(VieName)); } private static String getDay(String vieName) { String EngName = switch (vieName) { case "thứ hai" -> DayOfWeek04_4_1.DayOfWeek.monday.getValue(); case "thứ ba" -> DayOfWeek04_4_1.DayOfWeek.tuesday.getValue(); case "thứ tư" -> DayOfWeek04_4_1.DayOfWeek.wednesday.getValue(); case "thứ năm" -> DayOfWeek04_4_1.DayOfWeek.thursday.getValue(); case "thứ sáu" -> DayOfWeek04_4_1.DayOfWeek.friday.getValue(); case "thứ bảy" -> DayOfWeek04_4_1.DayOfWeek.saturday.getValue(); case "chủ nhật" -> DayOfWeek04_4_1.DayOfWeek.sunday.getValue(); default -> "Không hợp lệ, vui lòng nhập lại"; }; return EngName; } }
package com.jenkins.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class TerminalCMD { private final static String JOINER = " & "; private List<String> commands; public TerminalCMD(boolean isLinux) { this.commands = new ArrayList<>(); if(isLinux) { this.commands.add("sh"); this.commands.add("-c"); }else { this.commands.add("sh"); this.commands.add("-c"); } } public String runBulk(List<String> commands,FileLogger logger) throws IOException, InterruptedException { ProcessBuilder builder = getDefualtBuilder(); builder.command().add(concatAllCommands(commands)); String res = run(builder,logger); return res; } public String runInSequence(List<String> commands,FileLogger logger) throws IOException, InterruptedException { StringBuilder res = new StringBuilder(); for(String command : commands) { ProcessBuilder builder = getDefualtBuilder(); builder.command().add(command); String out = run(builder,logger); res.append(out); } return res.toString(); } private String concatAllCommands(List<String> commands) { return commands.stream().collect(Collectors.joining(JOINER)); } public String run(String command,FileLogger logger) throws IOException, InterruptedException { ProcessBuilder builder = getDefualtBuilder(); builder.command().add(command); return run(builder,logger); } public String run(ProcessBuilder builder,FileLogger logger) throws IOException, InterruptedException { Process process = builder.start(); String res = run(process,logger); process.destroy(); return res; } public String run(Process process, FileLogger logger) throws IOException, InterruptedException { BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; StringBuilder sb = new StringBuilder(); while (true) { line = r.readLine(); if(line!=null && line.equals(logger.getClosingKey())) { logger.log("Closing key recieved :: shutting down jenkins"); r.close(); return sb.toString(); } if (line == null) { break; } line = line + "\n"; logger.log(line); sb.append(line); } return sb.toString(); } private ProcessBuilder getDefualtBuilder() { ProcessBuilder builder = new ProcessBuilder(); builder.redirectErrorStream(true); builder.command().add(this.commands.get(0)); builder.command().add(this.commands.get(1)); return builder; } }
package com.techelevator; import com.techelevator.tenmo.model.Authority; import com.techelevator.tenmo.model.User; import org.junit.Assert; import org.junit.Test; import java.util.HashSet; import java.util.Set; public class UserTest { User user = new User(); @Test public void userId_is_7(){ Long newId = 7L; user.setId(newId); Assert.assertEquals(newId, user.getId()); } @Test public void username_is_username(){ user.setUsername("username"); Assert.assertEquals("username", user.getUsername()); } @Test public void password_is_topsecret(){ user.setPassword("topsecret"); Assert.assertEquals("topsecret", user.getPassword()); } @Test public void isActivated_is_true(){ user.setActivated(true); Assert.assertTrue(user.isActivated()); } @Test public void setAuthorities_is_authority(){ Set<Authority> authority = new HashSet<>(); Set<Authority> authorityTwo = new HashSet<>(); user.setAuthorities(authority); Assert.assertEquals(authorityTwo, user.getAuthorities()); } }
package com.smxknife.java2.io.writer; import java.io.CharArrayWriter; import java.io.IOException; /** * @author smxknife * 2018/11/20 */ public class CharArrayWriterDemo { public static void main(String[] args) throws IOException { CharArrayWriter charArrayWriter = new CharArrayWriter(); charArrayWriter.write("你好".toCharArray()); System.out.println(charArrayWriter.toString()); } }
package com.tencent.mm.plugin.scanner.util; import android.os.Bundle; public interface b$a { void E(Bundle bundle); void b(int i, String str, byte[] bArr, byte[] bArr2, int i2, int i3); void bsf(); }
package com.julivalex.note.adapter; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.res.Resources; import android.icu.util.Calendar; import android.os.Handler; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.julivalex.note.R; import com.julivalex.note.Utils; import com.julivalex.note.fragment.CurrentTaskFragment; import com.julivalex.note.model.Item; import com.julivalex.note.model.ModelSeparator; import com.julivalex.note.model.ModelTask; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by julivalex on 09.09.17. */ public class CurrentTasksAdapter extends TaskAdapter { private static final int TYPE_TASK = 0; private static final int TYPE_SEPARATOR = 1; public CurrentTasksAdapter(CurrentTaskFragment taskFragment) { super(taskFragment); } @Override public int getItemViewType(int position) { //Выбираем тип задачи или разделителя if(getItem(position).isTask()) { return TYPE_TASK; } else { return TYPE_SEPARATOR; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { //Если тип - задача, по инфлейтим соответствующий layout case TYPE_TASK: View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.model_task, parent, false); TextView title = (TextView) v.findViewById(R.id.tvTaskTitle); TextView date = (TextView) v.findViewById(R.id.tvTaskDate); CircleImageView priority = (CircleImageView) v.findViewById(R.id.cvTaskPriority); return new TaskViewHolder(v, title, date, priority); case TYPE_SEPARATOR: View separator = LayoutInflater.from(parent.getContext()).inflate(R.layout.model_separator, parent, false); TextView type = (TextView) separator.findViewById(R.id.tvSeparatorName); return new SeparatorViewHolder(separator, type); default: return null; } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { final Item item = items.get(position); final Resources resources = holder.itemView.getResources(); if(item.isTask()) { holder.itemView.setEnabled(true); final ModelTask task = (ModelTask) item; final TaskViewHolder taskViewHolder = (TaskViewHolder) holder; //Устанавливаем цвет фона и элемент видимым, так как он имеет тип task final View itemView = taskViewHolder.itemView; itemView.setVisibility(View.VISIBLE); taskViewHolder.priority.setEnabled(true); if(task.getDate() != 0 && task.getDate() < java.util.Calendar.getInstance().getTimeInMillis()) { itemView.setBackgroundColor(resources.getColor(R.color.gray_200)); } else { itemView.setBackgroundColor(resources.getColor(R.color.gray_50)); } //По длительному нажатию удаляем элемент //Диалог вызывается с задержкой для показа анимации перед его вызовом itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { //Для удаления берем позицию из taskViewHolder getTaskFragment().removeTaskDialog(taskViewHolder.getLayoutPosition()); } }, 1000); return true; } }); //Достаем заголовок и дату из модели и кладем во viewHolder //Данные отобразятся в recyclerView taskViewHolder.title.setText(task.getTitle()); taskViewHolder.title.setTextColor(resources.getColor(R.color.primary_text_default_material_light)); //Кладем полную дату (дата + время) if(task.getDate() != 0) { taskViewHolder.date.setText(Utils.getFullDate(task.getDate())); } else { taskViewHolder.date.setText(null); } taskViewHolder.date.setTextColor(resources.getColor(R.color.secondary_text_default_material_light)); //Устанавливаем цвет для отображения CircleImageView //в зависимости от приоритета (из модели) //Устанавливаем сплошную иконку для невыполненой задачи taskViewHolder.priority.setColorFilter(resources.getColor(task.getPriorityColor())); taskViewHolder.priority.setImageResource(R.drawable.ic_circle_white_48dp); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getTaskFragment().showTaskEditDialog(task); } }); taskViewHolder.priority.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { taskViewHolder.priority.setEnabled(false); task.setStatus(ModelTask.STATUS_DONE); //Обновление статуса в БД getTaskFragment().activity.dbHelper.update().updateStatus(task.getTimeStamp(), task.getStatus()); //Установка блеклого цвета при изменении статуса taskViewHolder.title.setTextColor(resources.getColor(R.color.primary_text_disabled_material_light)); taskViewHolder.date.setTextColor(resources.getColor(R.color.secondary_text_disabled_material_light)); taskViewHolder.priority.setColorFilter(resources.getColor(task.getPriorityColor())); ObjectAnimator flipIn = ObjectAnimator.ofFloat(taskViewHolder.priority, "rotationY", -180f, 0f); flipIn.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { //Меняем иконку у проритета на выполненную по завершении анимации if(task.getStatus() == ModelTask.STATUS_DONE) { taskViewHolder.priority.setImageResource(R.drawable.ic_check_circle_white_48dp); ObjectAnimator translationX = ObjectAnimator. ofFloat(itemView, "translationX", 0f, itemView.getWidth()); ObjectAnimator translationXBack = ObjectAnimator .ofFloat(itemView, "translationX", itemView.getWidth(), 0f); translationX.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { itemView.setVisibility(View.GONE); getTaskFragment().moveTask(task); removeItem(taskViewHolder.getLayoutPosition()); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); AnimatorSet translationSet = new AnimatorSet(); translationSet.play(translationX).before(translationXBack); translationSet.start(); } } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); flipIn.start(); } }); } else { ModelSeparator separator = (ModelSeparator) item; SeparatorViewHolder separatorViewHolder = (SeparatorViewHolder) holder; separatorViewHolder.type.setText(resources.getString(separator.getType())); } } }
package com.vmk.solutions.nazgul.pokedex.network.models; import com.google.gson.annotations.SerializedName; public class Games { @SerializedName("game_indices") private int gameIndices; private Version version; public int getGameIndices() { return gameIndices; } public Version getVersion() { return version; } public class Version { private String name; private String url; public String getName() { return name; } public String getUrl() { return url; } } }
/** * @author yuanwq, date: 2017年8月16日 */ package com.xwechat.schedule; import com.xwechat.core.Application; import java.util.Map; /** * @author yuanwq */ public interface AppRepository { public void saveApplication(Application application); public Application getApplication(String appId); public void delete(String appId); public Map<String, Application> all(); }
package offer; import java.util.Arrays; // 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 // 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 // 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 // NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。 public class 旋转数组的最小数字 { public static void main(String[] args) { int[] arr = {3,4,5,1,2}; // System.out.println(minNumberInRotateArray1(arr)); System.out.println(minNumberInRotateArray2(arr)); } public static int minNumberInRotateArray1(int [] array) { if(array.length == 0) return 0; Arrays.sort(array); return array[0]; } public static int minNumberInRotateArray2(int [] array) { if (array.length == 0) return 0; int minVal = Integer.MIN_VALUE; for (int i = 1; i < array.length; i++) { if (array[i] < array[i - 1]) { minVal = array[i]; break; } } return minVal; } }
package com.tkb.elearning.dao; import com.tkb.elearning.model.UserLoginLog; /** * 使用者記錄Dao介面接口 * @author Admin * @version 創建時間:2016-03-15 */ public interface UserLoginLogDao { /** * 記錄登入Log * @param userLoginLog */ public void addUserLoginLog(UserLoginLog userLoginLog); }
/* * Copyright 2013-2014 ReConf Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reconf.server.services.product; import java.util.*; import javax.servlet.http.*; import org.springframework.beans.factory.annotation.*; import org.springframework.http.*; import org.springframework.security.core.*; import org.springframework.transaction.annotation.*; import org.springframework.web.bind.annotation.*; import reconf.server.*; import reconf.server.domain.*; import reconf.server.domain.result.*; import reconf.server.domain.security.*; import reconf.server.repository.*; import reconf.server.services.*; @CrudService public class ReadAllProductsService { @Autowired ProductRepository products; @Autowired UserProductRepository userProducts; @RequestMapping(value="/product", method=RequestMethod.GET) @Transactional(readOnly=true) public ResponseEntity<AllProductsResult> doIt(HttpServletRequest request, Authentication auth) { String baseUrl = CrudServiceUtils.getBaseUrl(request); List<ProductResult> result = new ArrayList<>(); if (ApplicationSecurity.isRoot(auth)) { for (Product product : products.findAll()) { ProductResult productResult = new ProductResult(product, baseUrl); for (UserProduct userProduct : userProducts.findByKeyProduct(product.getName())) { productResult.addUser(userProduct.getKey().getUsername()); result.add(productResult); } } } else { for(UserProduct userProduct : userProducts.findByKeyUsername(auth.getName())) { result.add(new ProductResult(products.findOne(userProduct.getKey().getProduct()), baseUrl)); } } return new ResponseEntity<AllProductsResult>(new AllProductsResult(result, baseUrl), HttpStatus.OK); } }
package com.gildedrose; public class TexttestFixture { public static void main(String[] args) { System.out.println("Wow is a terrible game but this kata is kind of good."); /* * Special Items: * Sulfuras, Hand of Ragnaros * Aged Brie * Backstage passes to a TAFKAL80ETC concert * */ Item[] items = new Item[] { new Item("Shovel", 10, 20) // }; GildedRose app = new GildedRose(items); int days = 10; if (args.length > 0) { days = Integer.parseInt(args[0]) + 1; } for (int i = 0; i < days; i++) { System.out.println("-------- day " + i + " --------"); System.out.println("name, sellIn, quality"); for (Item item : items) { System.out.println(item); } System.out.println(); app.updateQuality(); } } }
package com.ufc.poo.sorveteria.services; import javax.management.BadAttributeValueExpException; import com.ufc.poo.sorveteria.exceptions.NotFoundException; import com.ufc.poo.sorveteria.model.Venda; public interface VendaService { Venda cadastrar(Venda venda) throws NotFoundException, BadAttributeValueExpException; void remover(Integer id) throws NotFoundException; Venda editar(Venda venda) throws NotFoundException, BadAttributeValueExpException; Venda buscar(Integer id); }
import java.util.*; import java.util.Arrays; import java.math.BigInteger; public class Main { static int mod = 1000000007; public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); long[][][] dp = new long[10000][101][2]; dp[1][0][0] = 1; dp[1][0][1] = 1; for (int i = 2; i < dp.length; i++) { for (int j = 0; j < 101; j++) { dp[i][j][0] = (dp[i-1][j][0] + dp[i-1][j][1])%mod; dp[i][j][1] = (dp[i-1][j][0])%mod; if(j-1>=0) dp[i][j][1] += (dp[i-1][j-1][1]%mod); dp[i][j][1] %= mod; } } while(t>0) { int sno = sc.nextInt(); int n = sc.nextInt(); int k = sc.nextInt(); long ans = (dp[n][k][0] + dp[n][k][1])%mod; System.out.println(sno+" "+ans); t--; } } }
package edu.ucam.beans; import edu.ucam.actions.ActionAddCourse; public class Course { private int id; private String course; private String letter; public Course(String course, String letter) { super(); this.course = course; this.letter = letter; id = ActionAddCourse.contador; ActionAddCourse.contador++; } public String getCourse() { return course; } public void setCourse(String course) { this.course = course; } public String getLetter() { return letter; } public int getId() { return id; } public void setLetter(String letter) { this.letter = letter; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.webbeans.web.scanner; import org.apache.webbeans.corespi.scanner.AbstractMetaDataDiscovery; import org.apache.webbeans.corespi.scanner.xbean.OwbAnnotationFinder; import org.apache.webbeans.logger.WebBeansLoggerFacade; import org.apache.webbeans.util.ExceptionUtil; import org.apache.webbeans.util.WebBeansUtil; import jakarta.servlet.ServletContext; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; /** * Configures the web application to find beans. */ public class WebScannerService extends AbstractMetaDataDiscovery { public static final String WEB_INF_BEANS_XML = "/WEB-INF/beans.xml"; private static final Logger logger = WebBeansLoggerFacade.getLogger(WebScannerService.class); protected ServletContext servletContext; public WebScannerService() { } @Override public void init(Object context) { super.init(context); servletContext = (ServletContext) context; } @Override protected void configure() { ClassLoader loader = WebBeansUtil.getCurrentClassLoader(); addWarBeansArchive(); registerBeanArchives(loader); } public OwbAnnotationFinder getFinder() { return finder; } /** * Returns the web application class path if it contains * a beans.xml marker file. * * @return the web application class path * @throws Exception if any exception occurs */ protected void addWarBeansArchive() { if (servletContext == null) { // this may happen if we are running in a test container, in IDE development, etc return; } URL url = null; try { url = servletContext.getResource(WEB_INF_BEANS_XML); } catch (MalformedURLException e) { ExceptionUtil.throwAsRuntimeException(e); } if (url != null) { addWebBeansXmlLocation(url); logger.info("Adding information from WEB-INF/beans.xml"); // the deployment URL already was part of the classpath // so no need to do anything else } } }
package com.kunsoftware.service; import java.util.List; import org.apache.commons.lang3.math.NumberUtils; import org.apache.ibatis.annotations.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import com.kunsoftware.bean.ValueSetRequestBean; import com.kunsoftware.entity.Ground; import com.kunsoftware.entity.ValueSet; import com.kunsoftware.exception.KunSoftwareException; import com.kunsoftware.mapper.AirlineMapper; import com.kunsoftware.mapper.ArticleClassifyMapper; import com.kunsoftware.mapper.DestinationMapper; import com.kunsoftware.mapper.GroundMapper; import com.kunsoftware.mapper.HeadIconTitleMapper; import com.kunsoftware.mapper.ValueSetMapper; import com.kunsoftware.page.PageInfo; import com.kunsoftware.util.FileUtil; @Repository public class ValueSetService { private static Logger logger = LoggerFactory.getLogger(ValueSetService.class); @Autowired private ValueSetMapper valueSetMapper; @Autowired private DestinationMapper destinationMapper; @Autowired private AirlineMapper airlineMapper; @Autowired private GroundMapper groundMapper; @Autowired private HeadIconTitleMapper headIconTitleMapper; @Autowired private ArticleClassifyMapper articleClassifyMapper; public List<ValueSet> getValueSetListAll(@Param("code") String code) { logger.info("query"); return valueSetMapper.getValueSetListAll(code); } public List<ValueSet> getValueSetListPage(@Param("code") String code,@Param("keyword") String keyword,@Param("page") PageInfo page) { logger.info("query"); return valueSetMapper.getValueSetListPage(code,keyword,page); } public List<ValueSet> selectValueSetList(String valueSetCode) { return valueSetMapper.selectValueSetList(valueSetCode); } public List<ValueSet> selectValueSetDestinationList() { return destinationMapper.selectValueSetList(); } public List<ValueSet> selectValueSetAirlineList() { return airlineMapper.selectValueSetList(); } public List<ValueSet> selectValueSetGround() { return groundMapper.selectValueSetList(); } public List<ValueSet> selectValueSetHeadIconTitle(String type) { return headIconTitleMapper.selectValueSetList(type); } public List<ValueSet> selectValueSetArticleClassify() { return articleClassifyMapper.selectValueSetList(); } public String getGroundName(String value) { Ground entity = groundMapper.selectByPrimaryKey(NumberUtils.toInt(value)); if(entity != null) return entity.getName(); return ""; } public ValueSet selectValueSet(String valueSetCode,String valueSetValue) { ValueSet record = new ValueSet(); record.setCode(valueSetCode); record.setValue(valueSetValue); return valueSetMapper.selectValueSet(record); } @Transactional public ValueSet insert(ValueSetRequestBean valueSetRequestBean) throws KunSoftwareException { ValueSet record = new ValueSet(); BeanUtils.copyProperties(valueSetRequestBean, record); valueSetMapper.insert(record); record.setValue(record.getId().toString()); valueSetMapper.updateByPrimaryKeySelective(record); return record; } public ValueSet selectByPrimaryKey(Integer id) { return valueSetMapper.selectByPrimaryKey(id); } @Transactional public int updateByPrimaryKey(ValueSetRequestBean valueSetRequestBean,Integer id) { ValueSet record = valueSetMapper.selectByPrimaryKey(id); BeanUtils.copyProperties(valueSetRequestBean, record); return valueSetMapper.updateByPrimaryKeySelective(record); } @Transactional public int deleteByPrimaryKey(Integer id) { return valueSetMapper.deleteByPrimaryKey(id); } @Transactional public void deleteByPrimaryKey(Integer[] id) throws KunSoftwareException { for(int i = 0;i < id.length;i++) { valueSetMapper.deleteByPrimaryKey(id[i]); } } public String selectValueSetByCode(String code) { ValueSet record = valueSetMapper.selectValueSetByCode(code); if(record != null && record.getValue() != null) { return record.getValue(); } return ""; } @Transactional public void saveGcolor(String color1,String color2,String color3,String color4) { ValueSet record = valueSetMapper.selectValueSetByCode("index_color1"); if(record == null) record = new ValueSet(); record.setValue(color1); record.setCode("index_color1"); saveUpdate(record); record = valueSetMapper.selectValueSetByCode("index_color2"); if(record == null) record = new ValueSet(); record.setValue(color2); record.setCode("index_color2"); saveUpdate(record); record = valueSetMapper.selectValueSetByCode("index_color3"); if(record == null) record = new ValueSet(); record.setValue(color3); record.setCode("index_color3"); saveUpdate(record); record = valueSetMapper.selectValueSetByCode("index_color4"); if(record == null) record = new ValueSet(); record.setValue(color4); record.setCode("index_color4"); saveUpdate(record); } public void saveCustomize(String num,MultipartFile image) throws KunSoftwareException{ ValueSet record = valueSetMapper.selectValueSetByCode("customize_num"); if(record == null) record = new ValueSet(); record.setValue(num); record.setCode("customize_num"); saveUpdate(record); if(image != null) { record = valueSetMapper.selectValueSetByCode("customize_image"); if(record == null) record = new ValueSet(); String imagePath = FileUtil.uploadFile(image); record.setValue(imagePath); record.setCode("customize_image"); saveUpdate(record); } } public void saveHidePrice(String hidePrice) throws KunSoftwareException{ ValueSet record = valueSetMapper.selectValueSetByCode("hide_price"); if(record == null) record = new ValueSet(); record.setValue(hidePrice); record.setCode("hide_price"); saveUpdate(record); } public void saveGiftad(String num,MultipartFile image) throws KunSoftwareException{ ValueSet record = valueSetMapper.selectValueSetByCode("giftad_link"); if(record == null) record = new ValueSet(); record.setValue(num); record.setCode("giftad_link"); saveUpdate(record); if(image != null) { record = valueSetMapper.selectValueSetByCode("giftad_image"); if(record == null) record = new ValueSet(); String imagePath = FileUtil.uploadFile(image); record.setValue(imagePath); record.setCode("giftad_image"); saveUpdate(record); } } public void saveUpdate(ValueSet record) { if(record.getId() == null) { valueSetMapper.insert(record); } else { valueSetMapper.updateByPrimaryKey(record); } } }
package com.maweiming.wechat.bot.service.message; import com.maweiming.wechat.bot.service.message.core.BaseMessage; import com.maweiming.wechat.bot.service.message.core.IMessage; import com.maweiming.wechat.bot.utils.DingMessageUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * maweiming.com * Copyright (C) 1994-2018 All Rights Reserved. * 系统消息 * @author CoderMa * @version SystemMessage.java, v 0.1 2018-11-07 00:42 */ @Service public class SystemMessage extends BaseMessage implements IMessage { private static final Logger LOGGER = LoggerFactory.getLogger(SystemMessage.class); @Autowired private DingMessageUtils dingMessageUtils; @Override public void showMessage() { String content = message.getContent(); switch (content){ case "收到红包,请在手机上查看": LOGGER.info(content); dingMessageUtils.sendMessage(content); break; default: LOGGER.info(content); break; } } }
package com.hotmail.at.jablonski.michal.shoppinglist.db.entities; public class ChildEntity { private Integer id; private Integer rootId; private String name; private boolean isBought; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getRootId() { return rootId; } public void setRootId(Integer rootId) { this.rootId = rootId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isBought() { return isBought; } public void setBought(boolean bought) { isBought = bought; } }
package com.tencent.mm.wallet_core.e.a; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.wallet_core.c.o; import java.util.HashMap; import org.json.JSONObject; public final class b extends a { public b() { F(new HashMap()); } public final int bOo() { return 28; } public final void a(int i, String str, JSONObject jSONObject) { x.d("Micromsg.NetScenePayUTimeSeed", " errCode: " + i + " errMsg :" + str); String optString = jSONObject.optString("time_stamp"); if (!bi.oW(optString)) { o.setTimeStamp(optString); } } }
package com.jean.sbc.services.validation; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.HandlerMapping; import com.jean.sbc.domain.Customer; import com.jean.sbc.dto.CustomerDTO; import com.jean.sbc.repositories.CustomerRepository; import com.jean.sbc.resources.exception.FieldMessage; public class CustomerUpdateValidator implements ConstraintValidator<CustomerUpdate, CustomerDTO> { @Autowired private HttpServletRequest request; @Autowired private CustomerRepository customerRepository; @Override public void initialize(CustomerUpdate ann) { } @Override public boolean isValid(CustomerDTO customerDTO, ConstraintValidatorContext context) { Map<String, String> map = (Map<String, String>) request .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); Integer uriId = Integer.parseInt(map.get("id")); List<FieldMessage> list = new ArrayList<>(); Customer customer = customerRepository.findByEmail(customerDTO.getEmail()); if (customer != null && !customer.getId().equals(uriId)) { list.add(new FieldMessage("email", "Email already exists")); } for (FieldMessage e : list) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(e.getMessage()).addPropertyNode(e.getFieldName()) .addConstraintViolation(); } return list.isEmpty(); } }
package com.tencent.b.a.a; import org.json.JSONException; import org.json.JSONObject; final class g { String bjM = null; String bvw = null; String bvx = "0"; long bvy = 0; g() { } static g ch(String str) { g gVar = new g(); if (s.ci(str)) { try { JSONObject jSONObject = new JSONObject(str); if (!jSONObject.isNull("ui")) { gVar.bjM = jSONObject.getString("ui"); } if (!jSONObject.isNull("mc")) { gVar.bvw = jSONObject.getString("mc"); } if (!jSONObject.isNull("mid")) { gVar.bvx = jSONObject.getString("mid"); } if (!jSONObject.isNull("ts")) { gVar.bvy = jSONObject.getLong("ts"); } } catch (JSONException e) { } } return gVar; } final int a(g gVar) { if (gVar == null) { return 1; } if (s.cj(this.bvx) && s.cj(gVar.bvx)) { if (this.bvx.equals(gVar.bvx)) { return 0; } if (this.bvy < gVar.bvy) { return -1; } return 1; } else if (s.cj(this.bvx)) { return 1; } else { return -1; } } public final String toString() { return tN().toString(); } private JSONObject tN() { JSONObject jSONObject = new JSONObject(); try { s.a(jSONObject, "ui", this.bjM); s.a(jSONObject, "mc", this.bvw); s.a(jSONObject, "mid", this.bvx); jSONObject.put("ts", this.bvy); } catch (JSONException e) { } return jSONObject; } }
package com.worker.framework.messagehandlingchain; import java.util.List; import com.google.common.base.Objects; import com.worker.shared.WorkMessage; import com.worker.shared.WorkMessagesJoinState; public class VerifyChildrenInheritJoinState implements WMProcessor { private final WMProcessor delegator; public VerifyChildrenInheritJoinState(WMProcessor delegator) { this.delegator = delegator; } @Override public List<WorkMessage> handle(WorkMessage input) throws Exception { List<WorkMessage> triggeredTasks = delegator.handle(input); WorkMessagesJoinState joinState = input.getJoinState(); if (joinState != null) { for (WorkMessage task : triggeredTasks) { if (task.getJoinState() == null) { task.setJoinState(joinState); } else if (!Objects.equal(joinState.getJoinId(), task.getJoinState().getJoinId())) { throw new IllegalStateException("triggered task " + task + " changed join id from " + joinState.getJoinId() + " to " + task.getJoinState().getJoinId()); } else if (!Objects.equal(joinState.getSinkMessage().getTask(), task.getJoinState().getSinkMessage().getTask())){ throw new IllegalStateException("triggered task " + task + " changed sink task from " + joinState.getSinkMessage().getTask() + " to " + task.getJoinState().getSinkMessage().getTask()); } } } return triggeredTasks; } }
package com.smxknife.graphql.ex2.service; import com.smxknife.graphql.ex2.domain.User; import org.springframework.stereotype.Service; @Service public class UserService { public User findById(int id) { User user = new User(); user.setId(id); user.setAccount("admin"); user.setPassword("123456"); return user; } }
package pe.com.tss.bean; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import org.eclipse.persistence.annotations.ReturnInsert; @Entity @Table(name="GENERAL_TABLE") @NamedQueries({ @NamedQuery(name = "GeneralTable.existGeneralTable", query = "SELECT COUNT(g.generaltableid) FROM GeneralTable g WHERE g.value=:value"), @NamedQuery(name = "GeneralTable.getAll", query = "SELECT g FROM GeneralTable g"), @NamedQuery(name = "GeneralTable.getGeneralTable", query = "SELECT g FROM GeneralTable g WHERE g.code=:code") }) public class GeneralTable implements Serializable{ /** * */ private static final long serialVersionUID = 1094420543319274738L; @Id @Column(name = "GENERAL_TABLE_ID") @ReturnInsert(returnOnly=true) private long generaltableid; @Column(name = "TABLE_NAME") private String tablename; @Column(name = "STATUS") private String status; @Column(name = "CODE") private String code; @Column(name = "VALUE") private String value; @Column(name = "SORT_ORDER") private int sortorder; public long getGeneraltableid() { return generaltableid; } public void setGeneraltableid(long generaltableid) { this.generaltableid = generaltableid; } public String getTablename() { return tablename; } public void setTablename(String tablename) { this.tablename = tablename; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public int getSortorder() { return sortorder; } public void setSortorder(int sortorder) { this.sortorder = sortorder; } }
package mapper; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; public interface BasicMapper<T> { /** * * @param x * @param <T> * @return */ T getById(String x); /** * 有分页的限制不需要担心 * @param x * @param <T> * @return */ List<T> getAll(); /** * * @param x * @param <T> */ void insert(T x); /** * * @param x */ void updateById(T x); /** * * @param Id */ void softDeleteById(String Id); /** * * @param id */ void forceDeleteById(String id); /** * Dangerous ! */ void createTable(); /** * Dangerous ! */ void dropTable(); }
package com.rastiehaiev.notebook.response; import java.util.Map; /** * @author Roman Rastiehaiev * Created on 04.10.15. */ public abstract class BaseResponse implements IResponse { protected String errorMessage; protected Map<String, String> errorsMap; @Override public String getErrorMessage() { return errorMessage; } @Override public Map<String, String> getErrorsMap() { return errorsMap; } @Override public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } @Override public void setErrorsMap(Map<String, String> errorsMap) { this.errorsMap = errorsMap; } }
package com.tencent.mars.smc; import com.tencent.mm.protocal.a.a.a; import com.tencent.mm.protocal.a.a.b; import com.tencent.mm.protocal.a.a.c; import com.tencent.mm.protocal.a.a.d; import com.tencent.mm.protocal.a.a.e; import com.tencent.mm.protocal.a.a.f; import com.tencent.mm.protocal.a.a.g; import com.tencent.mm.protocal.a.a.h; import com.tencent.mm.protocal.a.a.i; import com.tencent.mm.protocal.a.a.j; import com.tencent.mm.protocal.a.a.k; import com.tencent.mm.protocal.a.a.l; import com.tencent.mm.protocal.a.a.m; import com.tencent.mm.protocal.a.a.n; import com.tencent.mm.protocal.a.a.o; import com.tencent.mm.protocal.c.ace; import com.tencent.mm.protocal.c.acf; import com.tencent.mm.protocal.c.ank; import com.tencent.mm.protocal.c.anl; import com.tencent.mm.protocal.c.apv; import com.tencent.mm.protocal.c.awc; import com.tencent.mm.protocal.c.brg; import com.tencent.mm.protocal.c.pa; import com.tencent.mm.protocal.c.pb; import com.tencent.mm.protocal.c.pc; import java.util.ArrayList; import java.util.LinkedList; public class SmcProtoBufUtil { public static pb toMMReportKvReq(i iVar) { pb pbVar = new pb(); pbVar.rti = iVar.qXj; pbVar.rtj = iVar.qXz; pbVar.rtk = iVar.qXx; for (int i = 0; i < iVar.qXA.size(); i++) { e eVar = (e) iVar.qXA.get(i); pa paVar = new pa(); paVar.iwE = eVar.uin; paVar.rgt = eVar.qXh; paVar.rth = eVar.nettype; paVar.rjN = eVar.qXt; paVar.rjL = eVar.qXr; paVar.rjM = eVar.qXs; paVar.rjO = eVar.qXu; paVar.rjP = eVar.qXv; paVar.hcJ = eVar.qXw; for (int i2 = 0; i2 < eVar.qXi.size(); i2++) { d dVar = (d) eVar.qXi.get(i2); apv apv = new apv(); apv.rSt = dVar.qXg; apv.rSu = dVar.qXp; apv.rSv = dVar.qXq; apv.rvJ = dVar.mXw; apv.hbF = dVar.count; paVar.jQF.add(apv); } pbVar.rtl.add(paVar); } return pbVar; } public static pb toMMReportIdkeyReq(g gVar) { pb pbVar = new pb(); pbVar.rti = gVar.qXj; pbVar.rtj = gVar.qXz; pbVar.rtk = 0; for (int i = 0; i < gVar.qXA.size(); i++) { b bVar = (b) gVar.qXA.get(i); pa paVar = new pa(); paVar.iwE = bVar.uin; paVar.rgt = bVar.qXh; paVar.rth = bVar.nettype; for (int i2 = 0; i2 < bVar.qXi.size(); i2++) { a aVar = (a) bVar.qXi.get(i2); apv apv = new apv(); apv.rSt = aVar.qXg; apv.rvJ = 0; apv.rSv = 0; apv.hbF = aVar.count; apv.rSu = com.tencent.mm.bk.b.bi(Integer.toString(aVar.value).getBytes()); paVar.jQF.add(apv); } pbVar.rtl.add(paVar); } return pbVar; } private static o fillStrategyTable(LinkedList<brg> linkedList) { o oVar = new o(); for (int i = 0; i < linkedList.size(); i++) { brg brg = (brg) linkedList.get(i); m mVar = new m(); mVar.qXM = brg.spu; mVar.qXN = brg.spv; for (int i2 = 0; i2 < brg.spw.size(); i2++) { awc awc = (awc) brg.spw.get(i2); n nVar = new n(); nVar.qXg = awc.rSt; nVar.qXP = awc.rZr; nVar.qXQ = awc.rZp; nVar.qXR = awc.rZq; nVar.qXS = awc.rZs; nVar.qXT = awc.rZt; nVar.qXU = awc.rZu; mVar.qXO.add(nVar); } oVar.qXV.add(mVar); } return oVar; } public static j toSmcReportKvResp(pc pcVar) { j jVar = new j(); jVar.ret = pcVar.rfn; jVar.qXj = pcVar.rto; jVar.qXk = pcVar.rtp; jVar.qXx = pcVar.rtq; jVar.qXn = pcVar.rtu; jVar.qXC = pcVar.rtv; jVar.qXo = pcVar.rtw; jVar.qXl = fillStrategyTable(pcVar.rtr); jVar.qXm = fillStrategyTable(pcVar.rts); jVar.qXy = fillStrategyTable(pcVar.rtt); return jVar; } public static h toSmcReportIdkeyResp(pc pcVar) { h hVar = new h(); hVar.ret = pcVar.rfn; hVar.qXj = pcVar.rto; hVar.qXk = pcVar.rtp; hVar.qXn = pcVar.rtu; hVar.qXC = pcVar.rtv; hVar.qXo = pcVar.rtw; hVar.qXl = fillStrategyTable(pcVar.rtr); hVar.qXm = fillStrategyTable(pcVar.rts); return hVar; } public static ace toMMGetStrategyReq() { ace ace = new ace(); ArrayList strategyVersions = SmcLogic.getStrategyVersions(); if (strategyVersions.size() != 6) { return null; } ace.rti = ((Integer) strategyVersions.get(0)).intValue(); ace.rtj = ((Integer) strategyVersions.get(1)).intValue(); ace.rtk = ((Integer) strategyVersions.get(2)).intValue(); ace.rGN = ((Integer) strategyVersions.get(3)).intValue(); ace.rGO = ((Integer) strategyVersions.get(4)).intValue(); ace.rGP = ((Integer) strategyVersions.get(5)).intValue(); return ace; } public static f toSmcKVStrategyResp(acf acf) { f fVar = new f(); fVar.ret = acf.rfn; fVar.qXj = acf.rGN; fVar.qXk = acf.rGO; fVar.qXx = acf.rGP; fVar.qXn = acf.rtu; fVar.qXo = acf.rtw; fVar.qXl = fillStrategyTable(acf.rGQ); fVar.qXm = fillStrategyTable(acf.rGR); fVar.qXy = fillStrategyTable(acf.rGS); return fVar; } public static c toSmcIdkeyStrategyResp(acf acf) { c cVar = new c(); cVar.ret = acf.rfn; cVar.qXj = acf.rto; cVar.qXk = acf.rtp; cVar.qXn = acf.rtu; cVar.qXo = acf.rtw; cVar.qXl = fillStrategyTable(acf.rtr); cVar.qXm = fillStrategyTable(acf.rts); return cVar; } public static ank toMMSelfMonitor(k kVar) { ank ank = new ank(); ank.rPZ = kVar.qXD; int i = 0; while (true) { int i2 = i; if (i2 >= kVar.qXE.size()) { return ank; } anl anl = new anl(); l lVar = (l) kVar.qXE.get(i2); anl.rQa = lVar.qXF; anl.bHC = lVar.action; anl.rQb = lVar.qXG; anl.rQc = lVar.qXH; anl.rQd = lVar.qXI; anl.rQe = lVar.qXJ; anl.rQf = lVar.qXK; anl.rQg = lVar.qXL; ank.jQF.add(anl); i = i2 + 1; } } }
package com.jim.multipos.ui.admin_main_page; import com.jim.multipos.core.BasePresenterImpl; import com.jim.multipos.utils.RxBus; import javax.inject.Inject; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; public class AdminMainPagePresenterImpl extends BasePresenterImpl<AdminMainPageView> implements AdminMainPagePresenter { AdminMainPageView view; CompositeDisposable disposable = new CompositeDisposable(); @Inject protected AdminMainPagePresenterImpl(AdminMainPageView adminMainPageView) { super(adminMainPageView); view = adminMainPageView; } }
package com.example.demo.Service; import com.example.demo.Model.Kommune; import com.example.demo.Model.Sogne; import com.example.demo.Model.SogneDTO; import com.example.demo.Repository.KommuneRepository; import com.example.demo.Repository.SogneRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.Iterator; import java.util.Optional; import java.util.Set; @Service public class KommuneService { @Autowired KommuneRepository kommuneRepository; @Autowired SogneRepository sogneRepository; public Kommune create(Kommune kommune){ Optional<Sogne> sogne = sogneRepository.findById(kommune.getKommunekode()); return kommuneRepository.save(new Kommune(kommune.getKommunekode(), sogne.toString())); } public Set<Kommune> findAll(){ Set<Kommune> kommuneSet = new HashSet<>(); for(Kommune kommune: kommuneRepository.findAll()){ kommuneSet.add(kommune); } return kommuneSet; } public Kommune findById(long id){ Optional<Kommune> kommuneOptional = kommuneRepository.findById(id); if (!kommuneOptional.isPresent()){ throw new RuntimeException("Kommune: " + id + " blev ikke fundet"); } else { return kommuneOptional.get(); } } public Kommune update(SogneDTO sogneDTO) throws Exception { Iterator<Kommune> iterator = kommuneRepository.findAll().iterator(); while (iterator.hasNext()) { Kommune kommune = iterator.next(); if(sogneDTO.getKommunekode() == kommune.getKommunekode()){ return kommuneRepository.save(kommune); } } throw new Exception("Kan ikke updatere"); } public ResponseEntity<String> delete (long id){ Optional<Kommune> optionalKommune = kommuneRepository.findById(id); if (optionalKommune.isEmpty()){ //Så findes id ikke return ResponseEntity.status(HttpStatus.NOT_FOUND).body("{ 'msg' : id " + id + " not found'}"); } //Ellers sletter jeg den her kommuneRepository.deleteById(id); return ResponseEntity.status(HttpStatus.OK).body("{ 'msg' : 'deleted'}"); } }
package topKfrequencywords; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.PriorityQueue; public class Solution { public String[] topKFrequent(String[] combo, int k) { // Write your solution here. if(combo.length == 0){ return new String[0]; } Map<String, Integer> freqmap = getfreq(combo); PriorityQueue<Map.Entry<String,Integer>> minheap = new PriorityQueue<>(k,new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> a,Map.Entry<String, Integer> b){ return a.getValue().compareTo(b.getValue()); } }); for(Map.Entry<String, Integer> Entry : freqmap.entrySet()){ if(minheap.size() < k){ minheap.offer(Entry); } else if(Entry.getValue() > minheap.peek().getValue()){ minheap.poll(); minheap.offer(Entry); } } return output(minheap); } private Map<String, Integer> getfreq(String[] input){ Map<String, Integer> map = new HashMap<>(); for(String s : input){ if(map.get(s) == null){ map.put(s, 1); } else{ map.put(s, map.get(s)+1); } } return map; } private String[] output(PriorityQueue<Map.Entry<String,Integer>> minheap){ String [] result = new String [minheap.size()]; for(int i = minheap.size() - 1; i >= 0; i--){ result[i] = minheap.poll().getKey(); } return result; } public static void main (String [] args){ Solution s = new Solution(); String [] input = {"a","a","b","c","d","d","d"}; System.out.println(Arrays.toString(s.topKFrequent(input, 2))); } }
package pwr.chrzescijanek.filip.gifa.core.function.hsv.fuzziness.linear; import org.opencv.core.Mat; import pwr.chrzescijanek.filip.gifa.core.function.EvaluationFunction; import static org.opencv.imgproc.Imgproc.COLOR_BGR2HSV_FULL; import static pwr.chrzescijanek.filip.gifa.core.util.FunctionUtils.calculateLinearFuzzinesses; import static pwr.chrzescijanek.filip.gifa.core.util.ImageUtils.convertType; /** * Provides method to calculate saturation linear fuzziness. */ public final class LinearFuzzinessSaturation implements EvaluationFunction { /** * Default constructor. */ public LinearFuzzinessSaturation() {} @Override public double[] evaluate(final Mat[] images) { convertType(images, COLOR_BGR2HSV_FULL); return calculateLinearFuzzinesses(images, 1); } }
/** * what is Armstrong number? * 153----->(1*1* + 5*5*5 + 3*3*3 =153 * */ /** * @author Madan * */ package armstrongNumber;
package com.mygdx.factory; import java.util.Iterator; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.ObjectMap.Values; import com.mygdx.ObjectInfo.MonsterInfo; public class MonsterInfoFactory { private static ObjectMap<String,MonsterInfo> monsterInfoMap = new ObjectMap<String,MonsterInfo>() ; public MonsterInfoFactory(){} @SuppressWarnings({ "unchecked" }) public static void instantiate(){ Json json = new Json(); json.addClassTag("MonsterInfo", MonsterInfo.class); monsterInfoMap = json.fromJson(ObjectMap.class,Gdx.files.internal("json/MonsterInfo.json")); } public static MonsterInfo getMonsterInfo(String monsterName){ return monsterInfoMap.get(monsterName); } public static Array<MonsterInfo> getMonsterInfoArray(){ Array<MonsterInfo> monsterInfoArray = new Array<MonsterInfo>(); for (Values<MonsterInfo> iterator = monsterInfoMap.values(); iterator.hasNext();) { MonsterInfo mI = (MonsterInfo) iterator.next(); monsterInfoArray.add(mI); } return monsterInfoArray; } }
package com.zking.ssm.mapper; import com.zking.ssm.model.NewsC; public interface NewsCMapper { int deleteByPrimaryKey(Integer id); int insert(NewsC record); int insertSelective(NewsC record); NewsC selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(NewsC record); int updateByPrimaryKey(NewsC record); }
package springboot_demo.springcloud.controller; import java.io.File; import org.springframework.beans.factory.annotation.Value; 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 springboot_demo.springcloud.handler.DocHelpUtils; @RestController public class FristController { @Value("${server.port}") String port; @RequestMapping("/hi") public String home(@RequestParam String name) { return "hi "+name+",i am from port:" +port; } @RequestMapping("/doc") public String getDoc(@RequestParam(value = "file") MultipartFile mfile) throws Exception{ File file = DocHelpUtils.mutifile2File(mfile); String name = file.getName().substring(0, file.getName().lastIndexOf(".")); String filePath = file.getPath().replaceAll(file.getName(), ""); System.out.println(file.getName()); if (file.getName().endsWith(".docx") || file.getName().endsWith(".DOCX")) { DocHelpUtils.docx(filePath ,file.getName(),name +".htm"); }else{ DocHelpUtils.dox(filePath ,file.getName(),name +".htm"); } DocHelpUtils.deleteFile(file); return "success"; } }
package ua.addicted.assetwand.models; import android.graphics.Bitmap; import java.util.Date; /** * Created by addicted on 12.03.16. */ public class Receipt { private int id; private User user; private Bitmap image; private String imageSrc; private ReceiptEntry[] entries; private Double totalAmount; private String location; private Date date; private Date createdOn; public Receipt() { } public Receipt(Bitmap image) { this.image = image; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Bitmap getImage() { return image; } public void setImage(Bitmap image) { this.image = image; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getImageSrc() { return imageSrc; } public void setImageSrc(String imageSrc) { this.imageSrc = imageSrc; } public ReceiptEntry[] getEntries() { return entries; } public void setEntries(ReceiptEntry[] entries) { this.entries = entries; } public Double getTotalAmount() { return totalAmount; } public void setTotalAmount(Double totalAmount) { this.totalAmount = totalAmount; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Date getCreatedOn() { return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Receipt receipt = (Receipt) o; if (user != null ? !user.equals(receipt.user) : receipt.user != null) return false; if (imageSrc != null ? !imageSrc.equals(receipt.imageSrc) : receipt.imageSrc != null) return false; if (date != null ? !date.equals(receipt.date) : receipt.date != null) return false; if (createdOn != null ? !createdOn.equals(receipt.createdOn) : receipt.createdOn != null) return false; return true; } @Override public int hashCode() { int result = user != null ? user.hashCode() : 0; result = 31 * result + (imageSrc != null ? imageSrc.hashCode() : 0); result = 31 * result + (date != null ? date.hashCode() : 0); result = 31 * result + (createdOn != null ? createdOn.hashCode() : 0); return result; } }
package com.tencent.mm.plugin.appbrand.ui; import android.app.Dialog; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.ViewGroup.MarginLayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import com.tencent.mm.plugin.appbrand.app.e; import com.tencent.mm.plugin.appbrand.report.a.o; import com.tencent.mm.plugin.appbrand.s; import com.tencent.mm.plugin.appbrand.s.j; import com.tencent.mm.plugin.appbrand.s.k; import com.tencent.mm.plugin.appbrand.ui.banner.AppBrandStickyBannerLogic.b; import com.tencent.mm.plugin.appbrand.ui.banner.f; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.ak; import com.tencent.mm.ui.base.a; import com.tencent.mm.ui.widget.a.c; @a(7) public final class AppBrandGuideUI extends MMActivity implements f { protected final int getLayoutId() { return -1; } public final void onCreate(Bundle bundle) { setTheme(k.MMTheme_NoTitleTranslucent); super.onCreate(bundle); ak.a(getWindow()); a aaY = e.aaY(); if (aaY == null) { super.finish(); return; } b.d(this); c.a aVar = new c.a(this); aVar.Gq(j.app_brand_entrance); View imageView = new ImageView(this); imageView.setImageResource(s.f.app_brand_guide_image); View textView = new TextView(this); textView.setText(j.app_brand_guide_message); textView.setTextSize(2, 14.0f); textView.setTextColor(Color.argb(Math.round(137.70001f), 0, 0, 0)); textView.setLineSpacing(0.0f, 1.2f); View linearLayout = new LinearLayout(this); linearLayout.setOrientation(1); linearLayout.addView(imageView, new LayoutParams(-1, -2)); linearLayout.addView(textView, new LayoutParams(-1, -2)); ((MarginLayoutParams) textView.getLayoutParams()).topMargin = com.tencent.mm.bp.a.fromDPToPix(this, 16); aVar.dR(linearLayout); aVar.a(new 1(this)); aVar.Gu(j.close_btn); aVar.b(new 2(this)); aVar.Gt(j.app_brand_guide_confirm_view_list); aVar.a(false, new 3(this)); aVar.mF(false); aVar.mG(true); Dialog anj = aVar.anj(); anj.setOnKeyListener(new 4(this)); anj.show(); o.a(o.a.gsw, aaY.gux); aaY.guw = false; aaY.gux = null; } protected final void onDestroy() { super.onDestroy(); b.c(this); } public final void an(String str, int i) { finish(); } }
/* * YNAB API Endpoints * Our API uses a REST based design, leverages the JSON data format, and relies upon HTTPS for transport. We respond with meaningful HTTP response codes and if an error occurs, we include error details in the response body. API Documentation is at https://api.youneedabudget.com * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ynab.client.api; import ynab.client.invoker.ApiException; import ynab.client.model.ErrorResponse; import ynab.client.model.UserResponse; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for UserApi */ @Ignore public class UserApiTest { private final UserApi api = new UserApi(); /** * User info * * Returns authenticated user information. * * @throws ApiException * if the Api call fails */ @Test public void getUserTest() throws ApiException { UserResponse response = api.getUser(); // TODO: test validations } }
package com.atTrip.vo; public class CityVo { private int city_no; private String city_name_kor; private String city_name_eng; private String city_topinfo; private String city_info; private String city_gooddate; private String city_gooddate_number; private String city_visa; private String city_volt; private String city_flytime; private String city_image1; private String city_image2; private String city_image3; private String city_image4; private String city_location_X; private String city_location_Y; private String city_style; private String city_weather; private int city_hit; private int city_liketot; private int country_no; public CityVo() { super(); } public CityVo(int city_no, String city_name_kor, String city_name_eng, String city_topinfo, String city_info, String city_gooddate, String city_gooddate_number, String city_visa, String city_volt, String city_flytime, String city_image1, String city_image2, String city_image3, String city_image4, String city_location_X, String city_location_Y, String city_style, String city_weather, int city_hit, int city_liketot, int country_no) { super(); this.city_no = city_no; this.city_name_kor = city_name_kor; this.city_name_eng = city_name_eng; this.city_topinfo = city_topinfo; this.city_info = city_info; this.city_gooddate = city_gooddate; this.city_gooddate_number = city_gooddate_number; this.city_visa = city_visa; this.city_volt = city_volt; this.city_flytime = city_flytime; this.city_image1 = city_image1; this.city_image2 = city_image2; this.city_image3 = city_image3; this.city_image4 = city_image4; this.city_location_X = city_location_X; this.city_location_Y = city_location_Y; this.city_style = city_style; this.city_weather = city_weather; this.city_hit = city_hit; this.city_liketot = city_liketot; this.country_no = country_no; } public String getCity_gooddate_number() { return city_gooddate_number; } public void setCity_gooddate_number(String city_gooddate_number) { this.city_gooddate_number = city_gooddate_number; } public String getCity_name_kor() { return city_name_kor; } public void setCity_name_kor(String city_name_kor) { this.city_name_kor = city_name_kor; } public String getCity_name_eng() { return city_name_eng; } public void setCity_name_eng(String city_name_eng) { this.city_name_eng = city_name_eng; } public int getCity_no() { return city_no; } public void setCity_no(int city_no) { this.city_no = city_no; } public String getCity_topinfo() { return city_topinfo; } public void setCity_topinfo(String city_topinfo) { this.city_topinfo = city_topinfo; } public String getCity_info() { return city_info; } public void setCity_info(String city_info) { this.city_info = city_info; } public String getCity_gooddate() { return city_gooddate; } public void setCity_gooddate(String city_gooddate) { this.city_gooddate = city_gooddate; } public String getCity_visa() { return city_visa; } public void setCity_visa(String city_visa) { this.city_visa = city_visa; } public String getCity_volt() { return city_volt; } public void setCity_volt(String city_volt) { this.city_volt = city_volt; } public String getCity_flytime() { return city_flytime; } public void setCity_flytime(String city_flytime) { this.city_flytime = city_flytime; } public String getCity_image1() { return city_image1; } public void setCity_image1(String city_image1) { this.city_image1 = city_image1; } public String getCity_image2() { return city_image2; } public void setCity_image2(String city_image2) { this.city_image2 = city_image2; } public String getCity_image3() { return city_image3; } public void setCity_image3(String city_image3) { this.city_image3 = city_image3; } public String getCity_image4() { return city_image4; } public void setCity_image4(String city_image4) { this.city_image4 = city_image4; } public String getCity_location_X() { return city_location_X; } public void setCity_location_X(String city_location_X) { this.city_location_X = city_location_X; } public String getCity_location_Y() { return city_location_Y; } public void setCity_location_Y(String city_location_Y) { this.city_location_Y = city_location_Y; } public String getCity_style() { return city_style; } public void setCity_style(String city_style) { this.city_style = city_style; } public String getCity_weather() { return city_weather; } public void setCity_weather(String city_weather) { this.city_weather = city_weather; } public int getCity_hit() { return city_hit; } public void setCity_hit(int city_hit) { this.city_hit = city_hit; } public int getCity_liketot() { return city_liketot; } public void setCity_liketot(int city_liketot) { this.city_liketot = city_liketot; } public int getCountry_no() { return country_no; } public void setCountry_no(int country_no) { this.country_no = country_no; } }
package com.dsc.dw.internal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class DateMagic { public static String MonthDiffa(int year, String month, int offset) { String date2 = year +"-"+month; SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd"); SimpleDateFormat sdfm = new SimpleDateFormat("MMMM-yyyy"); SimpleDateFormat sdfmm = new SimpleDateFormat("M"); Calendar calendar = new GregorianCalendar(year,0,28); //System.out.println("Date : " + sdf.format(calendar.getTime())); // set date using month and year format try{ calendar.setTime(sdfm.parse(date2));} catch(Exception ee){ System.out.println("");} //add one month calendar.add(Calendar.MONTH, 3); System.out.println("Date plus month 3 : " + sdf.format(calendar.getTime())); //subtract 10 days calendar.add(Calendar.DAY_OF_MONTH, -10); System.out.println("Date day -10: " + sdfm.format(calendar.getTime())); // Get Month Number System.out.println("MonthNumber: " + sdfmm.format(calendar.getTime())); return date2; } public static String MonthDiff(int year, String month, int offset) { String date2 = month +"-"+Integer.toString(year); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd"); SimpleDateFormat sdfm = new SimpleDateFormat("MMMM-yyyy"); Calendar calendar = new GregorianCalendar(year,0,28); // set date using month and year format try{ calendar.setTime(sdfm.parse(date2));} catch(Exception ee){ return "";} //add one month calendar.add(Calendar.MONTH, offset); System.out.println("Date plus month 3 : " + sdf.format(calendar.getTime())); return sdf.format(calendar.getTime()); } public String MonthRange(int year, String month, int offset) { // Month has to be in Alpha ex: June String date2 = month +"-"+Integer.toString(year); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd"); SimpleDateFormat sdfn = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat mmmyyyy = new SimpleDateFormat("MMMM-yyyy"); SimpleDateFormat sdfm = new SimpleDateFormat("MMMM-yyyy"); Calendar calendar = new GregorianCalendar(year,0,28); Calendar calendar2 = new GregorianCalendar(year,0,28); // set date using month and year format try{ calendar.setTime(sdfm.parse(date2)); calendar2.setTime(sdfm.parse(date2)); } catch(Exception ee){ } //add one month System.out.println("Date Starting : " + sdfn.format(calendar.getTime())); calendar2.add(Calendar.MONTH,+1); calendar.add(Calendar.MONTH, offset); calendar2.add(Calendar.DAY_OF_MONTH,-1); //System.out.println("Date Offset : " + sdfn.format(calendar.getTime())); //System.out.println("Last Day of Month : " + sdfn.format(calendar2.getTime())); // System.out.println("Long Month Year:" + mmmyyyy.format(calendar.getTime())); String range="'"+sdfn.format(calendar.getTime()) +"' and '" +sdfn.format(calendar2.getTime()) +"'"; return range; } }
public class Searching { public static void search(int[] args, int start, int end, int searchnum) { int center = (start + end) / 2; if (args[center] == searchnum) System.out.println(searchnum + "은 배열에 존재합니다."); else if (args[center] > searchnum){ //찾는 수가 중심값보다 작을 때 if (center > end) System.out.println(searchnum + "은 배열에 존재하지 않습니다."); else search(args, start, center - 1, searchnum); } else if (args[center] < searchnum){ //찾는 수가 중심값보다 클 떄 if (center < start) System.out.println(searchnum + "은 배열에 존재하지 않습니다."); else search(args, center + 1, end, searchnum); } } }
package java8; import org.junit.jupiter.api.Test; import java.io.FileNotFoundException; import java.io.IOException; import java.time.*; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class java8ceritification { @Test public void testForLoop() { for (int i = 0; i < 5; i++, System.out.println(i + "HI")) ; //output:: weCanDeclareForLoopLikeThisAsWell } @Test //todo public void testForLoop1() { L1: for (int i = 5, j = 0; i > 0; i--) { L2: for (; j < 5; j++) { System.out.println(i + "" + j + " "); if (j == 0) continue L2; } } } @Test public void testForLoopIteratingTwoways() { //two-dimensional arrays: int arr[][] = {{1, 3, 5}, {7, 8}}; for (int j = 0; j < arr.length; j++) { int[] a = arr[j]; for (int k = 0; k < a.length; k++) { int i = a[k]; System.out.println(i); } } //three-dimensional arrays: int[][][] arr1 = {{{1, 3, 5}, {7, 8}, {4, 5, 6}}}; for (int j = 0; j < arr1.length; j++) { int[][] a = arr1[j]; for (int k = 0; k < a.length; k++) { int i[] = a[k]; for (int l = 0; l < i.length; l++) { int m = i[l]; System.out.println(m); } } } } @Test public void testLocalDate() { LocalDate date = LocalDate.parse("1947-08-14"); LocalTime time = LocalTime.MAX; System.out.println(date.atTime(time)); } @Test public void invalidDateInTheCalendar() { LocalDate date = LocalDate.of(2020, 9, 30); System.out.println(date); } @Test public void testLocalDate1() { LocalDateTime localDate = LocalDateTime.now(); System.out.println(localDate); System.out.println(localDate.getSecond()); System.out.println(localDate.getMinute()); System.out.println(localDate.getHour()); } @Test public void testLocalDate2() { List<LocalDate> localDates = new ArrayList<>(); localDates.add(LocalDate.parse("2020-09-11")); localDates.add(LocalDate.parse("1919-02-25")); localDates.add(LocalDate.of(2020, 9, 8)); localDates.add(LocalDate.of(1980, Month.DECEMBER, 31)); localDates.removeIf(localDate -> localDate.getYear() < 2000); System.out.println(localDates); } @Test public void testLocalDate3() { LocalDate date = LocalDate.of(2012, 1, 11); Period period = Period.ofMonths(2); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yy"); System.out.print(formatter.format(date.minus(period))); } @Test public void testLocalDate4() { LocalTime time = LocalTime.of(16, 40); String amPm = time.getHour() >= 12 ? time.getHour() == 12 ? "PM" : "AM" : "kis"; System.out.println(amPm); } @Test public void testLocalDate5() { LocalDate localDate = LocalDate.of(2012, 1, 11); Period period = Period.ofMonths(2); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("mm-dd-yy"); System.out.println(dateTimeFormatter.format(localDate.minus(period))); } @Test public void testLocalDate6() { // LocalDate localDate = LocalDate.parse("2020-5-9"); LocalDate localDate = LocalDate.parse("2020-05-09"); System.out.println(localDate); //output:: LocalDate.parse(CharSequence) method accepts String in "9999-99-99" format only. Single digit month and day value are padded with 0 to convert it to 2 digits. // //To represent 9th June 2018, format String must be "2018-06-09". // //If correct format string is not passed then an instance of java.time.format.DateTimeParseException is thrown. } @Test public void tesLocalDate7() { LocalDate date = LocalDate.parse("1980-03-16"); System.out.println(date.minusYears(-5)); } @Test public void tesLocalDate8() { LocalDate d1 = LocalDate.parse("1999-09-09"); LocalDate d2 = LocalDate.parse("1999-09-09"); LocalDate d3 = LocalDate.of(1999, 9, 9); LocalDate d4 = LocalDate.of(1999, 9, 9); System.out.println((d1 == d2) + ":" + (d2 == d3) + ":" + (d3 == d4)); //ouput:: "parse" and "of" methods create new instances, so in this case you get 4 different instance of LocalDate stored at 4 different memory addresses. } @Test public void testLocalDate9() { LocalDate date = LocalDate.parse("2000-06-25"); while (date.getDayOfMonth() >= 20) { System.out.println(date); date.plusDays(-1); } //date.plusDays(-1); creates a new LocalDate object {2000-06-24} but date reference variable still refers to {2000-06-25}. date.getDayOfMonth() again returns 25, this is an infinite loop. } @Test public void testLocalDate10() { LocalDate localDate = LocalDate.of(2020, 12, 15); int days = localDate.lengthOfMonth(); System.out.println(days); } @Test public void testLocalDate11() { LocalDate date1 = LocalDate.parse("1980-03-16"); LocalDate date2 = LocalDate.parse("1980-03-16"); System.out.println(date1.equals(date2) + " : " + date1.isEqual(date2)); } @Test public void testLocalDate_period() { Period period = Period.of(2020, 10, 29); System.out.println(period); Period period1 = Period.of(0, 0, 0); System.out.println(period1); } @Test public void testLocalDate_different_formats() { LocalDate date = LocalDate.of(1987, 11, 29); LocalTime time = LocalTime.of(8, 7, 5); String format = LocalDateTime.of(date, time).format(DateTimeFormatter.ISO_DATE_TIME); String format1 = LocalDateTime.of(date, time).format(DateTimeFormatter.ISO_TIME); System.out.println("Date is: " + format); System.out.println("Date is: " + format1); } @Test public void arrayIsHomogenous_arrayListIsHeterogenous() { List<String> list = new ArrayList<>(5); //add more elements, np, list will automatically increment list.add(0, "Array"); list.add(1, "one"); list.add(2, "List"); list.add(3, "three"); list.add(4, "four"); list.add(5, "fivew"); // System.out.println(list); int[] arrays = new int[2]; //increase the size, sout witll throw indexOutOfBoundsException arrays[0] = 1; arrays[1] = 2; for (int i = 0; i < arrays.length; i++) { System.out.println(i); } } @Test public void testArrayListAddition() { List<String> list1 = new ArrayList<>(); list1.add("A"); list1.add("D"); List<String> list2 = new ArrayList<>(); list2.add("B"); list2.add("C"); list1.addAll(1, list2); System.out.println(list1); } @Test public void testArrayListAddition1() { List<Character> list = new ArrayList<>(); list.add(0, 'V'); list.add('T'); list.add(1, 'E'); list.add(3, 'O'); if (list.contains('O')) { list.remove('O'); } for (char ch : list) { System.out.print(ch); } //output:: list.add(0, 'V'); => char 'V' is converted to Character object and stored as the first element in the list. list --> [V]. // //list.add('T'); => char 'T' is auto-boxed to Character object and stored at the end of the list. list --> [V,T]. // //list.add(1, 'E'); => char 'E' is auto-boxed to Character object and inserted at index 1 of the list, this shifts T to the right. list --> [V,E,T]. // //list.add(3, 'O'); => char 'O' is auto-boxed to Character object and added at index 3 of the list. list --> [V,E,T,O]. // //list.contains('O') => char 'O' is auto-boxed to Character object and as Character class overrides equals(String) method this expression returns true. Control goes inside if-block and executes: list.remove('O');. // // //remove method is overloaded: remove(int) and remove(Object). char can be easily assigned to int so compiler tags remove(int) method. list.remove(<ASCCI value of 'O'>); ASCCI value of 'A' is 65 (this everybody knows) so ASCII value of 'O' will be more than 65. // // //list.remove('O') throws runtime exception, as it tries to remove an item from the index greater than 65 but allowed index is 0 to 3 only. } @Test public void testArrayList100() { List<Integer> list = new ArrayList<Integer>(); list.add(27); list.add(27); list.add(new Integer(27)); list.add(new Integer(27)); System.out.println(list.get(0) == list.get(1)); System.out.println(list.get(2) == list.get(3)); //ouput:: For 1st statement, list.add(27); => Auto-boxing creates an integer object for 27. // //For 2nd statement, list.add(27); => Java compiler finds that there is already an Integer object in the memory with value 27, so it uses the same object. //new Integer(27) creates a new Object in the memory, so System.out.println(list.get(2) == list.get(3)); returns false. } @Test public void testArrayList101() { List<String> list = new ArrayList<>(); list.add(0, "Array"); list.set(0, "List"); System.out.println(list.toString()); } @Test public void testArrayListRemoval() { List<Student> students = new ArrayList<>(); students.add(new Student("James", 25)); students.add(new Student("James", 27)); students.add(new Student("James", 25)); students.add(new Student("James", 25)); students.remove(new Student("James", 25)); for (Student stud : students) { System.out.println(stud); } } class Student { private String name; private int age; Student(String name, int age) { this.name = name; this.age = age; } public String toString() { return "Student[" + name + ", " + age + "]"; } //output: Before you answer this, you must know that there are 5 different Student object created in the memory (4 at the time of adding to the list and 1 at the time of removing from the list). This means these 5 Student objects will be stored at different memory addresses. } @Test public void testArrayListRmoval() { List<Student4> students = new ArrayList<>(); students.add(new Student4("James", 25)); students.add(new Student4("James", 27)); students.add(new Student4("James", 25)); students.add(new Student4("James", 25)); students.remove(new Student4("James", 25)); for (Student4 stud : students) { System.out.println(stud); } //ouput:: remove(Object) method removes the first occurrence of matching object and equals(Object) method decides whether 2 objects are equal or not. equals(Object) method has been overridden by the Student class and equates the object based on their name and age. } class Student4 { private String name; private int age; Student4(String name, int age) { this.name = name; this.age = age; } public String toString() { return "Student[" + name + ", " + age + "]"; } public boolean equals(Object obj) { if (obj instanceof Student4) { Student4 stud = (Student4) obj; if (this.name.equals(stud.name) && this.age == stud.age) { return true; } } return false; } } @Test public void testArrayListRemoval1() { List<String> list = new ArrayList<>(); list.add("X"); list.add("Y"); list.add("X"); list.add("Y"); list.add("Z"); list.remove(new String("Y")); System.out.println(list); //ouput:: After all the add statements are executed, list contains: [X, Y, X, Y, Z]. // //list.remove(new String("Y")); removes the first occurrence of "Y" from the list, which means the 2nd element of the list. After removal list contains: [X, X, Y, Z]. // //NOTE: String class and all the wrapper classes override equals(Object) method, hence at the time of removal when another instance is passes [new String("Y")], there is no issue in removing the matching item. } @Test public void testArrayListRemoval2() { List<Integer> list = new ArrayList<>(); list.add(100); list.add(200); list.add(100); list.add(100); list.remove(new Integer(100)); System.out.println(list); } @Test public void testArrayListRemoval3() { List<String> fruits = new ArrayList<>(); fruits.add("apple"); fruits.add("orange"); fruits.add("grape"); fruits.add("mango"); fruits.add("banana"); fruits.add("grape"); if (fruits.remove("grape")) { fruits.remove("kishore"); } System.out.println(fruits); } @Test public void testArrayListRemoval4(){ List<String> dryFruits = new ArrayList<>(); dryFruits.add("Walnut"); dryFruits.add("Apricot"); dryFruits.add("Almond"); dryFruits.add("Date"); for(String dryFruit : dryFruits) { if(dryFruit.startsWith("A")) { dryFruits.remove(dryFruit); } } System.out.println(dryFruits); //output: An exception is thrown at run time } @Test public void intToDoubleTesting() { // double [] arr = new int[2]; //Line 3 // System.out.println(arr[0]); //L } @Test public void javaByValueOrPassByReference() { Message obj = new Message(); obj.print(); change(obj); obj.print(); } class Message { String msg = "Happy New Year!"; public void print() { System.out.println(msg); } } public void change(Message m) { m = new Message(); //here we are creating new object, so m.msg hoids in new referene, not the old one m.msg = "Happy Holidays!"; } @Test public void removingElementInTheList() { List<Integer> list = new ArrayList<>(); list.add(new Integer(2)); list.add(new Integer(1)); list.add(new Integer(1)); list.add(new Integer(1)); list.add(new Integer(0)); list.remove(list.indexOf(1)); list.remove(2); System.out.println(list); } @Test public void remoeveElementsFromTheList() { List<Integer> list = new ArrayList<>(); list.add(100); list.add(200); list.add(100); list.add(200); list.remove(100); System.out.println(list); //output::List cannot accept primitives, it can accept objects only. So, when 100 and 200 are added to the list, then auto-boxing feature converts these to wrapper objects of Integer type. // //So, 4 items gets added to the list. One can expect the same behavior with remove method as well that 100 will be auto-boxed to Integer object. // //But remove method is overloaded in List interface: remove(int) => Removes the element from the specified position in this list // //and remove(Object) => Removes the first occurrence of the specified element from the list. // //As remove(int) version is available, which perfectly matches with the call remove(100); hence compiler does not do auto-boxing in this case. // //But at runtime remove(100) tries to remove the element at 100th index and this throws IndexOutOfBoundsException. } @Test public void testJava8Predicate1_other_way_of_writing_predicate() { Predicate predicate = s -> true; Predicate predicate1 = s -> { return true; }; } @Test public void testJava8Predicate() { String[] arr = {"A", "ab", "bab", "Aa", "bb", "baba", "aba", "Abab"}; Predicate<String> p = s -> s.toUpperCase().substring(0, 1).equals("A"); processStringArray(arr, p); } private static void processStringArray(String[] arr, Predicate<String> predicate) { for (String str : arr) { if (predicate.test(str)) { System.out.println(str); } } } @Test public void testPrimitvesVsObjects() { int[] a1 = {2, 5, 8, 6, 9,}; int[] a2 = {2, 5, 8, 6, 9,}; Object[] a3 = {4, 4, 5, 5}; Object[] a4 = {4, 4, 5, 5}; System.out.println(Arrays.equals(a1, a2)); System.out.println(Arrays.deepEquals(a3, a4)); } @Test public void guessOutput100() { double price = 90000; String model; if (price > 100000) { model = "Tesla Model X"; } else if (price <= 100000) { model = "Tesla Model S"; } // System.out.println(model); //output: 90000 is assigned to variable 'price' but you can assign parameter value or call some method returning double value, such as: //'double price = currentTemp();'. //Usage of LOCAL variable, 'model' without initialization gives compilation error. Hence, System.out.println(model); gives compilation error. } @Test public void testDouble() { Double[] arr = new Double[2]; //System.out.println(arr[0]); int[] arra1 = new int[2]; System.out.println(arra1[0] + arra1[1]); } @Test public void guessOutput101() { int[] arr = {2, 1, 0}; for (int j : arr) { System.out.println(j); } } @Test public void guessOutput102() { new B().print(); } public class B extends A { private int i2 = 10; public void print() { A obj = new A(); System.out.println(obj.i1); System.out.println(obj.i2); System.out.println(this.i2); System.out.println(super.i2); } } public class A { private int i1 = 1; protected int i2 = 2; } @Test public void guessOutput103() { byte var = 100; switch (var) { case 100: System.out.println("var is 100"); break; // case 200: // System.out.println("var is 200"); // break; default: System.out.println("In default"); } } //output: In this case, switch expression [switch (var)] is of byte type. // //byte range is from -128 to 127. But in case expression [case 200], 200 is outside byte range and hence compilation error. @Test public void guessOutput104() { //System.out.println("Output is: 10" !=5); //output:: Binary plus (+) has got higher precedence than != operator. Let us group the expression. // //"Output is: " + 10 != 5 // //= ("Output is: " + 10) != 5 // //[!= is binary operator, so we have to evaluate the left side first. + operator behaves as concatenation operator.] // //= "Output is: 10" != 5 // //Left side of above expression is String, and right side is int. But String can't be compared to int, hence compilation error. } //list of final classes in java //java.lang.String The wrapper classes for the primitive types: // java.lang.Integer //java.lang.Byte //java.lang.Character // java.lang.Short //java.lang.Boolean //java.lang.Long // java.lang.Double // java.lang.Float // java.lang.StackTraceElement (used in building exception stacktraces) // Most of the enum classes //java.math.BigInteger // java.math.BigDecimal //java.io.File //java.awt.Font //java.awt.BasicStroke //java.awt.Color // java.awt.GradientPaint, //java.awt.LinearGradientPaint //java.awt.RadialGradientPaint, //java.awt.Cursor // java.util.Locale // java.util.UUID //java.util.Collections //java.net.URL //java.net.URI // java.net.Inet4Address //java.net.Inet6Address // java.net.InetSocketAddress //classes of java 8 time API //Clock //Duration //Instant //LocalDate //LocalDateTime //LocalTime //MonthDay //OffsetDateTime //OffSetTime //Period //Year //YearMonth //ZonedDateTime //ZoneId //ZoneOffset @Test public void testStringMethod() { String str1 = " "; boolean b1 = str1.isEmpty(); System.out.println(b1); str1.trim(); b1 = str1.isEmpty(); System.out.println(b1); } @Test public void testStringMethod1() { String[] strings = {"N", "L", "n", "O", "S"}; Arrays.sort(strings); for (String s : strings) { System.out.println(s); } } @Test public void testStrinMethod2() { String s1 = "java"; s1.concat(" rules"); System.out.println("s1 refers to " + s1); String s2 = "php"; s2 = s2.concat(" rules"); System.out.println("s2 refers to " + s2); //ouput:: string is immutabe ? //https://stackoverflow.com/questions/8798403/string-is-immutable-what-exactly-is-the-meaning } @Test public void testStringMethod3() { String javaworld = "JavaWorld"; String java = "Java"; String world = "World"; java = java + world; //this value is caluculated at run time, mnot compile time ,so java==javaworld is true System.out.println(java==(javaworld)); String pythonWorld = "PythonWorld"; //this value is at compile time only String kishoreWorld = "KishoreWorld"; //this value is at compile time only System.out.println(pythonWorld==kishoreWorld); ////hence the pythonWorld==kishoreWorld is true //ouput from udayan:Please note that Strings computed by concatenation at compile time, will be referred by String Pool during execution. Compile time String concatenation happens when both of the operands are compile time constants, such as literal, final variable etc. // //Whereas, Strings computed by concatenation at run time (if the resultant expression is not constant expression) are newly created and therefore distinct. // // //`java += world;` is same as `java = java + world;` and `java + world` is not a constant expression and hence is calculated at runtime and returns a non pool String object "JavaWorld", which is referred by variable 'java'. // // //On the other hand, variable 'javaworld' refers to String Pool object "JavaWorld". As both the variables 'java' and 'javaworld' refer to different String objects, hence `java == javaworld` returns false. } @Test public void testStringBuilder() { StringBuilder sb = new StringBuilder(100); System.out.println(sb.length() + ":" + sb.toString().length()); } @Test public void testStringBuilder1() { StringBuilder sb = new StringBuilder(5); sb.append("0123456789"); sb.delete(8, 1000); System.out.println(sb); } @Test public void testStringBuilder_String() { StringBuilder sb = new StringBuilder("Java"); String s1 = sb.toString(); String s2 = "Java"; System.out.println(s1 == s2); } @Test public void testStringBuilder_String_one() { List<String> dryFruits = new ArrayList<>(); dryFruits.add(new String("Walnut")); dryFruits.add(new String("Apricot")); dryFruits.add(new String("Almond")); dryFruits.add(new String("Date")); for (int i = 0; i < dryFruits.size(); i++) { if (i == 0) { dryFruits.remove(new String("Almond")); } } System.out.println(dryFruits); } @Test public void testStringBuilder_String_two() { List<StringBuilder> dryFruits = new ArrayList<>(); dryFruits.add(new StringBuilder("Walnut")); dryFruits.add(new StringBuilder("Apricot")); dryFruits.add(new StringBuilder("Almond")); dryFruits.add(new StringBuilder("Date")); for (int i = 0; i < dryFruits.size(); i++) { if (i == 0) { dryFruits.remove(new StringBuilder("Almond")); } } System.out.println(dryFruits); } @Test public void testStringBuilder_100() { StringBuilder stringBuilder = new StringBuilder("IZO"); stringBuilder.append("-808"); System.out.println(stringBuilder.length()); System.out.println(stringBuilder.capacity()); } @Test public void classCastExceptionExample() { /*INSERT*/ int[] arr = new int[]{100, 20, 36}; arr[1] = 5; arr[2] = 10; System.out.println("[" + arr[0] + ", " + arr[2] + "]"); //Line n1 } @Test public void guessTheOutput105() { Point p1 = new Point(); p1.x = 10; p1.y = 20; Point p2 = new Point(); p2.assign(p1.x, p1.y); System.out.println(p1.toString() + ";" + p2.toString()); } class Point { int x; int y; void assign(int x, int y) { x = this.x; this.y = y; } public String toString() { return "Point(" + x + ", " + y + ")"; } } @Test public void testSpecialStringMethod() { Object[] arr = new Object[4]; for (int i = 1; i <= 3; i++) { switch (i) { case 1: arr[i] = new String("Java"); break; case 2: arr[i] = new StringBuilder("Java"); break; case 3: arr[i] = new SpecialString("Java"); break; } } for (Object obj : arr) { System.out.println(obj); } } class SpecialString { String str; SpecialString(String str) { this.str = str; } } //output: Variable 'arr' refers to an Object array of size 4 and null is assigned to all 4 elements of this array. // //for-loop starts with i = 1, which means at 1st index String instance is stored, at 2nd index StringBuiler instance is stored and at 3rd index SpecialString instance is stored. null is stored at 0th index. // //So, first null will be printed on to the console. // //String and StringBuilder classes override toString() method, which prints the text stored in these classes. SpecialString class doesn't override toString() method and hence when instance of SpecialString is printed on to the console, you get: <fully qualified name of SpecialString class>@<hexadecimal representation of hashcode>. // //Therefore output will be: // //null // //Java // //Java // //<Some text containing @ symbol> @Test public void guessOutput106() { Student1 student1 = new Student1("James", 25); int marks = 25; review(student1, marks); System.out.println(marks + "-" + student1.marks); } private void review(Student1 student1, int marks) { marks = marks + 10; student1.marks += marks; } class Student1 { String name; int marks; Student1(String name, int marks) { this.name = name; this.marks = marks; } } @Test public void guessOutput107() { Student2 student2 = new Student2(); System.out.println(student2.name + "::" + student2.age); //output:: Methods can have same name as the class. Student() and Student(String, int) are methods and not constructors of the class, note the void return type of these methods. } class Student2 { String name; int age; void Student() { Student("James", 25); } void Student(String name, int age) { this.name = name; this.age = age; } } @Test public void guessOutput108() { int a = 100; System.out.println(-a++); } @Test public void guessOutput109() { Test1 obj = new Test1(); System.out.println(">" + obj.var1); System.out.println(">" + obj.var2); System.out.println(">" + obj.var3); } public class Test1 { char var1; double var2; float var3; } @Test public void guessOutput110() { char c = 'Z'; long l = 100_00l; int i = 9_2; float f = 2.02f; double d = 10_0.35d; l = c + i; f = c * l * i * f; f = l + i + c; i = (int) d; f = (long) d; System.out.println(i); } @Test public void guessOutput111() { System.out.println("Hello" + 1 + 2 + 3 + 4); //output:+ operator with String behaves as concatenation operator. } @Test public void guessOutput(){ Boolean [] arr = new Boolean[2]; System.out.println(arr[0] + ":" + arr[1]); boolean[] booleans = new boolean[5]; System.out.println(booleans[0] + ":" + booleans[1]); Integer[] integers = new Integer[2]; System.out.println(integers[0] + ":" + integers[1]); int[] integersList = new int[2]; System.out.println(integersList[0] + ":" + integersList[1]); } @Test public void testOutput12() { int y = 5; if (y++ == 11 && true) { //though the control is not going into the loop, it checks for frst condition, y++-11, the value of y is now 6 System.out.println(" I m in the if block"); } else if (true || --y == 4) { //here the y values will even be checed as first condition is true, it will go into the loop, so y value will still be 6 System.out.println(y); System.out.println("I am in the else if block"); } else { System.out.println("I am in the else block"); } System.out.println("I am in the main block"); } @Test public void dealingWithStaticMethod() { try { m1(); }/*catch (ArithmeticException a){ System.out.println("I am here"); }*/ finally { System.out.println("A"); } } private static void m1() { System.out.println(1 / 0); } @Test public void dealingWithStaticBlock() { System.out.println("entered test clas"); } static { // System.out.println(1/0); } @Test public void operatorsPrecendence() { int a = 10, b = 5, c = 1, result; int aeroplane = a++; System.out.println(a); System.out.println(++c); } @Test public void operatorsPrecendence1() { int i = 5; if (i++ < 6) { System.out.println(i++); System.out.println(i); } int j = 16; ++j; System.out.println(j); } @Test public void testingConstructor() { Student3 student3 = new Student3(); System.out.println(student3.name + ":" + student3.age); } public class Student3 { String name; int age; Student3() { //Student3("james",34); //A constructor can call another constructor by using this(...) and not the constructor name. //Hence Student("James", 25); causes compilation error. this("james", 34); } Student3(String name, int age) { this.name = name; this.age = age; } } @Test public void testSwitchStatement() { String[][] arr = {{"7", "6", "5"}, {"4", "3"}, {"2", "1"}}; for (int i = 0; i < arr.length; i++) { //Line n1 for (int j = 0; j < arr[i].length; j++) { //Line n2 switch (arr[i][j]) { //Line n3 case "2": case "4": case "6": break; //Line n4 default: continue; //Line n5 } System.out.print(arr[i][j]); //Line n6 } } } @Test public void testSwitchStatemenet2() { int score = 60; switch (score) { default: System.out.println("Not a valid score"); /* case score < 70: System.out.println("Failed"); break; case score >= 70: System.out.println("Passed"); break;*/ } //output: case values must evaluate to the same type / compatible type as the switch expression can use. } @Test public void testSwitchStatemenet3() { Boolean b = new Boolean("tRUe"); /* switch (b) { case true: System.out.println("ONE"); case false: System.out.println("TWO"); default: System.out.println("THREE"); }*/ //output: switch can accept primitive types: byte, short, int, char; wrapper types: Byte, Short, Integer, Character; String and enums. // //switch(b) causes compilation failure as b is of Boolean type. //pro-tip: why to override and equals method in java //https://www.techiedelight.com/why-override-equals-and-hashcode-methods-java/ } @Test public void testSwitchStatement4() { String s = "A"; String c1 = "A"; String c2 = "B"; String c3 = "C"; switch (s) { //case c1: // System.out.println("we are good"); //case c2: // System.out.println("we are c2"); //case c3: // System.out.println("we are c3"); default: System.out.println("we are default"); } //output: constants can be used for cases not variables } static String out = ""; @Test public void testSwitchStatement5() { int x = 5, y = 8; if (x++ == 5) out += "1"; if (x != 6) { } else if (x > 9) { out += "2"; } else if (y < 9) { out += "3"; } else if (x == 6) { out += "4"; } else { out += "5"; } System.out.println(out); } @Test public void testExceptionHandlingScenario() { try { method(); } catch (FileNotFoundException fileNotFoundException) { System.out.println("IO exception caught"); } catch (IOException | NoSuchFieldException ioException) { System.out.println("we are good"); } } private static void method() throws IOException, ClassCastException, NoSuchFieldException { throw new FileNotFoundException(); } @Test public void testExceptionHandlingScenario1() { try { print(); } catch (NullPointerException exception) { System.out.println("NullPointerException"); } } public static void print() { try { throw new NullPointerException(); } catch (ClassCastException classCastException) { System.out.println("ClassCastException"); } finally { System.out.println(" I am in the final block"); } } @Test public void testExceptionHandlingScenario2() { try { int x = Integer.parseInt("one"); } catch (IllegalArgumentException illegalArgumentException) { System.out.println("IllegalArgumentException"); } //ouput::: why not "NumberFormatException" , here we are using IllegalArgumentException, this is parent // of NumberFormatException } @Test public void testObjectMethod() { Object[] objects = {1, 4, 6, 8, 34}; System.out.println(mysize(objects)); } public int mysize(Object obj) { return ((Object[]) obj).length; } @Test public void java_8_interfaces() { Whiz.print(); //since java-8, static & defauly methods are allowed in interfaces } public interface Whiz { public static void main(String[] args) { System.out.println("I am good"); } public static void print() { System.out.println("I am doing goood"); } } }
package com.jzx.validate.core.core; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; /** * 解析xml中的验证规则类 * * @author 杨杰 * @version 2018年4月9日 * @see LoadValidate * @since */ public class LoadValidate { /** 存放所有的验证规则 **/ private static Map<String, ActionValidate> validateMap = new LinkedHashMap<String, ActionValidate>(); static { try { readConfiguration(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } } /** * * 读取验证规则 * * @param xmlStr * @throws DocumentException */ @SuppressWarnings("rawtypes") public static void loadValidate(String xmlStr) throws DocumentException { Document document = DocumentHelper.parseText(xmlStr); // 获取要解析的元素 Element root = document.getRootElement(); for (Iterator parent = root.elementIterator(); parent.hasNext();) { Element e = (Element) parent.next(); ActionValidate actionValidate = new ActionValidate(); actionValidate.setActionUrl(e.attributeValue("actionUrl")); List<ParamValidate> valdateList = new ArrayList<ParamValidate>(); for (Iterator son = e.elementIterator(); son.hasNext();) { Element el = (Element) son.next(); // 搜索Action引用的验证规则 if (StringUtils.equalsIgnoreCase(el.getName(), "reference")) { if (StringUtils.isEmpty(actionValidate.getReferenceName())) { actionValidate.setReferenceName(el.attributeValue("name")); } continue; } // 验证规则 ParamValidate validate = new ParamValidate(); validate.setName(el.attributeValue("name")); validate.setValidate(el.attributeValue("validate")); validate.setType(el.attributeValue("type")); validate.setIsNull(el.attributeValue("isnull")); validate.setMsg(el.attributeValue("msg")); // 增加验证规则 valdateList.add(validate); } // 增加当前actiion的验证规则 actionValidate.setParamList(valdateList); validateMap.put(e.attributeValue("actionUrl"), actionValidate); } } /** * * 获取指定目录下所有xml字符串动态数组 * * @return * @throws IOException */ public static List<String> getValidateXmlStr() throws IOException { PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(); Resource[] resources = patternResolver.getResources("classpath:validate/*-validator.xml"); List<String> xmlStrList = new ArrayList<String>(); for (int i = 0; i < resources.length; i++) { InputStreamReader inputStreamReader = new InputStreamReader(resources[i].getInputStream()); BufferedReader breader = new BufferedReader(inputStreamReader); String temp = breader.readLine(); String xmlStr = ""; while (temp != null) { xmlStr += temp + "\n"; temp = breader.readLine(); } xmlStrList.add(xmlStr); } return xmlStrList; } /** * * 初始化配置 * * @throws IOException * @throws DocumentException */ public static void readConfiguration() throws IOException, DocumentException { List<String> xmlStrList = getValidateXmlStr(); for (String xmlStr : xmlStrList) { loadValidate(xmlStr); } } public static Map<String, ActionValidate> getValidateMap() { return validateMap; } }
package lesson_4; public class first { public static void main(String[] argc){ int[] num = {1,2,3,4,5}; try{ System.out.println(num[5]); }catch (ArrayIndexOutOfBoundsException e){ System.out.println(e); }finally { System.out.println("Завершение программы"); } } }
/* * Copyright Yahoo Inc. 2016, see https://github.com/flurry/upload-clients/blob/master/LICENSE.txt for full details */ package com.flurry.proguard; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.utils.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.FileEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.UUID; import java.util.zip.GZIPOutputStream; public class UploadMapping { private static final String METADATA_BASE = "https://crash-metadata.flurry.com/pulse/v1"; private static final String UPLOAD_BASE = "https://upload.flurry.com/upload/v1"; public static final int FIVE_SECONDS_IN_MS = 5 * 1000; public static final int ONE_MINUTE_IN_MS = 60 * 1000; public static final int THREE_SECONDS_IN_MS = 3 * 1000; public static final int TEN_MINUTES_IN_MS = 10 * ONE_MINUTE_IN_MS; private static boolean EXIT_PROCESS_ON_ERROR = false; private static Logger LOGGER = LoggerFactory.getLogger(UploadMapping.class.getName()); private static final RequestConfig REQUEST_CONFIG = RequestConfig.custom() .setConnectTimeout(FIVE_SECONDS_IN_MS) // 5 Seconds .setSocketTimeout(FIVE_SECONDS_IN_MS) .setConnectionRequestTimeout(ONE_MINUTE_IN_MS).build(); private static CloseableHttpClient httpClient; public static void main(String[] args) throws IOException { ArgumentParser parser = ArgumentParsers.newArgumentParser("com.flurry.proguard.UploadMapping", true) .description("Uploads Proguard/Native Mapping Files for Android"); parser.addArgument("-k", "--api-key").required(true) .help("API Key for your project"); parser.addArgument("-u", "--uuid").required(true) .help("The build UUID"); parser.addArgument("-p", "--path").required(true) .help("Path to ProGuard/Native mapping file for the build"); parser.addArgument("-t", "--token").required(true) .help("A Flurry auth token to use for the upload"); parser.addArgument("-to", "--timeout").type(Integer.class).setDefault(TEN_MINUTES_IN_MS) .help("How long to wait (in ms) for the upload to be processed"); parser.addArgument("-n", "--ndk").type(Boolean.class).setDefault(false) .help("Is it a Native mapping file"); Namespace res = null; try { res = parser.parseArgs(args); } catch (ArgumentParserException e) { parser.handleError(e); System.exit(1); } EXIT_PROCESS_ON_ERROR = true; if (res.getBoolean("ndk")) { uploadFiles(res.getString("api_key"), res.getString("uuid"), new ArrayList<>(Collections.singletonList(res.getString("path"))), res.getString("token"), res.getInt("timeout"), AndroidUploadType.ANDROID_NATIVE); } else { uploadFiles(res.getString("api_key"), res.getString("uuid"), new ArrayList<>(Collections.singletonList(res.getString("path"))), res.getString("token"), res.getInt("timeout"), AndroidUploadType.ANDROID_JAVA); } } public static void setLogger(Logger logger) { LOGGER = logger; } /** * Parses an properties file * * @param filePath the path to the config file * @return a map of the keys and values from the config */ public static Properties parseConfigFile(String filePath) { Properties config = new Properties(); File configFile = new File(filePath); try { config.load(new FileInputStream(configFile)); } catch (IOException e) { failWithError("Bad config file {}", configFile.getAbsolutePath(), e); } return config; } /** * Tar a ProGuard/Native mapping file and send it to Flurry's crash service * * @param apiKey the API key for the project being built * @param uuid the uuid for this build * @param paths the paths to the ProGuard/Native mapping.txt files * @param token the auth token for API calls * @param timeout the amount of time to wait for the upload to be processed (in ms) */ public static void uploadFiles(String apiKey, String uuid, List<String> paths, String token, int timeout, AndroidUploadType androidUploadType) throws IOException { ArrayList<File> files = new ArrayList<>(); paths.forEach(path -> { File file = new File(path); if (file.isDirectory()) { failWithError("{} is a directory. Please provide the path to " + androidUploadType.getDisplayName() + " mapping file " + path); } files.add(file); }); if (apiKey == null) { failWithError("No API key provided"); } if (androidUploadType == AndroidUploadType.ANDROID_JAVA && uuid == null) { failWithError("No UUID provided"); } if (token == null) { failWithError("No token provided"); } try { httpClient = HttpClientBuilder.create().setDefaultRequestConfig(REQUEST_CONFIG).build(); File zippedFile = createArchive(files, uuid); String projectId = lookUpProjectId(apiKey, token); LOGGER.info("Found project {} for api key {}", projectId, apiKey); String payload = getUploadJson(zippedFile, projectId, androidUploadType.getUploadType()); String uploadId = createUpload(projectId, payload, token); LOGGER.info("Created upload with ID: {}", uploadId); sendToUploadService(zippedFile, projectId, uploadId, token); LOGGER.info(androidUploadType.getDisplayName() + " mapping uploaded to Flurry"); waitForUploadToBeProcessed(projectId, uploadId, token, timeout); LOGGER.info("Upload completed successfully!"); } finally { httpClient.close(); httpClient = null; } } /** * Create a gzipped tar archive containing the ProGuard/Native mapping files * * @param files array of mapping.txt files * @return the tar-gzipped archive */ private static File createArchive(List<File> files, String uuid) { try { File tarZippedFile = File.createTempFile("tar-zipped-file", ".tgz"); TarArchiveOutputStream taos = new TarArchiveOutputStream( new GZIPOutputStream( new BufferedOutputStream( new FileOutputStream(tarZippedFile)))); for (File file : files) { taos.putArchiveEntry(new TarArchiveEntry(file, (uuid != null && !uuid.isEmpty() ? uuid : UUID.randomUUID()) + ".txt")); IOUtils.copy(new FileInputStream(file), taos); taos.closeArchiveEntry(); } taos.finish(); taos.close(); return tarZippedFile; } catch (IOException e) { failWithError("IO Exception while trying to tar and zip the file.", e); return null; } } /** * Call the metadata service to get the project's ID * * @param apiKey the API key for the project * @param token the Flurry auth token * @return the project's ID */ private static String lookUpProjectId(String apiKey, String token) throws IOException { String queryUrl = String.format("%s/project?fields[project]=apiKey&filter[project.apiKey]=%s", METADATA_BASE, apiKey); JSONObject jsonObject; try (CloseableHttpResponse response = executeHttpRequest(new HttpGet(queryUrl), getMetadataHeaders(token))) { expectStatus(response, HttpURLConnection.HTTP_OK); jsonObject = getJsonFromEntity(response.getEntity()); JSONArray jsonArray = jsonObject.getJSONArray("data"); if (jsonArray.length() == 0) { failWithError("No projects found for the API Key: " + apiKey); } return jsonArray.getJSONObject(0).get("id").toString(); } } /** * Get the payload for creating the Upload in the metadata service * * @param zippedFile the archive to upload * @param projectId the project's ID * @return a JSON string to be sent to the metadata service */ private static String getUploadJson(File zippedFile, String projectId, String uploadType) { return getUploadTemplate() .replace("UPLOAD_TYPE", uploadType) .replace("UPLOAD_SIZE", Long.toString(zippedFile.length())) .replace("PROJECT_ID", projectId); } /** * Convert a HTTP response to JSON * * @param httpEntity the response body * @return a JSON object */ private static JSONObject getJsonFromEntity(HttpEntity httpEntity) { try { return new JSONObject(EntityUtils.toString(httpEntity)); } catch (IOException e) { failWithError("Cannot read HttpEntity {}", httpEntity, e); return null; } finally { EntityUtils.consumeQuietly(httpEntity); } } /** * Read the template Upload from resources * * @return a mostly complete JSON string */ private static String getUploadTemplate() { return "{\"data\": {" + "\"type\": \"upload\"," + "\"attributes\":" + "{\"uploadType\": \"UPLOAD_TYPE\", \"contentLength\": UPLOAD_SIZE}," + "\"relationships\":" + "{\"project\":{\"data\":{\"id\":PROJECT_ID,\"type\":\"project\"}}}" + "}" + "}"; } /** * Register this upload with the metadata service * * @param projectId the id of the project * @param payload the JSON body to send * @param token the Flurry auth token * @return the id of the created upload */ private static String createUpload(String projectId, String payload, String token) throws IOException { String postUrl = String.format("%s/project/%s/uploads", METADATA_BASE, projectId); List<Header> requestHeaders = getMetadataHeaders(token); HttpPost postRequest = new HttpPost(postUrl); postRequest.setEntity(new StringEntity(payload, Charset.forName("UTF-8"))); try (CloseableHttpResponse response = executeHttpRequest(postRequest, requestHeaders)) { expectStatus(response, HttpURLConnection.HTTP_CREATED); JSONObject jsonObject = getJsonFromEntity(response.getEntity()); return jsonObject.getJSONObject("data").get("id").toString(); } finally { postRequest.releaseConnection(); } } /** * Upload the archive to Flurry * * @param file the archive to send * @param projectId the project's id * @param uploadId the the upload's id * @param token the Flurry auth token */ private static void sendToUploadService(File file, String projectId, String uploadId, String token) throws IOException { String uploadServiceUrl = String.format("%s/upload/%s/%s", UPLOAD_BASE, projectId, uploadId); List<Header> requestHeaders = getUploadServiceHeaders(file.length(), token); HttpPost postRequest = new HttpPost(uploadServiceUrl); postRequest.setEntity(new FileEntity(file)); try (CloseableHttpResponse response = executeHttpRequest(postRequest, requestHeaders)) { expectStatus(response, HttpURLConnection.HTTP_CREATED, HttpURLConnection.HTTP_ACCEPTED); } finally { postRequest.releaseConnection(); } } /** * Ensure that a response had an expected status * * @param response the API response * @param validStatuses the list of acceptable statuses */ private static void expectStatus(CloseableHttpResponse response, Integer... validStatuses) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { failWithError("The provided token is expired"); } if (!Arrays.asList(validStatuses).contains(statusCode)) { String responseString; try { responseString = "Response Body: " + EntityUtils.toString(response.getEntity()); } catch (IOException e) { responseString = "IO Exception while reading the response body."; } failWithError("Request failed: {} {}", statusCode, responseString); } } /** * Query the metadata service to see if the upload was processed * * @param projectId the project's id * @param uploadId the upload's id * @param token the Flurry auth token * @param maxWaitTime how long to wait for the upload to be processes (in ms) */ private static void waitForUploadToBeProcessed(String projectId, String uploadId, String token, int maxWaitTime) throws IOException { int waitingTime = 0; int maxTimeToWait = Math.max(ONE_MINUTE_IN_MS, maxWaitTime); int multiplier = 1; while (true) { JSONObject upload = fetchUpload(projectId, uploadId, token); String uploadStatus = upload.getJSONObject("data") .getJSONObject("attributes") .getString("uploadStatus").toUpperCase(); switch (uploadStatus) { case "COMPLETED": return; case "FAILED": String reason = upload.getJSONObject("data") .getJSONObject("attributes") .getString("failureReason"); failWithError("Upload processing failed: {}", reason); default: if (waitingTime < maxTimeToWait) { multiplier = multiplier + 1; int sleepTime = THREE_SECONDS_IN_MS * multiplier; waitingTime += sleepTime; try { Thread.sleep(sleepTime); } catch (InterruptedException e) { failWithError("Exception while waiting for the upload to be processed", e); } } else { failWithError("Upload not processed after {}s", maxTimeToWait / 1000); } } LOGGER.debug("Upload still not processed after {}s", waitingTime / 1000); } } /** * Fetch the upload from the metadata service * * @param projectId the project's id * @param uploadId the upload's id * @param token the Flurry auth token * @return the upload */ private static JSONObject fetchUpload(String projectId, String uploadId, String token) throws IOException { String queryUrl = String.format("%s/project/%s/uploads/%s?fields[upload]=uploadStatus,failureReason", METADATA_BASE, projectId, uploadId); HttpGet getRequest = new HttpGet(queryUrl); List<Header> requestHeaders = getMetadataHeaders(token); try (CloseableHttpResponse response = executeHttpRequest(getRequest, requestHeaders)) { expectStatus(response, HttpURLConnection.HTTP_OK); return getJsonFromEntity(response.getEntity()); } finally { getRequest.releaseConnection(); } } private static CloseableHttpResponse executeHttpRequest(HttpUriRequest request, List<Header> requestHeaders) { for (Header header : requestHeaders) { request.setHeader(header.getName(), header.getValue()); } try { return httpClient.execute(request); } catch (IOException e) { failWithError("IO Exception during request: {}", request, e); return null; } } /** * Get headers for a JSON API service * * @param token the Flurry auth token to use * @return the headers */ private static List<Header> getMetadataHeaders(String token) { List<Header> headers = new ArrayList<>(); headers.add(new BasicHeader("Authorization", "Bearer " + token)); headers.add(new BasicHeader("Accept", "application/vnd.api+json")); headers.add(new BasicHeader("Content-Type", "application/vnd.api+json")); return headers; } /** * Get headers for the upload service * * @param size the size of the payload * @param token the Flurry auth token to use * @return the headers */ private static List<Header> getUploadServiceHeaders(long size, String token) { List<Header> headers = new ArrayList<>(); headers.add(new BasicHeader("Content-Type", "application/octet-stream")); headers.add(new BasicHeader("Range", "bytes 0-" + Long.toString(size - 1))); headers.add(new BasicHeader("Authorization", "Bearer " + token)); return headers; } /** * Print a message and exit the script * * @param format The message format string * @param args the extra arguments for the logger */ private static void failWithError(String format, Object... args) { LOGGER.error(format, args); if (EXIT_PROCESS_ON_ERROR) { System.exit(1); } else { String message = format; Throwable cause = null; if (args.length > 0 && args[args.length - 1] instanceof Throwable) { cause = (Throwable) args[args.length - 1]; args = Arrays.copyOf(args, args.length - 1); } if (args.length > 0) { message = String.format(format.replace("{}", "%s"), args); } throw new RuntimeException(message, cause); } } private static void validateResponse(CloseableHttpResponse httpResponse, String message) { if (httpResponse == null) { throw new NullPointerException(message); } } }
package com.clay.claykey.object.dto; /** * Created by Mina Fayek on 1/15/2016. */ public class BaseDto { }
package SukerEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.wb.swt.SWTResourceManager; public class SukerEditor_AboutDialog extends Dialog { protected Object result; protected Shell shlAbout; protected int mStyle; /** * Create the dialog. * @param parent * @param style */ public SukerEditor_AboutDialog(Shell parent, int style) { super(parent, style); mStyle = style; setText("SWT Dialog"); } /** * Open the dialog. * @return the result */ public Object open() { createContents(); shlAbout.open(); shlAbout.layout(); Display display = getParent().getDisplay(); while (!shlAbout.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return result; } /** * Create contents of the dialog. */ private void createContents() { shlAbout = new Shell(getParent(), mStyle); shlAbout.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); shlAbout.setSize(415, 222); shlAbout.setText("SukerEditor 0.8"); shlAbout.setLayout(new FormLayout()); Label lblNewLabel = new Label(shlAbout, SWT.WRAP | SWT.CENTER); FormData fd_lblNewLabel = new FormData(); fd_lblNewLabel.top = new FormAttachment(0, 22); fd_lblNewLabel.left = new FormAttachment(0, 34); lblNewLabel.setLayoutData(fd_lblNewLabel); lblNewLabel.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); lblNewLabel.setFont(SWTResourceManager.getFont("ÈÞ¸Õ¸ðÀ½T", 14, SWT.BOLD)); lblNewLabel.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE)); lblNewLabel.setText("Suker Editor 0.8"); Label lblNewLabel_2 = new Label(shlAbout, SWT.NONE); FormData fd_lblNewLabel_2 = new FormData(); fd_lblNewLabel_2.top = new FormAttachment(0, 65); fd_lblNewLabel_2.left = new FormAttachment(0, 34); lblNewLabel_2.setLayoutData(fd_lblNewLabel_2); lblNewLabel_2.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); lblNewLabel_2.setText("Date 2012-05-01"); Label lblNewLabel_3 = new Label(shlAbout, SWT.NONE); FormData fd_lblNewLabel_3 = new FormData(); fd_lblNewLabel_3.top = new FormAttachment(0, 82); fd_lblNewLabel_3.left = new FormAttachment(0, 34); lblNewLabel_3.setLayoutData(fd_lblNewLabel_3); lblNewLabel_3.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); lblNewLabel_3.setText("Rebuild : N/A"); Label lblNewLabel_4 = new Label(shlAbout, SWT.NONE); FormData fd_lblNewLabel_4 = new FormData(); fd_lblNewLabel_4.top = new FormAttachment(0, 99); fd_lblNewLabel_4.left = new FormAttachment(0, 34); lblNewLabel_4.setLayoutData(fd_lblNewLabel_4); lblNewLabel_4.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); lblNewLabel_4.setText("Original version : none"); Label lblNewLabel_1 = new Label(shlAbout, SWT.NONE); FormData fd_lblNewLabel_1 = new FormData(); fd_lblNewLabel_1.top = new FormAttachment(0, 150); fd_lblNewLabel_1.left = new FormAttachment(0, 34); lblNewLabel_1.setLayoutData(fd_lblNewLabel_1); lblNewLabel_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); lblNewLabel_1.setFont(SWTResourceManager.getFont("µ¸¿òü", 10, SWT.BOLD)); lblNewLabel_1.setText("Creator : Suker (Choonghyun.jeon@lge.com)"); Label lblNewLabel_5 = new Label(shlAbout, SWT.NONE); lblNewLabel_5.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); FormData fd_lblNewLabel_5 = new FormData(); fd_lblNewLabel_5.top = new FormAttachment(lblNewLabel_4, 6); fd_lblNewLabel_5.left = new FormAttachment(lblNewLabel, 0, SWT.LEFT); lblNewLabel_5.setLayoutData(fd_lblNewLabel_5); lblNewLabel_5.setText("description : suker\uAC00 \uB9CC\uB4E0 \uCCAB\uBC88\uC9F8 editor"); } }
package com.mobilejohnny.remote.app; import android.app.Activity; import android.content.Intent; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.support.v4.widget.DrawerLayout; import android.widget.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks { private static final String TAG = "Main"; /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ private NavigationDrawerFragment mNavigationDrawerFragment; /** * Used to store the last screen title. For use in {@link #restoreActionBar()}. */ private CharSequence mTitle; static TCP tcp = new TCP(); private String server_ip; private int server_port; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); server_ip = PreferenceManager .getDefaultSharedPreferences(this) .getString("server", "192.168.1.5"); server_port = PreferenceManager .getDefaultSharedPreferences(this) .getInt("server_port", 3840); connectToServer(); setContentView(R.layout.activity_main); mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); } private void connectToServer() { new Thread(new Runnable() { @Override public void run() { boolean result = tcp.connect(server_ip,server_port); if(result) { Log.i(TAG,"连接成功"); } else { Log.e(TAG,"连接失败"); } } }).start(); } @Override public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, PlaceholderFragment.newInstance(position)) .commit(); } public void onSectionAttached(int number) { // switch (number) { // case 1: // mTitle = getString(R.string.title_section1); // break; // case 2: // mTitle = getString(R.string.title_section2); // break; // case 3: // mTitle = getString(R.string.title_section3); // break; // } String[] devices = getResources().getStringArray(R.array.devices); mTitle = devices[number]; } public void restoreActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. getMenuInflater().inflate(R.menu.main, menu); restoreActionBar(); return true; } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent intent = new Intent(this,SettingsActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment implements AdapterView.OnItemClickListener { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; private TextView tvSection; private int sectionNumber; private GridView grid; /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); grid = (GridView) rootView.findViewById(R.id.grid); List<Map<String,Object>> data = new ArrayList<Map<String, Object>>(); Map<String,Object> map = new HashMap<String, Object>(); map.put("icon",android.R.drawable.ic_lock_power_off); map.put("text","开关"); map.put("code","23098"); data.add(map); map = new HashMap<String, Object>(); map.put("icon",android.R.drawable.ic_lock_silent_mode); map.put("text","静音"); map.put("code","23098"); data.add(map); map = new HashMap<String, Object>(); map.put("icon",android.R.drawable.ic_media_play); map.put("text","播放"); map.put("code","23098"); data.add(map); map = new HashMap<String, Object>(); map.put("icon",android.R.drawable.ic_media_next); map.put("text","下一个"); map.put("code","23098"); data.add(map); map = new HashMap<String, Object>(); map.put("icon",android.R.drawable.ic_media_previous); map.put("text","上一个"); map.put("code","23098"); data.add(map); grid.setOnItemClickListener(this); SimpleAdapter adapter = new SimpleAdapter(getContext(), data,R.layout.grid_item,new String[]{"icon","text"},new int[]{R.id.img,R.id.text1} ); grid.setAdapter(adapter); return rootView; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Map<String,Object> item = (Map<String, Object>) parent.getAdapter().getItem(position); final String code = item.get("code").toString(); new Thread(new Runnable() { @Override public void run() { tcp.send(code.getBytes()); Log.i(TAG,"发送:"+code); } }).start(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER); ((MainActivity) activity).onSectionAttached(sectionNumber); } } }
package barrelofmonkeys; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; public class BarrelOfMonkeysEndToEnd { XPathParser fileParser; @Before public void parseFile() throws Exception { fileParser = new XPathFileParser("SongLibrary.xml"); } @Test public void testFinderForTenSongs() throws Exception { SongLoader loader = new XPathSongLoader(fileParser); SongFinderStrategy strategy = new FirstCharacterFinderStrategy('c', 5); List<Song> playList = strategy.playlist(loader); List<Song> expected = new ArrayList<Song>(); expected.add(new Song("Caught Up In You", ".38 Special")); expected.add(new Song("Under Attack", "ABBA")); expected.add(new Song("Kelly Watch The Stars", "Air [French Band]")); expected.add(new Song("Second Chance", ".38 Special")); expected.add(new Song("Eden", "10,000 Maniacs")); assertEquals(expected, playList); } @Ignore public void testFinderWithFirstAndLastSong() throws Exception { // TODO } @Ignore public void testFinderWithShortestPlaylistBetweenTwoSongs() throws Exception { // TODO } @Ignore public void testFinderWithSpecificDuration() throws Exception { // TODO } }
package com.example.healthmanage.ui.activity.famousDoctorHall.ui; import android.content.Context; import android.os.Bundle; import android.view.View; import androidx.core.content.ContextCompat; import androidx.lifecycle.Observer; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.example.healthmanage.BR; import com.example.healthmanage.R; import com.example.healthmanage.base.BaseActivity; import com.example.healthmanage.databinding.ActivityFamousDoctorDetailBinding; import com.example.healthmanage.ui.activity.famousDoctorHall.DoctorHallViewModel; import com.example.healthmanage.ui.activity.famousDoctorHall.adapter.AppraiseAdapter; import com.example.healthmanage.ui.activity.famousDoctorHall.response.AppraiseResponse; import com.example.healthmanage.ui.activity.famousDoctorHall.response.FamousDoctorInfoResponse; import com.example.healthmanage.view.GridItemDecoration; import com.example.healthmanage.widget.TitleToolBar; import java.util.ArrayList; import java.util.List; /** * desc:医生详情 * date:2021/7/8 17:20 * author:bWang */ public class FamousDoctorInfoActivity extends BaseActivity<ActivityFamousDoctorDetailBinding, DoctorHallViewModel> implements TitleToolBar.OnTitleIconClickCallBack { private Context mContext; private TitleToolBar mTitleToolBar = new TitleToolBar(); private List<AppraiseResponse.DataBean> mAppraiseDataBeans; private AppraiseAdapter mAppraiseAdapter; @Override protected void initData() { mContext = FamousDoctorInfoActivity.this; mTitleToolBar.setTitle("医生详情"); mTitleToolBar.setLeftIconVisible(true); mTitleToolBar.setTitleColor(getResources().getColor(R.color.colorBlack)); dataBinding.layoutDoctorDetailTitle.toolbarTitle.setBackgroundColor(getResources().getColor(R.color.white)); mTitleToolBar.setBackIconSrc(R.drawable.back_black); viewModel.setTitleToolBar(mTitleToolBar); viewModel.getDoctorInfo(getIntent().getIntExtra("systemUserId",0)); viewModel.getAppraiseList(getIntent().getIntExtra("systemUserId",0)); mAppraiseDataBeans = new ArrayList<>(); mAppraiseAdapter = new AppraiseAdapter(mAppraiseDataBeans); dataBinding.recyclerviewAppraise.setLayoutManager(new LinearLayoutManager(this)); //最后一个不显示分割线且自定义分割线 GridItemDecoration gridItemDecoration = new GridItemDecoration(this, DividerItemDecoration.VERTICAL); gridItemDecoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.line_divider)); if (dataBinding.recyclerviewAppraise.getItemDecorationCount()==0){ dataBinding.recyclerviewAppraise.addItemDecoration(gridItemDecoration); } dataBinding.recyclerviewAppraise.setAdapter(mAppraiseAdapter); } @Override protected void registerUIChangeEventObserver() { super.registerUIChangeEventObserver(); viewModel.doctorInfoLiveData.observe(this, new Observer<FamousDoctorInfoResponse.DataBean>() { @Override public void onChanged(FamousDoctorInfoResponse.DataBean dataBean) { if (dataBean!= null){ Glide.with(mContext).load(dataBean.getAvatar()).apply(new RequestOptions().circleCrop()) .error(R.drawable.ic_doctor_logo) .into(dataBinding.ivDoctor); dataBinding.tvNameOrRank.setText(dataBean.getName()+"\u3000"+dataBean.getRank()); dataBinding.tvAddressOrOffice.setText(dataBean.getAppHospital().getAddr()+"\u3000"+dataBean.getAppHospitalDepartment().getName()); dataBinding.tvConsultNumber.setText(String.valueOf(dataBean.getConsultAmount())); dataBinding.tvFocusNumber.setText(String.valueOf(dataBean.getFollowAmount())); dataBinding.tvDoctorSpeciality.setText(dataBean.getSpeciality()); } } }); viewModel.mAppraiseBeanMutableLiveData.observe(this, new Observer<List<AppraiseResponse.DataBean>>() { @Override public void onChanged(List<AppraiseResponse.DataBean> dataBeans) { if (dataBeans!=null && dataBeans.size()>0){ dataBinding.tvNoAppraise.setVisibility(View.GONE); dataBinding.recyclerviewAppraise.setVisibility(View.VISIBLE); if (mAppraiseDataBeans!=null&& mAppraiseDataBeans.size()>0){ mAppraiseDataBeans.clear(); } mAppraiseDataBeans.addAll(dataBeans); mAppraiseAdapter.notifyDataSetChanged(); }else { dataBinding.tvNoAppraise.setVisibility(View.VISIBLE); dataBinding.recyclerviewAppraise.setVisibility(View.GONE); } } }); } @Override public void initViewListener() { super.initViewListener(); mTitleToolBar.setOnClickCallBack(this); } @Override protected int initVariableId() { return BR.ViewModel; } @Override protected int setContentViewSrc(Bundle savedInstanceState) { return R.layout.activity_famous_doctor_detail; } @Override public void onRightIconClick() { } @Override public void onBackIconClick() { finish(); } }
package model; import java.util.ArrayList; import java.util.List; /** * Inventory is a space for items that is carried by the player. */ public class Inventory { private final List<Item> itemList; public Inventory() { itemList = new ArrayList<>(); } public void addItem(Item item) { itemList.add(item); } /** * @return names of all items on inventory */ public List<String> getNames() { List<String> names = new ArrayList<>(); for (Item item : itemList) names.add(item.getName()); return names; } }
package com.wenqiao.wendy; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class WendyApplicationTests { @Test void contextLoads() { } }
/* */ package datechooser.view.appearance.custom; /* */ /* */ import datechooser.view.appearance.CellRenderer; /* */ import java.awt.AlphaComposite; /* */ import java.awt.Color; /* */ import java.awt.Component; /* */ import java.awt.Composite; /* */ import java.awt.Font; /* */ import java.awt.Graphics2D; /* */ import java.awt.Insets; /* */ import java.awt.Rectangle; /* */ import java.awt.font.FontRenderContext; /* */ import java.awt.geom.Rectangle2D; /* */ import java.io.IOException; /* */ import java.io.ObjectInputStream; /* */ import javax.swing.border.Border; /* */ /* */ /* */ /* */ /* */ /* */ public class CustomCellRenderer /* */ extends CellRenderer /* */ { /* */ private CustomCellAppearance appearance; /* */ private transient Composite fillComposite; /* */ /* */ public CustomCellRenderer(CustomCellAppearance anAppearance) /* */ { /* 30 */ setAppearance(anAppearance); /* 31 */ this.fillComposite = AlphaComposite.getInstance(3); /* */ } /* */ /* */ public void render(Graphics2D g, Component c, String text, int width, int height, boolean isCursor) { /* 35 */ Border border = getAppearance().getCellBorder(); /* 36 */ g.setColor(getAppearance().getBackgroundColor()); /* 37 */ g.fillRect(0, 0, width, height); /* 38 */ g.setComposite(this.fillComposite); /* 39 */ Rectangle cellRect = new Rectangle(0, 0, width, height); /* 40 */ if (border != null) { /* 41 */ Insets borderInsets = border.getBorderInsets(c); /* 42 */ cellRect.setRect(cellRect.x + borderInsets.left, cellRect.y + borderInsets.top, cellRect.width - (borderInsets.left + borderInsets.right), cellRect.height - (borderInsets.top + borderInsets.bottom)); /* */ /* */ /* */ /* 46 */ border.paintBorder(c, g, 0, 0, width, height); /* */ } /* 48 */ g.setFont(this.appearance.getFont()); /* 49 */ paintText(g, text, getAppearance().getTextColor(), cellRect, this.appearance.getFont()); /* 50 */ if ((isCursor) && (getAppearance().isSelectable())) { /* 51 */ paintCursor(g, cellRect, getAppearance().getCursorColor()); /* */ } /* */ } /* */ /* */ /* */ private void paintText(Graphics2D g, String text, Color color, Rectangle rec, Font font) /* */ { /* 58 */ g.setColor(color); /* 59 */ FontRenderContext context = g.getFontRenderContext(); /* 60 */ Rectangle2D bounds = font.getStringBounds(text, context); /* */ /* 62 */ double x = rec.getX() + (rec.getWidth() - bounds.getWidth()) / 2.0D; /* 63 */ double y = rec.getY() + (rec.getHeight() - bounds.getHeight()) / 2.0D; /* */ /* 65 */ double ascent = -bounds.getY(); /* 66 */ double baseY = y + ascent; /* 67 */ g.drawString(text, (int)x, (int)baseY); /* */ } /* */ /* */ public CustomCellAppearance getAppearance() { /* 71 */ return this.appearance; /* */ } /* */ /* */ public void setAppearance(CustomCellAppearance appearance) { /* 75 */ this.appearance = appearance; /* */ } /* */ /* */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { /* 79 */ in.defaultReadObject(); /* 80 */ this.fillComposite = AlphaComposite.getInstance(3); /* */ } /* */ } /* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/view/appearance/custom/CustomCellRenderer.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
package com.devs4j.Rest.Services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import com.devs4j.Rest.Entity.User; import com.devs4j.Rest.Repository.UserRepository; @Service public class UserJpaService { @Autowired private UserRepository userRepository; public List<User> getUsers(){ return userRepository.findAll(); } public User getUserById(Integer id) { return userRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NO_CONTENT,String.format("no existe el id %d", id)) ); } @Cacheable("users") // para guadra en caheche la respuest, la confifuracipon esta en la clase CacheConfig public User getUserByUserName(String userName) { try {//se simula una respuest tardada Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } // la primera vez se tardará el tiempo original //pero despues solo regresará lo que ya tiene en cahce y en realidas ya no se ejecuta el metodo //y la respuesta es más rapida return userRepository.findByUserName(userName).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND,String.format("no existe el usuario %s",userName)) ); } public User getUserByUserNameAndPassword(String usarName,String password) { return userRepository.findByUserNameAndPassword(usarName, password).orElseThrow(() -> new ResponseStatusException(HttpStatus.NO_CONTENT,"User and password don´t exist") ); } public Page<User> getUsersPages(int page,int size) { return userRepository.findAll(PageRequest.of(page, size)); } public List<String> getUserNames(){ return userRepository.findUserNames(); } public Page<String> getUserNamesPages(int page,int size){ return userRepository.findUserNamesPages(PageRequest.of(page, size)); } @CacheEvict("users") public void deleteUserByName(String userName) { User userByUserName = getUserByUserName(userName); userRepository.delete(userByUserName); } }
package Index.Action; import Base.Date.DateBase; import Common.TimeCommon; import Index.Date.*; import Index.Model.*; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.catalina.connector.Request; import org.apache.catalina.deploy.LoginConfig; import org.apache.jasper.tagplugins.jstl.core.Out; import com.mysql.fabric.Response; import com.sun.crypto.provider.RSACipher; public class AttendanceAction extends HttpServlet { PreparedStatement sql; AttendanceModel attendance=new AttendanceModel(); HttpSession session; StudentDate stuDate; ResultSet result; PrintWriter out; AttendanceDate aten=new AttendanceDate(); String action="",user="",power=""; int state=0;//记录学生上机状态 private static final long serialVersionUID = 1L; public AttendanceAction() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { out=response.getWriter(); session=request.getSession(true); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); stuDate=new StudentDate(); user=(String)session.getAttribute("user"); result=stuDate.findAttendance(user); session.setAttribute("attenInfo", result); power=(String)session.getAttribute("power"); action=request.getParameter("action"); session.setAttribute("stateInfo", ""); session.setAttribute("state", "-1"); out=response.getWriter(); session.setAttribute("attendance",attendance); //查找课程 result=aten.findCourse(); attendance.setResult(result); ResultSet rs1; try{ if(result.next()){ session.setAttribute("course_name", result.getString("course_name")); session.setAttribute("att_class", result); String cid=result.getString("course_id"); rs1=aten.findattence(user,cid); if(rs1.next()){ session.setAttribute("stateInfo", "你已经考勤完毕"); response.sendRedirect("./student/attendance.jsp"); }else{ session.setAttribute("state", "0"); } //学生的相关信息 int endTime; if(power.equals("1")){ if(action==null) action=""; if(action.equals("begin")){ int beginTime; beginTime=TimeCommon.getMin(); session.setAttribute("beginTime", beginTime); aten.getBegin(beginTime); session.setAttribute("state", "1"); session.setAttribute("stateInfo", "上机成功"); response.sendRedirect("./student/attendance.jsp"); } if(action.equals("end")){ endTime=TimeCommon.getMin(); int beginTime=(int)session.getAttribute("beginTime"); int m=aten.addAttendance(result, beginTime,endTime, user); session.setAttribute("state", "-1"); if(m!=0){ session.setAttribute("stateInfo", "下机成功"); }else{ session.setAttribute("stateInfo", "下机失败"); } response.sendRedirect("./student/attendance.jsp"); } } }else { session.setAttribute("stateInfo", "当前没有课程"); } response.sendRedirect("./student/attendance.jsp"); }catch(Exception e){ } } } //学生方面的出勤状况 /*try{ if(result.next()){ if(power.equals("1")){ if(action==null) action=""; if(action.equals("begin")){ session.setAttribute("state", "1"); session.setAttribute("stateInfo", "上机成功"); response.sendRedirect("./student/attendance.jsp"); } if(action.equals("end")){ session.setAttribute("state", "-1"); session.setAttribute("stateInfo", "下机成功"); response.sendRedirect("./student/attendance.jsp"); } } response.sendRedirect("./student/attendance.jsp"); } }catch(Exception e){ } }*/ /*result=aten.findCourse(); attendance.setResult(result); try{ response.sendRedirect("./student/attendance.jsp"); }catch(Exception e){ }*/
package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * Category */ @Validated @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2020-04-02T16:04:50.980Z") public class Category { /** * Gets or Sets _9Name */ public enum 9NameEnum { AM("AM"), A1("A1"), B1("B1"), B("B"), D1("D1"), D("D"), BE("BE"), D1E("D1E"), DE("DE"); private String value; 9NameEnum(String value) { this.value = value; } @Override @JsonValue public String toString() { return String.valueOf(value); } @JsonCreator public static 9NameEnum fromValue(String text) { for (9NameEnum b : 9NameEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } } @JsonProperty("9_name") private 9NameEnum _9Name = null; @JsonProperty("10_dateOfIssue") private String _10DateOfIssue = null; @JsonProperty("11_dateOfExpiry") private String _11DateOfExpiry = "null"; @JsonProperty("12_code") private String _12Code = "null"; public Category _9Name(9NameEnum _9Name) { this._9Name = _9Name; return this; } /** * Get _9Name * @return _9Name **/ @ApiModelProperty(value = "") public 9NameEnum get9Name() { return _9Name; } public void set9Name(9NameEnum _9Name) { this._9Name = _9Name; } public Category _10DateOfIssue(String _10DateOfIssue) { this._10DateOfIssue = _10DateOfIssue; return this; } /** * Get _10DateOfIssue * @return _10DateOfIssue **/ @ApiModelProperty(example = "19.01.13", value = "") public String get10DateOfIssue() { return _10DateOfIssue; } public void set10DateOfIssue(String _10DateOfIssue) { this._10DateOfIssue = _10DateOfIssue; } public Category _11DateOfExpiry(String _11DateOfExpiry) { this._11DateOfExpiry = _11DateOfExpiry; return this; } /** * Get _11DateOfExpiry * @return _11DateOfExpiry **/ @ApiModelProperty(example = "24.11.21", value = "") public String get11DateOfExpiry() { return _11DateOfExpiry; } public void set11DateOfExpiry(String _11DateOfExpiry) { this._11DateOfExpiry = _11DateOfExpiry; } public Category _12Code(String _12Code) { this._12Code = _12Code; return this; } /** * Get _12Code * @return _12Code **/ @ApiModelProperty(example = "95.(24.11.21)", value = "") public String get12Code() { return _12Code; } public void set12Code(String _12Code) { this._12Code = _12Code; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Category category = (Category) o; return Objects.equals(this._9Name, category._9Name) && Objects.equals(this._10DateOfIssue, category._10DateOfIssue) && Objects.equals(this._11DateOfExpiry, category._11DateOfExpiry) && Objects.equals(this._12Code, category._12Code); } @Override public int hashCode() { return Objects.hash(_9Name, _10DateOfIssue, _11DateOfExpiry, _12Code); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Category {\n"); sb.append(" _9Name: ").append(toIndentedString(_9Name)).append("\n"); sb.append(" _10DateOfIssue: ").append(toIndentedString(_10DateOfIssue)).append("\n"); sb.append(" _11DateOfExpiry: ").append(toIndentedString(_11DateOfExpiry)).append("\n"); sb.append(" _12Code: ").append(toIndentedString(_12Code)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.osce.server.security; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @ClassName: PfUserDetails * @Description: 当前登录用户详情 * @Author yangtongbin * @Date 2017/9/2 22:53 */ public class PfUserDetails extends User implements UserDetails { private static final long serialVersionUID = -2920433765248963774L; private Map<String, GrantedAuthority> authorityMap; private boolean accountNonExpired; private boolean accountNonLocked; private boolean credentialsNonExpired; public PfUserDetails() {} public Map<String, GrantedAuthority> getAuthorityMap() { return authorityMap; } public void setAuthorityMap(Map<String, GrantedAuthority> authorityMap) { this.authorityMap = authorityMap; } @Override public Collection<GrantedAuthority> getAuthorities() { return authorityMap.values(); } @Override public boolean isAccountNonExpired() { return accountNonExpired; } @Override public boolean isAccountNonLocked() { return accountNonLocked; } @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired; } public void setAuthorities(Collection<GrantedAuthority> authorities) { if(CollectionUtils.isEmpty(authorities)){ return; } this.authorityMap = new HashMap<String, GrantedAuthority>(); for (GrantedAuthority auth : authorities) { if(!StringUtils.isEmpty(auth.getAuthority())){ this.authorityMap.put(auth.getAuthority().trim(), auth); } } } public void setAccountNonExpired(boolean accountNonExpired) { this.accountNonExpired = accountNonExpired; } public void setAccountNonLocked(boolean accountNonLocked) { this.accountNonLocked = accountNonLocked; } public void setCredentialsNonExpired(boolean credentialsNonExpired) { this.credentialsNonExpired = credentialsNonExpired; } @Override public boolean equals(Object rhs) { if (rhs instanceof PfUserDetails) { return getUsername().equals(((PfUserDetails) rhs).getUsername()); } return false; } @Override public int hashCode() { return getUsername().hashCode(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()).append(": "); sb.append("Username: ").append(getUsername()).append("; "); sb.append("Password: [PROTECTED]; "); sb.append("Enabled: ").append(isEnabled()).append("; "); sb.append("AccountNonExpired: ").append(this.accountNonExpired).append("; "); sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired).append("; "); sb.append("AccountNonLocked: ").append(this.accountNonLocked).append("; "); if (!this.authorityMap.isEmpty()) { sb.append("当前用户被授予的权限有:"); boolean first = true; for (GrantedAuthority auth : this.authorityMap.values()) { if (!first) { sb.append(","); } first = false; sb.append(auth); } } else { sb.append("当前用户没有被授予任何权限!"); } return sb.toString(); } }
package com.union.design.generator.jpa; import com.union.design.generator.ClassField; import lombok.Builder; import lombok.Data; import java.util.List; import java.util.Set; @Builder @Data public class JPAEntity { private String packageName; private Set<String> importPackages; private String tableName; private String className; private List<ClassField> classFields; }
package mk.petrovski.weathergurumvp.ui.city; import java.util.List; import mk.petrovski.weathergurumvp.data.local.db.CityDetailsModel; import mk.petrovski.weathergurumvp.data.remote.model.location_models.LocationModel; import mk.petrovski.weathergurumvp.ui.base.BaseMvpView; /** * Created by Nikola Petrovski on 2/14/2017. */ public interface ManageCityMvpView extends BaseMvpView { void showAutocompleteCities(List<LocationModel> locationList, LocationModel[] locationArray); void showCities(List<CityDetailsModel> cities); void showEmptyView(); void onCityAdded(CityDetailsModel city); void onCityDelete(int position); }
package com.tencent.mm.plugin.account.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.plugin.account.ui.l.9; class l$9$2 implements OnClickListener { final /* synthetic */ 9 eSL; l$9$2(9 9) { this.eSL = 9; } public final void onClick(DialogInterface dialogInterface, int i) { this.eSL.eSI.eSu.eSO.reset(); } }
package things.entity; import things.entity.template_method.DestroyableObject; import java.awt.*; /** * This is an instantiable class called BarrierBlock for creating individual barrier blocks entities. * It is a sub-class of GameComponent therefore it inherits all of its * attributes and abstract methods * * @author Darren Moriarty * created on 11/11/2016. * * @version 2.0 */ public class BarrierBlock extends DestroyableObject { // class attributes are made private so that they can not be directly accessed outside this class /** * 6 argument constructor method * * @param topLeftXPos * @param topLeftYPos * @param width * @param height * @param color * @param destroyed The initial value of destroyed */ public BarrierBlock(int topLeftXPos, int topLeftYPos, int width, int height, Color color, boolean destroyed) { super(topLeftXPos, topLeftYPos, width, height, color); setDestroyed(destroyed); } @Override public void draw(Graphics2D g) { g.setColor(color); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.drawRect(topLeftXPos, topLeftYPos, width, height); g.fillRect(topLeftXPos, topLeftYPos, width, height); } @Override public void update() { } @Override protected void performDestroyableObjectCollisionAction(DestroyableObject destroyableObject, Bullet tankBullet) { } public String toString(){ return "BarrierBlock class is working"; } }
package sort; import java.util.Arrays; //给定一个数组arr和一个数num,请把小于num的数放在数组的左边,等于num的数放在数组的中间,大于num的数放在数组的右边。要求额外空间复杂度为O(1),时间复杂度为O(N) public class NetherLandFlag { public static int[] partition(int[] arr,int startIndex,int endIndex,int target){ int less = startIndex - 1; int more = endIndex + 1; int cur = 0; while (cur < more){ if(arr[cur] < target){ swap(arr,++less,cur++); }else if(arr[cur] > target){ swap(arr,cur,--more); }else{ cur++; } } return arr; } public static void swap(int[] arr, int i,int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void main(String[] args) { int[] arr = new int[]{7,2,9,3,5,8,8,5,1,6,6,4}; int[] res = partition(arr,0,arr.length-1,5); System.out.println(Arrays.toString(res)); } }
package se.lexicon.carl.data; import se.lexicon.carl.model.Person; public class People { private static Person[] array1 = new Person[0]; public int size(){ return array1.length; } public Person[] findAll(){ return array1; } public Person findById(int personID){ return array1[personID]; } }
package com.smxknife.cloud.netflix.service; import javax.transaction.Transactional; /** * @author smxknife * 2021/5/29 */ public interface PayOrderService { @Transactional void syncOrder(); }
package com.jackie.classbook.dto.request; import com.jackie.classbook.dto.BaseReqDTO; import com.jackie.classbook.util.ValidtionUitl; /** * Created with IntelliJ IDEA. * Description: * * @author xujj * @date 2018/7/3 */ public class ClassRemoveMateReqDTO extends BaseReqDTO { private Long classId; private String mateIds; @Override public void validation() { ValidtionUitl.validation(this); } public Long getClassId() { return classId; } public void setClassId(Long classId) { this.classId = classId; } public String getMateIds() { return mateIds; } public void setMateIds(String mateIds) { this.mateIds = mateIds; } }
package br.usp.memoriavirtual.controle; import java.util.ArrayList; import java.util.List; import br.usp.memoriavirtual.modelo.entidades.Multimidia; public interface BeanComMidia { /** * * @return Coleção de objetos Multimídia */ public List<Multimidia> recuperaColecaoMidia(); /** *Adicionar Objetos Multimidia */ public void adicionarMidia (Multimidia midia); /** *Remover Objetos Multimidia */ public String removeMidia(Multimidia midia); public String removeMidia(int index); public ArrayList<Integer> getApresentaMidias() ; public void setApresentaMidias(ArrayList<Integer> apresentaMidias); public boolean isRenderCell(int index) ; }
package com.yinghai.a24divine_user.module.login.phone; import android.content.Context; import android.text.TextUtils; import com.example.fansonlib.utils.NetWorkUtil; import com.example.fansonlib.utils.ShowToast; import com.yinghai.a24divine_user.R; import com.yinghai.a24divine_user.base.MyBasePresenter; import com.yinghai.a24divine_user.bean.PersonInfoBean; import io.rong.imlib.RongIMClient; /** * @author Created by:fanson * Created on:2017/10/25 15:44 * Describe:登录的P层(逻辑)实现类 */ public class LoginPresenter extends MyBasePresenter<LoginModel, ContractLogin.ILoginView> implements ContractLogin.ILoginPresenter , ContractLogin.ILoginModel.ILoginCallback, ContractLogin.ILoginModel.IGetCodeCallback { private Context mContext; public LoginPresenter(ContractLogin.ILoginView view, Context context) { this.mContext = context; attachView(view); } @Override public void onLogin(String countryCode, String telNo, String verifyCode) { if (!checkToPhoneLogin()) { return; } getBaseView().showLoading(); mBaseModel.verifyLogin(getBaseView().getCountryCode(), getBaseView().getTelNo(), getBaseView().getVerifyCode(), this); } /** * 手机登录前進行輸入判空 * * @return */ private boolean checkToPhoneLogin() { if (TextUtils.isEmpty(getBaseView().getTelNo())) { return false; } if (TextUtils.isEmpty(getBaseView().getVerifyCode())) { return false; } if (!NetWorkUtil.isNetWordConnected(mContext)) { ShowToast.singleShort(mContext.getString(R.string.no_net)); return false; } return true; } @Override public void onLoingPwd(String countryCode, String telNo, String pwd) { if (!checkToPasswordLogin()) { return; } getBaseView().showLoading(); mBaseModel.pwdLogin(getBaseView().getCountryCode(), getBaseView().getTelNo(), getBaseView().getPassword(), this); } /** * 密码登录前進行輸入判空 * * @return */ private boolean checkToPasswordLogin() { if (TextUtils.isEmpty(getBaseView().getTelNo())) { return false; } if (TextUtils.isEmpty(getBaseView().getPassword())) { return false; } if (!NetWorkUtil.isNetWordConnected(mContext)) { ShowToast.singleShort(mContext.getString(R.string.no_net)); return false; } return true; } @Override public void onGetCode(String countryCode, String telNo) { if (!checkToGetVerifyCode()) { getBaseView().setGetVerifyCodeEnable(true); return; } getBaseView().hideLoading(); mBaseModel.getVerifyCode(getBaseView().getCountryCode(), getBaseView().getTelNo(), this); } /** * 獲取驗證碼前進行輸入判斷 * * @return */ private boolean checkToGetVerifyCode() { if (TextUtils.isEmpty(getBaseView().getTelNo())) { return false; } if (!NetWorkUtil.isNetWordConnected(mContext)) { ShowToast.singleShort(mContext.getString(R.string.no_net)); return false; } return true; } @Override public void onGetCodeSuccess() { if (isViewAttached()) { getBaseView().getCodeSuccess(); } } @Override public void onGetCodeFailure(String errorMsg) { if (isViewAttached()) { getBaseView().getCodeFailure(errorMsg); } } @Override public void onLoginSuccess(final PersonInfoBean bean) { mBaseModel.rongIMLogin(bean.getData().getTfUser().getUToken(), new RongIMClient.ConnectCallback() { @Override public void onTokenIncorrect() { if (isViewAttached()) { getBaseView().hideLoading(); getBaseView().onLoginFailure(mContext.getString(R.string.token_incorrect)); } } @Override public void onSuccess(String s) { if (isViewAttached()) { getBaseView().hideLoading(); if (TextUtils.isEmpty(bean.getData().getTfUser().getUPassword())) { getBaseView().loginSuccess(false); } else { getBaseView().loginSuccess(true); } } } @Override public void onError(RongIMClient.ErrorCode errorCode) { if (isViewAttached()) { getBaseView().hideLoading(); getBaseView().onLoginFailure(mContext.getString(R.string.im_connect_error) + errorCode.getMessage()); } } }); } @Override public void onLoginFailure(String errorMsg) { if (isViewAttached()) { getBaseView().getCodeFailure(errorMsg); } } @Override protected LoginModel createModel() { return new LoginModel(); } @Override public void handlerResultCode(int code) { handleResultCode(code); } @Override public void detachView() { super.detachView(); } }
package ru.busride.activities; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import com.roadtob.R; import java.util.Timer; import java.util.TimerTask; /** * Created by Shcherbakov on 04.08.2016. */ public class SplashActivity extends Activity { private static final long DELAY = 3000; private boolean scheduled = false; private Timer splashTimer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_screen); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); preferences.edit().remove("date").commit(); splashTimer = new Timer(); splashTimer.schedule(new TimerTask() { @Override public void run() { Log.e("qwe", "AEEEEEEEEEEEEE"); SplashActivity.this.finish(); startActivity(new Intent(SplashActivity.this, NavigationActivity.class)); } }, DELAY); scheduled = true; } @Override protected void onDestroy() { super.onDestroy(); if (scheduled) splashTimer.cancel(); splashTimer.purge(); } }
/* 1: */ package com.kaldin.analytics.action; /* 2: */ /* 3: */ import com.kaldin.analytics.dao.AnalyticsDAO; /* 4: */ import com.kaldin.analytics.dto.PageDTO; /* 5: */ import com.kaldin.exception.ErrorLogDAO; /* 6: */ import com.kaldin.user.register.dao.impl.ActivationImplementor; /* 7: */ import java.util.ArrayList; /* 8: */ import java.util.List; /* 9: */ import javax.servlet.http.HttpServletRequest; /* 10: */ import javax.servlet.http.HttpServletResponse; /* 11: */ import org.apache.struts.action.Action; /* 12: */ import org.apache.struts.action.ActionForm; /* 13: */ import org.apache.struts.action.ActionForward; /* 14: */ import org.apache.struts.action.ActionMapping; /* 15: */ /* 16: */ public class AnalyticsAction /* 17: */ extends Action /* 18: */ { /* 19: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) /* 20: */ throws Exception /* 21: */ { /* 22:26 */ String forward = "success"; /* 23: */ /* 24:28 */ AnalyticsDAO analyticsDAO = new AnalyticsDAO(); /* 25: */ /* 26:30 */ analyticsDAO.getClass();int ie7Count = analyticsDAO.getBrowserWiseUsers("%MSIE 7.0%", null, null); /* 27:31 */ analyticsDAO.getClass();int ie8Count = analyticsDAO.getBrowserWiseUsers("%MSIE 8.0%", null, null); /* 28:32 */ analyticsDAO.getClass();int ie9Count = analyticsDAO.getBrowserWiseUsers("%MSIE 9.0%", null, null); /* 29:33 */ analyticsDAO.getClass();int ie10Count = analyticsDAO.getBrowserWiseUsers("%MSIE 10.0%", null, null); /* 30:34 */ analyticsDAO.getClass();int firefoxCount = analyticsDAO.getBrowserWiseUsers("%Firefox%", null, null); /* 31:35 */ analyticsDAO.getClass();int chromeCount = analyticsDAO.getBrowserWiseUsers("%Chrome%", null, null); /* 32:36 */ analyticsDAO.getClass();int safariCount = analyticsDAO.getBrowserWiseUsers("%Safari%", null, null); /* 33:37 */ analyticsDAO.getClass();int operaCount = analyticsDAO.getBrowserWiseUsers("%Opera%", null, null); /* 34:38 */ analyticsDAO.getClass();int iphoneCount = analyticsDAO.getBrowserWiseUsers("%iPhone%", null, null); /* 35:39 */ analyticsDAO.getClass();int ipadCount = analyticsDAO.getBrowserWiseUsers("%iPad%", null, null); /* 36:40 */ analyticsDAO.getClass();int ipodCount = analyticsDAO.getBrowserWiseUsers("%iPod%", null, null); /* 37:41 */ analyticsDAO.getClass();int androidCount = analyticsDAO.getBrowserWiseUsers("%Android%", null, null); /* 38: */ /* 39:43 */ request.setAttribute("ie7Count", Integer.valueOf(ie7Count)); /* 40:44 */ request.setAttribute("ie8Count", Integer.valueOf(ie8Count)); /* 41:45 */ request.setAttribute("ie9Count", Integer.valueOf(ie9Count)); /* 42:46 */ request.setAttribute("ie10Count", Integer.valueOf(ie10Count)); /* 43:47 */ request.setAttribute("firefoxCount", Integer.valueOf(firefoxCount)); /* 44:48 */ request.setAttribute("chromeCount", Integer.valueOf(chromeCount)); /* 45:49 */ request.setAttribute("safariCount", Integer.valueOf(safariCount)); /* 46:50 */ request.setAttribute("operaCount", Integer.valueOf(operaCount)); /* 47:51 */ request.setAttribute("iphoneCount", Integer.valueOf(iphoneCount)); /* 48:52 */ request.setAttribute("ipadCount", Integer.valueOf(ipadCount)); /* 49:53 */ request.setAttribute("ipodCount", Integer.valueOf(ipodCount)); /* 50:54 */ request.setAttribute("androidCount", Integer.valueOf(androidCount)); /* 51: */ /* 52:56 */ ArrayList<PageDTO> adminPageCountList = analyticsDAO.getAdminPageWiseUsers(null, null, null); /* 53:57 */ request.setAttribute("adminPageCountList", adminPageCountList); /* 54: */ /* 55:59 */ ArrayList<PageDTO> candPageCountList = analyticsDAO.getCandidatePageWiseUsers(null, null, null); /* 56:60 */ request.setAttribute("candPageCountList", candPageCountList); /* 57: */ /* 58:62 */ ErrorLogDAO errorLogDAO = new ErrorLogDAO(); /* 59:63 */ int jspCount = errorLogDAO.getTypewiseCount("JSP", null, null); /* 60:64 */ int javaCount = errorLogDAO.getTypewiseCount("Java", null, null); /* 61: */ /* 62:66 */ request.setAttribute("jspCount", Integer.valueOf(jspCount)); /* 63:67 */ request.setAttribute("javaCount", Integer.valueOf(javaCount)); /* 64: */ /* 65:69 */ ActivationImplementor actImpl = new ActivationImplementor(); /* 66:70 */ List<?> actadminList = actImpl.getActivatedAdminList(); /* 67:71 */ List<?> deactadminList = actImpl.getDeactivatedAdminList(); /* 68: */ /* 69:73 */ int activatedUsers = actadminList.size(); /* 70:74 */ int inactivatedUsers = deactadminList.size(); /* 71:75 */ int deletedUsers = 0; /* 72: */ /* 73:77 */ request.setAttribute("activatedUsers", Integer.valueOf(activatedUsers)); /* 74:78 */ request.setAttribute("inactivatedUsers", Integer.valueOf(inactivatedUsers)); /* 75:79 */ request.setAttribute("deletedUsers", Integer.valueOf(deletedUsers)); /* 76: */ /* 77:81 */ return mapping.findForward(forward); /* 78: */ } /* 79: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.analytics.action.AnalyticsAction * JD-Core Version: 0.7.0.1 */
/* * Copyright 2009 Kjetil Valstadsve * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package vanadis.extrt; import vanadis.core.reflection.Invoker; import vanadis.ext.Inject; import vanadis.osgi.Reference; import java.lang.reflect.Field; final class FieldInjector<T> extends AccessibleInjector<T> { private final Field field; FieldInjector(FeatureAnchor<T> featureAnchor, Field field, Inject annotation, InjectionListener listener) { super(featureAnchor.asRequired(annotation.required()), annotation, false, field.getType().equals(Reference.class), listener); this.field = field; } @Override protected void performInject(Reference<T> reference, T service) { Invoker.assign(this, getManaged(), field, isPassReference() ? reference : service); } @Override protected void performUninject(Reference<T> reference, T service) { Invoker.assign(this, getManaged(), field, null); } }
package lookup; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sql.rowset.CachedRowSet; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Execution; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.event.ForwardEvent; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Button; import org.zkoss.zul.Hbox; import org.zkoss.zul.Label; import org.zkoss.zul.Listbox; import org.zkoss.zul.Listcell; import org.zkoss.zul.Listhead; import org.zkoss.zul.Listheader; import org.zkoss.zul.Listitem; import org.zkoss.zul.Textbox; import org.zkoss.zul.Vbox; import org.zkoss.zul.Window; import services.ChangeStatusService; import services.GeneralService; import services.pivot.PivotService; import util.MessageUtil; import util.SessionUtil; import util.StringUtil; public class LookUpPivot extends GenericForwardComposer { static HashMap<String,String> headerLabel; static{ headerLabel=new HashMap<String, String>(); headerLabel.put("name", "name"); } Window winLookUpSavedPivot; Button btnCancel; String userId; public void doAfterCompose(Component win) throws Exception{ super.doAfterCompose(win); //input userId=(String)Executions.getCurrent().getArg().get("userId"); // system.out.println("Pivot lookup userid: "+userId); //default id (no item selected) winLookUpSavedPivot.setAttribute("id", ""); createtemplateBox(); } List<Map<String, Object>> templateList, searchTemplate,searchTemplateMap; String[] templateHeaders; Listbox box; Button btnSearch; private void createtemplateBox() { //baris ini adalah baris untuk mengambil datanya CachedRowSet mpCr = GeneralService.getChachedRowSetFromQuery("select id,name from d_pivot where user_id='" + userId +"'"); templateHeaders = GeneralService.getColumnNamesFromRowSet(mpCr); templateList = GeneralService.getMapListFromRowSet(mpCr); try { mpCr.close(); } catch (Exception e) { e.printStackTrace(); } initMPSearchMap(); rendertemplateBox(templateList); } private void rendertemplateBox(List<Map<String, Object>> list) { if (box.getListhead() != null){ box.getListhead().setParent(null); } box.getItems().clear(); if (templateHeaders==null) return; Listcell cell; Listitem item; Listhead head; Listheader header; //render header head = new Listhead(); header = new Listheader("Action"); header.setWidth("100px"); header.setAlign("center"); header.setParent(head); //header labels int i = 0; for(String s: templateHeaders){ // // system.out.println("s: "+s); if (s == null) continue; //kalau kolom id, skip if (s.equalsIgnoreCase("id")) continue; Vbox box = new Vbox(); box.setAlign("left"); box.setWidth("95%"); Label lbHeader = new Label(headerLabel.get(s)); lbHeader.setParent(box); // // Textbox txSearch = new Textbox(); // txSearch.setWidth("100%"); // searchTemplateMap.get(i).put("searchBox", txSearch); // txSearch.setParent(box); header = new Listheader(); header.setAlign("left"); box.setParent(header); header.setParent(head); i++; } head.setParent(box); //render isi for(Map<String,Object> r: list){ item = new Listitem(); item.setAttribute("object", r); cell = new Listcell(); Hbox h = new Hbox(); h.setAlign("left"); Button btnDetail = new Button("Choose"); // btnDetail.setWidth("100px"); btnDetail.addForward("onClick", winLookUpSavedPivot, "onClickSavedPivot", r); btnDetail.setParent(h); // Button btnDel = new Button("Delete"); // btnDel.addForward("onClick", winLookUpSavedPivot, "onDeleteSavedPivot", r); // btnDel.setParent(h); h.setParent(cell); cell.setParent(item); item.setAttribute("object", r); item.setParent(box); for(String key: templateHeaders){ if (key == null) continue; if (key.equalsIgnoreCase("id")) continue; cell = new Listcell(StringUtil.convertObjectToString(r.get(key))); cell.setParent(item); } } // templateBox.setWidth(width+"px"); } private void initMPSearchMap() { searchTemplateMap = new ArrayList<Map<String,Object>>(); Map<String, Object> m; for (int i = 0; i<templateHeaders.length; i++){ m = new HashMap<String, Object>(); searchTemplateMap.add(m); } int i=0; if(templateHeaders!= null){ for (String s: templateHeaders){ //initialize map searchTemplateMap.get(i).put("mapKey", s); i++; } } } public void onOK(){ if (templateList == null || templateList.size() == 0) return; Boolean isContain; searchTemplate = new ArrayList<Map<String,Object>>(); for (Map<String,Object> m: templateList){ isContain = true; for (Map<String, Object> searchMap: searchTemplateMap){ Textbox txKey = (Textbox) searchMap.get("searchBox"); String searchKey = txKey.getValue().toLowerCase(); String mapKey = (String) searchMap.get("mapKey"); String mapData = StringUtil.convertObjectToString(m.get(mapKey)).toLowerCase(); if (!mapData.contains(searchKey)){ isContain = false; break; } } if (isContain){ searchTemplate.add(m); } } rendertemplateBox(searchTemplate); } public void onClickSavedPivot$winLookUpSavedPivot (ForwardEvent fwd){ Map<String,Object> r = (Map<String, Object>) fwd.getOrigin().getData(); String val = (String) r.get("id"); winLookUpSavedPivot.setAttribute("id", val); winLookUpSavedPivot.onClose(); } public void onDeleteSavedPivot$winLookUpSavedPivot (ForwardEvent fwd){ if (!MessageUtil.confirmation("Delete This Pivot?")) return; Map<String,Object> r = (Map<String, Object>) fwd.getOrigin().getData(); String val = (String) r.get("id"); // PivotService.deleteSavedPivotByID(val); createtemplateBox(); } public void onClick$btnCancel (){ winLookUpSavedPivot.onClose(); } }
package com.oobootcamp; public class ParkingDirector { private ParkingManager parkingManager; public ParkingDirector(ParkingManager parkingManager) { this.parkingManager = parkingManager; } public String printReport() { return ReportUtil.printSimpleReport(parkingManager.getReportData()); } }
package sps; public class BST { int data; BST leftNode; BST rightnode; BST root=null; public BST(int item){ data=item; } public BST() { // TODO Auto-generated constructor stub } public void insert(int data){ BST newNode=new BST(data); if(root==null){ root=newNode; } else{ BST current=root; BST parent; while(true){ parent=current; if(data<current.data){ current=current.leftNode; if(current==null){ parent.leftNode=newNode; return; } } else{ current=current.rightnode; if(current==null){ parent.rightnode=newNode; return; } } } } } public void Inorder(BST rootNode){ if(rootNode!=null){ Inorder(rootNode.leftNode); System.out.print(rootNode.data + " "); Inorder(rootNode.rightnode); } } public void Preorder(BST rootNode){ if(rootNode!=null){ System.out.print(rootNode.data + " "); Inorder(rootNode.leftNode); Inorder(rootNode.rightnode); } } public void Postorder(BST rootNode){ if(rootNode!=null){ Inorder(rootNode.leftNode); Inorder(rootNode.rightnode); System.out.print(rootNode.data + " "); } } public BST Search(int data){ BST current=root; while(data != current.data){ if(data<current.data){ current=current.leftNode; } else{ current=current.rightnode; } if(current==null){ return null; } } return current; } public static void main(String[] args) { BST bb=new BST(); bb.insert(54); bb.insert(10); bb.insert(25); bb.insert(5); bb.insert(90); bb.insert(64); bb.Inorder(bb.root); System.out.println(); bb.Preorder(bb.root); System.out.println(); bb.Postorder(bb.root); System.out.println(); System.out.println(bb.Search(90).data); } }
package com.yida.poi; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.yida.utils.DateUtils; import com.yida.utils.StringUtils; /** * 传参的方式可以更优美,时间有了再更新 * * @author 0 * */ public class ExportDoc { private static final Logger LOGGER = LoggerFactory.getLogger(ExportDoc.class); // 文本 public static final Pattern PATTERN_REG_TXT = Pattern.compile("\\{Txt%(.*?)%Txt\\}"); // 图片 public static final Pattern PATTERN_REG_PIC = Pattern.compile("\\{Pic%(.*?)%Pic\\}"); // 表格 public static final Pattern PATTERN_REG_TAB = Pattern.compile("\\{Tab%(.*?)%Tab\\}"); // 列 public static final Pattern PATTERN_REG_COL = Pattern.compile("\\{Col%(.*?)%Col\\}"); /* * 替换模版内容 * * @param templatePath 模板路径 * * @param tempPath 缓存路径 * * @param contentMap key:标识符; value:替换数据 */ public void replaceContent(String templatePath, String tempPath, Map<String, Object> contentMap) throws IOException { FileInputStream in = new FileInputStream(new File(templatePath)); XWPFDocument xwpf = new XWPFDocument(in); try { for (Map.Entry<String, Object> entry : contentMap.entrySet()) { /* * key {Txt%Text%Txt} {Pic%Picture%Pic} {Tab%table%Tab} */ String key = entry.getKey(); Matcher textMatcher = PATTERN_REG_TXT.matcher(key); Matcher picMatcher = PATTERN_REG_PIC.matcher(key); Matcher tabMatcher = PATTERN_REG_TAB.matcher(key); if (textMatcher.find()) { replaceText(xwpf, entry); } if (picMatcher.find()) { replacePic(xwpf, entry); } if (tabMatcher.find()) { replaceTable(xwpf, entry); } } FileOutputStream out = new FileOutputStream(tempPath); try { xwpf.write(out); } finally { xwpf.close(); } } catch (Exception e) { LOGGER.error("Word文档生成出错:", e); throw e; } finally { xwpf.close(); } } @SuppressWarnings({ "unchecked" }) private void replaceTable(XWPFDocument doc, Entry<String, Object> entry) { List<XWPFTable> tables = doc.getTables(); List<Map<String, Object>> records = null; for (XWPFTable table : tables) { List<XWPFTableRow> rows = table.getRows(); int rowCount = rows.size(); for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { // 表名配置信息 String cellContent = rows.get(rowIndex).getCell(0).getText(); Matcher matcher = PATTERN_REG_TAB.matcher(cellContent); if (matcher.find()) { String k = entry.getKey(); if (k.equals(cellContent)) { records = (List<Map<String, Object>>) entry.getValue(); // 列配置信息 if (rowIndex + 1 < rowCount) { XWPFTableRow xwpfTableRow = rows.get(rowIndex + 1); List<XWPFTableCell> tableCells = xwpfTableRow.getTableCells(); int colCount = tableCells.size(); CTTcPr[] tcPrs = new CTTcPr[colCount]; String[] colNames = new String[colCount]; CTPPr[] pPrs = new CTPPr[colCount]; CTRPr[] rPrs = new CTRPr[colCount]; for (int colIndex = 0; colIndex < colCount; colIndex++) { XWPFTableCell xwpfTableCell = tableCells.get(colIndex); XWPFParagraph paragraph = xwpfTableCell.getParagraphs().get(0); String text = paragraph.getText(); Matcher mCol = PATTERN_REG_COL.matcher(text); if (mCol.find()) { String colName = mCol.group(1).trim(); tcPrs[colIndex] = xwpfTableCell.getCTTc().getTcPr(); colNames[colIndex] = colName; pPrs[colIndex] = paragraph.getCTP().getPPr(); XWPFRun xwpfRun = paragraph.getRuns().get(0); rPrs[colIndex] = xwpfRun.getCTR().getRPr(); } } for (int i = 0; i < records.size(); i++) { Map<String, Object> map1 = records.get(i); XWPFTableRow newRow = table.createRow(); for (int j = 0; j < colNames.length; j++) { String key = colNames[j]; if (StringUtils.isEmpty(key)) { continue; } String value = map1.get(key) == null ? "" : map1.get(key).toString(); XWPFTableCell cell = newRow.getCell(j); cell.getCTTc().setTcPr(tcPrs[j]); XWPFParagraph newParagraph = cell.getParagraphs().get(0); newParagraph.getCTP().setPPr(pPrs[j]); XWPFRun createRun = newParagraph.createRun(); createRun.getCTR().setRPr(rPrs[j]); createRun.setText(value); } } } } table.removeRow(rowIndex + 1); table.removeRow(rowIndex); break; } } } } /* * 替换图片:获取段落所有文本,一次性替换内容,因为poi会出现分段落混乱的情况 */ private void replacePic(XWPFDocument xwpf, Entry<String, Object> entry) { String replaceKey = null; Iterator<XWPFParagraph> itPara = xwpf.getParagraphsIterator(); try { while (itPara.hasNext()) { XWPFParagraph paragraph = (XWPFParagraph) itPara.next(); List<XWPFRun> runs = paragraph.getRuns(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < runs.size(); i++) { XWPFRun run = runs.get(i); int pos = run.getTextPosition(); sb.append(run.getText(pos)); } replaceKey = entry.getKey(); String str = sb.toString(); boolean contains = str.contains(replaceKey); if (contains) { for (int i = 0; i < runs.size(); i++) { XWPFRun run = runs.get(i); run.setText("", 0); } String regex = StringUtils.string2RegExp(replaceKey); String[] split = str.replaceAll(regex, "," + regex + ",").split(","); for (int i = 0; i < split.length; i++) { String string = split[i]; if (!StringUtils.isEmpty(split[i])) { if (string.equals(replaceKey)) { String imgPath = entry.getValue().toString(); int format = getImgFormat(imgPath); paragraph.createRun().addPicture(new FileInputStream(imgPath), format, imgPath, Units.toEMU(415), Units.toEMU(253)); } else { paragraph.createRun().setText(split[i]); } } } } } } catch (Exception e) { e.printStackTrace(); } } /** * 获取图片格式 * * @param imgFile * @return */ private int getImgFormat(String imgFile) { int format; if (imgFile.endsWith(".emf")) { format = XWPFDocument.PICTURE_TYPE_EMF; } else if (imgFile.endsWith(".wmf")) { format = XWPFDocument.PICTURE_TYPE_WMF; } else if (imgFile.endsWith(".pict")) { format = XWPFDocument.PICTURE_TYPE_PICT; } else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) { format = XWPFDocument.PICTURE_TYPE_JPEG; } else if (imgFile.endsWith(".png")) { format = XWPFDocument.PICTURE_TYPE_PNG; } else if (imgFile.endsWith(".dib")) { format = XWPFDocument.PICTURE_TYPE_DIB; } else if (imgFile.endsWith(".gif")) { format = XWPFDocument.PICTURE_TYPE_GIF; } else if (imgFile.endsWith(".tiff")) { format = XWPFDocument.PICTURE_TYPE_TIFF; } else if (imgFile.endsWith(".eps")) { format = XWPFDocument.PICTURE_TYPE_EPS; } else if (imgFile.endsWith(".bmp")) { format = XWPFDocument.PICTURE_TYPE_BMP; } else if (imgFile.endsWith(".wpg")) { format = XWPFDocument.PICTURE_TYPE_WPG; } else { throw new RuntimeException("不支持的图片格式。"); } return format; } /* * 替换文本内容:获取段落所有文本,一次性替换内容,因为poi会出现分段落混乱的情况 */ private void replaceText(XWPFDocument xwpf, Entry<String, Object> entry) { String replaceKey = null; Iterator<XWPFParagraph> itPara = xwpf.getParagraphsIterator(); try { replaceKey = entry.getKey(); while (itPara.hasNext()) { XWPFParagraph paragraph = (XWPFParagraph) itPara.next(); List<XWPFRun> runs = paragraph.getRuns(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < runs.size(); i++) { XWPFRun run = runs.get(i); int pos = run.getTextPosition(); sb.append(run.getText(pos)); } String str = sb.toString(); boolean contains = str.contains(replaceKey); if (contains) { for (int i = 0; i < runs.size(); i++) { XWPFRun run = runs.get(i); run.setText("", 0); } String regex = StringUtils.string2RegExp(replaceKey); String replaceAll = sb.toString().replaceAll(regex, entry.getValue().toString()); if (runs.size() > 0) { runs.get(0).setText(replaceAll); } } } } catch (Exception e) { LOGGER.error("Word文档生成出错:", e); throw e; } } public static void main(String[] args) { String ss = "这是一整{Txt%Text%Txt}"; String aa = "{Txt%Text%Txt}"; System.out.println(ss.contains(aa)); } /* * 通过字段类型控制数据输出格式 * * @param dataset 数据集 * * @param headers 需要设置的字段集合 * * @return */ public List<Map<String, Object>> setDataFormatByFieldType(List<Map<String, Object>> dataset, List<Map<String, String>> headers) { for (Map<String, Object> dataMap : dataset) { for (Map<String, String> typeMap : headers) { String field = typeMap.get("field"); String fieldType = typeMap.get("fieldType"); String value = dataMap.get(field) == null ? "" : dataMap.get(field).toString(); if ("number".equals(fieldType)) {// 数字类型 if ("".equals(value)) { value = "0"; } dataMap.put(field, value); } else if ("isThrough".equals(fieldType)) {// 状态码转描述 if ("0".equals(value)) { value = "不可通行"; } else if ("1".equals(value)) { value = "可通行"; } dataMap.put(field, value); } else if ("date".equals(fieldType)) {// 无时分秒的日期格式 value = DateUtils.formatDate(new Date(Long.valueOf(value)), DateUtils.DATE_FORMAT); dataMap.put(field, value); } else if ("datetime".equals(fieldType)) {// 包涵时分秒的日期格式 value = DateUtils.formatDate(new Date(Long.valueOf(value)), DateUtils.DATE_TIME24_FORMAT); dataMap.put(field, value); } } } return dataset; } }
package com.dais.service.impl; import com.common.constant.FilePathConstant; import com.common.pojo.ResultModel; import com.common.utils.*; import com.common.utils.Utils; import com.dais.mapper.FvirtualcointypeMapper; import com.dais.mapper.UserMapper; import com.dais.model.*; import com.dais.service.CommonParamsService; import com.dais.service.FvirtualaddressService; import com.dais.service.FvirtualwalletService; import com.dais.service.UserService; import com.dais.utils.*; import com.dais.utils.DateUtils; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.sql.Timestamp; import java.util.*; import static com.common.utils.HashUtil.encodePassword; /** * @author xxp * @version 2017- 08- 08 20:54 * @description * @copyright www.zhgtrade.com */ @Service public class UserServiceImpl implements UserService { private static Logger logger = Logger.getLogger(UserServiceImpl.class); @Autowired private CommonParamsService commonParamsService; @Autowired private UserMapper userMapper; @Autowired private JedisClient jedisClient; @Autowired private FvirtualaddressService fvirtualaddressService; @Autowired private FvirtualcointypeMapper fvirtualcointypeMapper; @Autowired private FvirtualwalletService fvirtualwalletService; @Value("${REGISTER_CODE_KEY}") private String REGISTER_CODE_KEY; @Value("${REGISTER_CODE_EXPIRE}") private Integer REGISTER_CODE_EXPIRE; @Value("${REDIS_USER_SESSION_KEY}") private String REDIS_USER_SESSION_KEY; @Value("${SSO_SESSION_EXPIRE}") private Integer SSO_SESSION_EXPIRE; @Override public ResultModel createUser(User user, String authCode) { String loginName = user.getFloginName(); String md5Password = encodePassword(user.getFloginPassword()); UserExample example = new UserExample(); UserExample.Criteria criteria = example.createCriteria(); criteria.andFloginNameEqualTo(loginName); List<User> users = userMapper.selectByExample(example); if(users != null && users.size() > 0){ return ResultModel.build(403,"手机号码已被注册"); } String serverCode = jedisClient.get(REGISTER_CODE_KEY + ":" + user.getFloginName()); if(authCode != null && !authCode.equals(serverCode)){ return ResultModel.build(403,"验证码错误"); } if(user.getFnickName() == null){ user.setFnickName("d_"+user.getFloginName().substring(7)); } user.setFtelePhone(loginName); user.setFregisterTime(new Date()); //md5加密 user.setFloginPassword(md5Password); user.setHasPayPwd(false); user.setFpostRealValidate(false); user.setFisMailValidate(false); user.setFisTelephoneBind(true); user.setFhasRealValidate(false); user.setMemWords(MemWordsUtil.createMemWords()); userMapper.insertSelective(user); users = userMapper.selectByExample(example); if(CollectionUtils.isEmpty(users)){ return ResultModel.build(500,"数据异常"); } /*//为用户生成比特币钱包和以太坊钱包 List<Fvirtualcointype> fcctList = fvirtualcointypeMapper.selectByExample(new FvirtualcointypeExample()); for(Fvirtualcointype fvirtualcointype : fcctList) { if(!"ETH".equals(fvirtualcointype.getFshortname()) && !"BTC".equals(fvirtualcointype.getFshortname())) continue; try { fvirtualaddressService.updateAssignWalletAddress(users.get(0).getFid(),fvirtualcointype.getFid()); fvirtualwalletService.insertFvirtualwallet(users.get(0).getFid(),fvirtualcointype.getFid()); } catch (Exception e) { e.printStackTrace(); return ResultModel.build(500,"数据异常"); } }*/ return ResultModel.ok(); } @Override public ResultModel updateWallatOrAddress(Integer userid, Integer symbol,String type) throws Exception { //type is open or off try { Fvirtualwallet fvirtualwallet = fvirtualwalletService.selectFvirtualwallet(userid,symbol); if("off".equals(type)){//钱包存在时的关闭开关 if(fvirtualwallet != null && fvirtualwallet.getIshow()){ fvirtualwallet.setIshow(false); fvirtualwalletService.updateFvirtualwallet(fvirtualwallet); return ResultModel.ok(); } return ResultModel.build(403,"无效的操作"); } if("open".equals(type)){ if(fvirtualwallet != null){ if(!fvirtualwallet.getIshow()){ fvirtualwallet.setIshow(true); fvirtualwalletService.updateFvirtualwallet(fvirtualwallet); return ResultModel.ok(); } return ResultModel.build(403,"无效的操作"); } //下面情况说明用户还没有创建钱包 Fvirtualcointype fvirtualcointype = this.fvirtualcointypeMapper.selectByPrimaryKey(symbol); Fvirtualaddress fvirtualaddress = fvirtualaddressService.selectFvirtualAddress(userid,fvirtualcointype.getParentid()); if(fvirtualaddress == null){ fvirtualaddressService.updateAssignWalletAddress(userid,symbol); } fvirtualwalletService.insertFvirtualwallet(userid,symbol); return ResultModel.ok(); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } return ResultModel.build(403,"无效的操作"); } @Override public ResultModel getUserList(int start, int limit, String search) { UserExample example = new UserExample(); UserExample.Criteria criteria = new UserExample().createCriteria(); if(org.apache.commons.lang.StringUtils.isNotBlank(search)){ criteria.andFnickNameLike("%"+search+"%"); example.or(criteria); criteria = new UserExample().createCriteria(); criteria.andFloginNameLike("%"+search+"%"); example.or(criteria); criteria = new UserExample().createCriteria(); criteria.andFrealNameLike("%"+search+"%"); example.or(criteria); } PageHelper.startPage(start, limit); example.setOrderByClause(" fregister_time desc"); List<User> paramList = this.userMapper.selectByExample(example); PageInfo<User> pageInfo = new PageInfo<>(paramList); return ResultModel.build(200, "OK", pageInfo); } @Override public ResultModel userLogin(String phone, String password) { UserExample example = new UserExample(); UserExample.Criteria criteria = example.createCriteria(); criteria.andFloginNameEqualTo(phone); List<User> list = userMapper.selectByExample(example); //如果没有此用户名 if (CollectionUtils.isEmpty(list)) { return ResultModel.build(400, "用户名不存在"); } User user = list.get(0); for (User nowUser : list) { if (nowUser.getWalletStatus() == 1){ user = nowUser; break; } } //说明所有钱包已禁用 if (user == null){ user = list.get(0); } //比对密码 if (!encodePassword(password).equals(user.getFloginPassword())){ return ResultModel.build(400, "手机号或密码错误"); } //清除原来的token,保证mysql中的token和redis中的一直,并且只能同时存在一个用户登录 this.removeUserByToken(user.getToken()); //生成token String token = UUID.randomUUID().toString(); user.setToken(token); this.updateUser(user,token); return ResultModel.ok(token); } @Override public ResultModel getUserByToken(String token) { //根据token从redis中查询用户信息 String json = jedisClient.get(REDIS_USER_SESSION_KEY + ":" + token); //判断是否为空 if (StringUtils.isBlank(json)) { return ResultModel.build(400, "此session已经过期,请重新登录"); } //更新过期时间 jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE); // 拼接前端需要的信息 User user = JsonUtils.jsonToPojo(json, User.class); //返回用户信息 return ResultModel.ok(user); } @Override public ResultModel removeUserByToken(String token) { //根据token从redis中查询用户信息 jedisClient.del(REDIS_USER_SESSION_KEY + ":" + token); return ResultModel.build(200, "OK"); } @Override public ResultModel sendAuthenticationCode(String phone) { if(phone != null){ int authenticationCode = (int)((Math.random()*9+1)*100000); logger.info(phone + "的验证码为:" + authenticationCode); String messageName = this.commonParamsService.getValue(ConstantKeys.MESSAGE_NAME); String messagePassword = this.commonParamsService.getValue(ConstantKeys.MESSAGE_PASSWORD); int ret = MessagesUtils.send(messageName,messagePassword,phone,"尊敬的客户,您的验证码为: " + authenticationCode + ",请勿泄漏给他人。"); if(ret == 1){ //把用户登录的验证码写入redis jedisClient.set(REGISTER_CODE_KEY + ":" + phone, authenticationCode + ""); //设置验证码的过期时间 jedisClient.expire(REGISTER_CODE_KEY + ":" + phone, REGISTER_CODE_EXPIRE); logger.debug("短信验证码:"+authenticationCode); return ResultModel.ok(authenticationCode); }else{ return ResultModel.build(500,"短信发送失败!"); } } return ResultModel.build(403,"手机号码不能为空!"); } @Override public User queryUser(String token) { //根据token从redis中查询用户信息 String json = jedisClient.get(REDIS_USER_SESSION_KEY + ":" + token); if(json == null){ return null; } User user = JsonUtils.jsonToPojo(json, User.class); return user; } @Override public User queryUser(int id) { //根据token从redis中查询用户信息 String json = jedisClient.get(id + "_" + id); if(json == null){ return null; } User user = JsonUtils.jsonToPojo(json, User.class); return user; } @Override public User queryUserByLoginName(String loginName) { UserExample example = new UserExample(); example.createCriteria().andFloginNameEqualTo(loginName); return this.userMapper.selectByExample(example).get(0); } @Override public ResultModel updatePassword(String token, String oldPassword, String newPassword,String authCode) { User user = this.queryUser(token); String serverCode = jedisClient.get(REGISTER_CODE_KEY + ":" + user.getFloginName()); if(authCode != null && !authCode.equals(serverCode)){ return ResultModel.build(403,"验证码错误"); } User user2 = userMapper.selectByPrimaryKey(user.getFid()); user2.setFloginPassword(encodePassword(newPassword)); int count = userMapper.updateByPrimaryKeySelective(user2); if(count < 1){ return ResultModel.build(500,"数据异常"); } user2.setFloginPassword(null); this.freshRedisUserInfo(token,user2); return ResultModel.ok(); } @Override public ResultModel updateBindPhone(String token, String newPhone, String authCode) { UserExample example = new UserExample(); example.createCriteria().andFloginNameEqualTo(newPhone); List<User> users = userMapper.selectByExample(example); if(users != null && users.size() > 0){ return ResultModel.build(403,"手机号码已被使用"); } User user = this.queryUser(token); String serverAuthCode = jedisClient.get(REGISTER_CODE_KEY + ":" + newPhone); if(authCode != null && !authCode.equals(serverAuthCode)){ return ResultModel.build(403,"验证码错误"); } user.setFoldLoginName(user.getFloginName()); user.setFloginName(newPhone); user.setFtelePhone(newPhone); int count = userMapper.updateByPrimaryKeySelective(user); if(count == 0){ return ResultModel.build(500,"数据异常"); } // 刷新redis中缓存的用户 this.freshRedisUserInfo(token,user); return ResultModel.ok(); } @Override public ResultModel updateNickName(String token, String nickName) { User user = this.queryUser(token); user.setFnickName(nickName); //只修改当前提交字段 User user2 = new User(); user2.setFid(user.getFid()); user2.setFnickName(user.getFnickName()); int count = userMapper.updateByPrimaryKeySelective(user2); if(count == 0){ return ResultModel.build(500,"数据异常"); } this.freshRedisUserInfo(token,user); return ResultModel.ok(nickName); } /** * 用户找回密码 * @param phone * @param authCode * @param newPassword * @return */ @Override public ResultModel updateResetPassword(String phone, String authCode, String newPassword) { UserExample example = new UserExample(); UserExample.Criteria criteria = example.createCriteria(); criteria.andFloginNameEqualTo(phone); //后续需要考虑用户系统 List<User> userList = userMapper.selectByExample(example); if(CollectionUtils.isEmpty(userList)){ return ResultModel.build(403,"该手机号没有注册"); } String serverCode = jedisClient.get(REGISTER_CODE_KEY + ":" + phone); if(authCode != null && !authCode.equals(serverCode)){ return ResultModel.build(403,"验证码错误"); } User user = userList.get(0); user.setFloginPassword(encodePassword(newPassword)); userMapper.updateByPrimaryKeySelective(user); return ResultModel.ok(); } @Override public ResultModel setTradePassword(String token,String tradePassword,String authCode) { User user = this.queryUser(token); User user2 = userMapper.selectByPrimaryKey(user.getFid()); String md5Password = HashUtil.encodePassword(tradePassword); if(user2.getFloginPassword().equals(md5Password)){ return ResultModel.build(403,"交易密码不能登录密码相同"); } user.setFtradePassword(md5Password); user.setHasPayPwd(true); int count = userMapper.updateByPrimaryKeySelective(user); if(count < 1){ return ResultModel.build(500,"数据异常"); } user.setFtradePassword(null); this.freshRedisUserInfo(token,user); return ResultModel.ok(); } @Override public ResultModel createWallet(String token, String memWords) { User user = this.queryUser(token); User user2 = userMapper.selectByPrimaryKey(user.getFid()); if(user.getWalletStatus() == 1){ return ResultModel.build(403,"已经存在钱包,不能再次创建"); } String temp = jedisClient.get("mem:"+user.getFid() + ":key"); if(!memWords.trim().equals(temp)){ return ResultModel.build(403,"助记词不正确"); } user2.setHasPayPwd(true); List<Fvirtualwallet> fvirtualwallets = this.fvirtualwalletService.listFvirtualwallet(user.getFid()); if(CollectionUtils.isEmpty(fvirtualwallets)){ user2.setWalletStatus(1); userMapper.updateByPrimaryKeySelective(user2); //为用户生成比特币钱包和以太坊钱包 creteWallet(user); }else { //钱包处于删除状态,此时用户创建钱包需要copy一条用户信息 if(user2.getWalletStatus() == 2){ user.setToken(com.dais.utils.Utils.getMD5_32(new Date().getTime()+"")); this.userMapper.updateByPrimaryKeySelective(user); user2.setFid(null); user2.setWalletStatus(1); user2.setMemWords(temp); user2.setFtradePassword(jedisClient.get("password:"+user.getFid() + ":key")); this.userMapper.insertSelective(user2); creteWallet(user2); } } user.setFtradePassword(null); this.freshRedisUserInfo(user2.getToken(),user2); return ResultModel.ok(); } private void creteWallet(User user){ List<Fvirtualcointype> fcctList = fvirtualcointypeMapper.selectByExample(new FvirtualcointypeExample()); for(Fvirtualcointype fvirtualcointype : fcctList) { if(!"ETH".equals(fvirtualcointype.getFshortname()) && !"BTC".equals(fvirtualcointype.getFshortname())) continue; try { fvirtualaddressService.updateAssignWalletAddress(user.getFid(),fvirtualcointype.getFid()); fvirtualwalletService.insertFvirtualwallet(user.getFid(),fvirtualcointype.getFid()); } catch (Exception e) { e.printStackTrace(); } } } @Override public ResultModel validateOldPhone(String token, String authCode) { User user = this.queryUser(token); if(user == null){ return ResultModel.build(401,"验证失败!"); } String serverAuthCode = jedisClient.get(REGISTER_CODE_KEY + ":" + user.getFloginName()); if(serverAuthCode == null){ return ResultModel.build(403,"验证码超时!"); } if(!serverAuthCode.equals(authCode)){ return ResultModel.build(403,"验证码错误!"); } return ResultModel.ok(); } @Override public User findByUserId(int userId) { return userMapper.selectByPrimaryKey(userId); } @Override public ResultModel updateUser(User user,String token) { if(user == null){ return ResultModel.build(500,"数据异常"); } int count = userMapper.updateByPrimaryKeySelective(user); if(count == 0){ return ResultModel.build(500,"数据异常"); } // 刷新redis中缓存的用户 this.freshRedisUserInfo(token,user); return ResultModel.ok(); } @Override public ResultModel commonUploadHeadImg(String token, MultipartFile multipartFile) throws IOException{ if(null == multipartFile){ // 上传文件不存在 return ResultModel.build(101,"上传文件不存在"); }else if(multipartFile.getSize() > 3 * 1024 * 1024){ // 上传文件过大 return ResultModel.build(102,"上传文件超过3M"); }else{ byte[] bytes = multipartFile.getBytes(); if(!Utils.isImage(bytes)){ // 不是有效图片文件 return ResultModel.build(103,"不是有效图片文件"); }else{ String ext = Utils.getFilenameExtension(multipartFile.getOriginalFilename()); String filePath = FilePathConstant.HeadImgDirectory + Utils.getRelativeFilePath(ext, bytes); boolean flag = Utils.uploadFileToOss(multipartFile.getInputStream(), filePath); if(flag){ User user = this.queryUser(token); if(user == null){ return ResultModel.build(500,"数据异常"); } user.setFheadImgUrl(filePath); user.setFlastUpdateTime(new Timestamp(System.currentTimeMillis())); int count = userMapper.updateByPrimaryKeySelective(user); if(count == 0){ return ResultModel.build(500,"数据异常"); } this.freshRedisUserInfo(token,user); return ResultModel.ok(filePath); }else{ // 上传失败 return ResultModel.build(500,"上传失败"); } } } } @Override public ResultModel commonUploadAuthImg(String token, MultipartFile multipartFile) throws IOException { if(null == multipartFile){ // 上传文件不存在 return ResultModel.build(101,"上传文件不存在"); }else if(multipartFile.getSize() > 3 * 1024 * 1024){ // 上传文件过大 return ResultModel.build(102,"上传文件超过3M"); }else{ byte[] bytes = multipartFile.getBytes(); if(!Utils.isImage(bytes)){ // 不是有效图片文件 return ResultModel.build(103,"不是有效图片文件"); }else{ User user = this.queryUser(token); String ext = Utils.getFilenameExtension(multipartFile.getOriginalFilename()); String filePath = FilePathConstant.IdentityPicDirectory + Utils.getRelativeFilePath(ext, bytes, user.getFid()); boolean flag = Utils.uploadFileToOss(multipartFile.getInputStream(), filePath); if(flag){ return ResultModel.ok(filePath); }else{ // 上传失败 return ResultModel.build(500,"上传失败"); } } } } @Override public User selectByExampe(UserExample example) { List<User> list = this.userMapper.selectByExample(example); if (CollectionUtils.isEmpty(list)){ return null; } return list.get(0); } private void freshRedisUserInfo(String token,User user){ user.setFloginPassword(null); user.setFtradePassword(null); user.setMemWords(null); // 刷新redis中缓存的用户 jedisClient.set(REDIS_USER_SESSION_KEY + ":" + token, JsonUtils.objectToJson(user)); //设置session的过期时间 jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE); jedisClient.set(user.getFid()+"_"+user.getFid(),JsonUtils.objectToJson(user)); } }
package com.website.views.pages; import javax.enterprise.context.RequestScoped; import javax.inject.Named; import com.website.views.WebPages; /** * The view for the home web page.</br> * This {@link Named} class is bound with the same named xhtml file. * * @author Jérémy Pansier */ @Named @RequestScoped public class Home { /** The web page. */ public static final WebPages WEB_PAGE = WebPages.HOME; /** * @return the web page */ public WebPages getWebPage() { return WEB_PAGE; } }
package com.deltastuido.user; import java.io.Serializable; import javax.persistence.*; import java.sql.Timestamp; import java.time.Instant; /** * The persistent class for the site_user_group database table. * */ @Entity @Table(name="user_groups") @NamedQuery(name="UserGroup.findAll", query="SELECT s FROM UserGroup s") public class UserGroup implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId private UserGroupPK id; @Column(name="time_joined") private Timestamp timeJoined = Timestamp.from(Instant.now()); public UserGroup() { //for jpa } public UserGroup(String userId, String group) { this.id = new UserGroupPK(userId, group); } public UserGroupPK getId() { return this.id; } public void setId(UserGroupPK id) { this.id = id; } public Timestamp getTimeJoined() { return this.timeJoined; } public void setTimeJoined(Timestamp timeJoined) { this.timeJoined = timeJoined; } }
public class Conta { private double saldo; public void atualiza(double taxa){ synchronized (this) { double saldoAtualiza = this.saldo * (1 + taxa); this.saldo = saldoAtualiza; } } public void deposita(double valor){ synchronized (this) { double novoSaldo = this.saldo + valor; this.saldo = novoSaldo; } } }