blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
c809548fe9e676499089cb72c71c0452394b7fdc
Java
igoryavk/web333
/src/main/java/web/Config.java
UTF-8
643
2.078125
2
[]
no_license
package web; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; @Configuration public class Config { @Bean public DataSource getDataSource(){ DriverManagerDataSource dataSource=new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUrl("jdbc:postgresql://35.226.23.157/mybase"); dataSource.setUsername("spring"); dataSource.setPassword("yavkin85"); return dataSource; } }
true
8ace73f1b25be27da2823398ff22b872f2aba753
Java
tobega/tailspin-v0
/src/tailspin/matchers/composer/CaptureSubComposer.java
UTF-8
1,186
2.4375
2
[ "MIT" ]
permissive
package tailspin.matchers.composer; import tailspin.control.Value; import tailspin.interpreter.Scope; public class CaptureSubComposer implements SubComposer { private final String identifier; private final Scope scope; private final SubComposer subComposer; private boolean satisfied = false; CaptureSubComposer(String identifier, Scope scope, SubComposer subComposer) { this.identifier = identifier; this.scope = scope; this.subComposer = subComposer; } @Override public Memo nibble(String s, Memo memo) { memo = subComposer.nibble(s, memo); checkSatisfaction(); return memo; } private void checkSatisfaction() { satisfied = subComposer.isSatisfied(); if (subComposer.isSatisfied()) { Object result = Value.oneValue(subComposer.getValues()); scope.defineValue(identifier, result); } } @Override public Memo backtrack(String s, Memo memo) { scope.undefineValue(identifier); memo = subComposer.backtrack(s, memo); checkSatisfaction(); return memo; } @Override public Object getValues() { return null; } @Override public boolean isSatisfied() { return satisfied; } }
true
ac6d9860f0cc226414311f5b21c8c0062388f029
Java
SXiang/JUnitWebTest
/selenium-wd/tests/surveyor/dataaccess/source/StoredProcComplianceGetGaps.java
UTF-8
5,741
2.125
2
[]
no_license
package surveyor.dataaccess.source; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.sql.CallableStatement; import common.source.Log; public class StoredProcComplianceGetGaps extends BaseEntity { private String rowNumber; private String colA; private String colB; private String colC; private String colD; private String colE; private String colF; private String colG; private String colH; private String colI; private String colJ; private String colK; private String colL; public StoredProcComplianceGetGaps() { super(); } @Override public String toString() { return this.getColA().concat(this.getColB().concat(this.getColC()).concat(this.getColD()).concat(this.getColE()).concat(this.getColF()).concat(this.getColG()).concat(this.getColH()).concat(this.getColI()).concat(this.getColJ()).concat(this.getColK()).concat(this.getColL())); } @Override public boolean equals(Object obj){ if (!(obj instanceof StoredProcComplianceGetGaps)) { return false; } StoredProcComplianceGetGaps gaps = (StoredProcComplianceGetGaps) obj; return this.toString().equals(gaps.toString()); } @Override public int hashCode(){ return this.toString().hashCode(); } public String getRowNumber() { String returnVal = (rowNumber != null) ? rowNumber : ""; return returnVal; } public void setRowNumber(String rowNumber) { this.rowNumber = rowNumber; } public String getColA() { String returnVal = (colA != null) ? colA : ""; return returnVal; } public void setColA(String colA) { this.colA = colA; } public String getColB() { String returnVal = (colB != null) ? colB : ""; return returnVal; } public void setColB(String colB) { this.colB = colB; } public String getColC() { String returnVal = (colC != null) ? colC : ""; return returnVal; } public void setColC(String colC) { this.colC = colC; } public String getColD() { String returnVal = (colD != null) ? colD : ""; return returnVal; } public void setColD(String colD) { this.colD = colD; } public String getColE() { String returnVal = (colE != null) ? colE : ""; return returnVal; } public void setColE(String colE) { this.colE = colE; } public String getColF() { String returnVal = (colF != null) ? colF : ""; return returnVal; } public void setColF(String colF) { this.colF = colF; } public String getColG() { String returnVal = (colG != null) ? colG : ""; return returnVal; } public void setColG(String colG) { this.colG = colG; } public String getColH() { String returnVal = (colH != null) ? colH : ""; return returnVal; } public void setColH(String colH) { this.colH = colH; } public String getColI() { String returnVal = (colI != null) ? colI : ""; return returnVal; } public void setColI(String colI) { this.colI = colI; } public String getColJ() { String returnVal = (colJ != null) ? colJ : ""; return returnVal; } public void setColJ(String colJ) { this.colJ = colJ; } public String getColK() { String returnVal = (colK != null) ? colK : ""; return returnVal; } public void setColK(String colK) { this.colK = colK; } public String getColL() { String returnVal = (colL != null) ? colL : ""; return returnVal; } public void setColL(String colL) { this.colL = colL; } public ArrayList<StoredProcComplianceGetGaps> get(String reportId) { ArrayList<StoredProcComplianceGetGaps> objReportList = load(reportId); return objReportList; } public static ArrayList<StoredProcComplianceGetGaps> getReportGaps(String reportId) { ArrayList<StoredProcComplianceGetGaps> objStoredProcComplianceGetGaps = new StoredProcComplianceGetGaps().get(reportId); return objStoredProcComplianceGetGaps; } private StoredProcComplianceGetGaps loadFrom(ResultSet resultSet) { StoredProcComplianceGetGaps objGap = new StoredProcComplianceGetGaps(); try { objGap.setRowNumber(resultSet.getString("RowNumber")); objGap.setColA(resultSet.getString("ColA")); objGap.setColB(resultSet.getString("ColB")); objGap.setColC(resultSet.getString("ColC")); objGap.setColD(resultSet.getString("ColD")); objGap.setColE(resultSet.getString("ColE")); objGap.setColF(resultSet.getString("ColF")); objGap.setColG(resultSet.getString("ColG")); objGap.setColH(resultSet.getString("ColH")); objGap.setColI(resultSet.getString("ColI")); objGap.setColJ(resultSet.getString("ColJ")); objGap.setColK(resultSet.getString("ColK")); objGap.setColL(resultSet.getString("ColL")); } catch (SQLException e) { Log.error("Class Report | " + e.toString()); } return objGap; } public ArrayList<StoredProcComplianceGetGaps> load(String reportId) { ArrayList<StoredProcComplianceGetGaps> objGapList = new ArrayList<StoredProcComplianceGetGaps>(); try { CallableStatement cs = connection.prepareCall("{CALL Compliance_Investigation_Assessment_GetGAPData(?)}"); cs.setString(1, reportId); boolean isRS = cs.execute(); boolean keepLooping = true; while (keepLooping) { isRS = cs.getMoreResults(); // This checks to see if there are no more resultsets. if (isRS == false && cs.getUpdateCount() == -1) { break; } if (!isRS) { continue; } resultSet = cs.getResultSet(); if (resultSet == null) { continue; } else { // No reason to loop anymore once the non-empty resultset is found. keepLooping = false; } while (resultSet.next()) { StoredProcComplianceGetGaps objGap = loadFrom(resultSet); objGapList.add(objGap); } resultSet.close(); } cs.close(); } catch (SQLException e) { Log.error(e.toString()); } return objGapList; } }
true
bbc9ee08b3dbc00589f2a0659defa999706c6015
Java
JianpingZeng/clank
/modules/org.llvm.ir/extra_members/MetadataExtraMembers.java
UTF-8
446
1.601563
2
[]
no_license
protected Metadata() { } protected Metadata(Metadata $Prm0) { this.Storage = $Prm0.Storage; this.SubclassID = $Prm0.SubclassID; this.SubclassData16 = $Prm0.SubclassData16; this.SubclassData32 = $Prm0.SubclassData32; } protected Metadata(JD$Move _dparam, Metadata $Prm0) { this.Storage = $Prm0.Storage; this.SubclassID = $Prm0.SubclassID; this.SubclassData16 = $Prm0.SubclassData16; this.SubclassData32 = $Prm0.SubclassData32; }
true
94a153526e3af8ea6c7e14c920420c3f4f793828
Java
charanshetty/Dev
/MemAllocTechniq_1/src/Buddy_Animation.java
UTF-8
1,896
2.84375
3
[]
no_license
import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import javax.swing.JPanel; public class Buddy_Animation extends JPanel{ ArrayList<Process_Detail> p=new ArrayList<Process_Detail>(); int mem_size; public void paintComponent(Graphics g) { //j.setText("hello"); //g.setColor(Color.BLACK); // g.drawLine(100, 0, 100, 800); // g.drawLine(0, 50, 700, 50); //g.drawLine(0, 120, 700, 120); g.setColor(Color.BLACK); g.drawRect( 100, 50 , mem_size/4, 70); // tot_mem_size... // g.drawRect(100, 50, mem_size/8, 70); // dividing line of memory // f.setVisible(true); g.setColor(Color.BLUE); for(Process_Detail p_info:p) { //System.out.println("process id:"+p_info.p_id+" p_size:"+p_info.p_size+"starting address"+p_info.start_address); if(p_info.p_id!=-1) { //startaddress[i]=startaddress[i]/4+200; g.setColor(Color.BLUE); g.fillRect(p_info.start_address/4+100, 50, (p_info.p_size/4), 70); g.setColor(Color.BLACK); g.drawRect(p_info.start_address/4+100+1, 50, (p_info.p_size/4)-1, 70-1); } else { g.setColor(Color.BLACK); g.drawRect(p_info.start_address/4+100, 50, (p_info.p_size/4), 70); g.setColor(Color.BLACK); //this.createToolTip().setBounds(p_info.start_address/4+100, 75, (p_info.p_size/4), 70); g.drawRect(p_info.start_address/4+100+1, 50, (p_info.p_size/4)-1, 70-1); } } } public void set_list(ArrayList<Process_Detail> p,int mem_size) // It will get next process values from current arraylist object { this.p=p; this.mem_size=mem_size; } }
true
b37269a0b89260ede319f31e1736941e1d6239e7
Java
xitmxnwz/laboratory
/src/spring/backendSpring/CDPlayer.java
UTF-8
645
1.992188
2
[]
no_license
package spring.backendSpring; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; @Component public class CDPlayer { @Autowired private CompactDisc cd; // @Bean // public CompactDisc sgtPeppers() { // return new SgtPeppers(); // } // @Bean // public CDPlayer cDPlayer(CompactDisc sgtPeppers) { // return new CDPlayer(sgtPeppers); // } public CDPlayer() { } public CDPlayer(CompactDisc sgtPeppers) { this.cd = sgtPeppers; } public void aa() { cd.play(); } }
true
022466307a7fa2565c0eeb2f034868e294428c5c
Java
niuskamora/Proyectos
/prueba/src/java/com/pangea/prueba/servicio/pruebaservicio.java
UTF-8
6,473
2.15625
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.pangea.prueba.servicio; import com.pangea.prueba.control.modelo.entidad.Cargo; import com.pangea.prueba.control.modelo.entidad.Departamento; import com.pangea.prueba.control.modelo.entidad.Empleado; import com.pangea.prueba.control.modelo.entidad.Proyecto; import com.pangea.prueba.modelo.bean.CargoFacade; import com.pangea.prueba.modelo.bean.DepartamentoFacade; import com.pangea.prueba.modelo.bean.EmpleadoFacade; import com.pangea.prueba.modelo.bean.ProyectoFacade; import java.math.BigDecimal; import java.util.List; import java.util.Map; import javax.ejb.EJB; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import org.primefaces.model.SortOrder; /** * * @author PANGEA */ @WebService(serviceName = "pruebaservicio") public class pruebaservicio { @EJB DepartamentoFacade departamentoFacade; @EJB CargoFacade cargoFacade; @EJB EmpleadoFacade empleadoFacade; @EJB ProyectoFacade proyectoFacade; /** * This is a sample web service operation */ @WebMethod(operationName = "hello") public String hello(@WebParam(name = "name") String txt) { return "Hello " + txt + " !"; } @WebMethod(operationName = "listaDepartamento") public List<Departamento> listaDepartamento() { return departamentoFacade.retornaDepartamentos(); } @WebMethod(operationName = "descripcionCargo") public Cargo descripcionCargo(@WebParam(name = "name") String txt) { return cargoFacade.descripcionCargo(txt); } @WebMethod(operationName = "listaDepartamentoMayor") public List<Departamento> listaDepartamentoMayor() { return departamentoFacade.listaDepartamentoMayorASeis(); } @WebMethod(operationName = "promedioSueldo") public List<String[]> promedioSueldo() { return departamentoFacade.promedioSueldoSql(); } @WebMethod(operationName = "cantidadEmpleados") public List<String[]> cantidadEmpleados() { return departamentoFacade.cantidadEmpleados(); } @WebMethod(operationName = "cantidadEmpleadosJPQL") public List<String[]> cantidadEmpleadosJPQL() { return departamentoFacade.cantidadEmpleadosJPQL(); } @WebMethod(operationName = "promedioSueldoGeneral") public BigDecimal promedioSueldoGeneral() { return empleadoFacade.promedioSueldoGeneral(); } @WebMethod(operationName = "todo") public List<String[]> todo() { return empleadoFacade.mostrarEmpleadoDepartamentoCargo(); } @WebMethod(operationName = "todoJPQL") public List<String[]> todoJPQL() { return empleadoFacade.mostrarEmpleadoDepartamentoCargoJPQL(); } //Metodos para CREAR!!! @WebMethod (operationName = "crearCargo") public void crearCargo(@WebParam(name = "registroCargo") Cargo registroc){ cargoFacade.insertarCargo(registroc); } @WebMethod (operationName = "crearDepartameto") public void crearDepartameto(@WebParam(name = "registroDepartamento") Departamento registrod){ departamentoFacade.insertarDepartamento(registrod); } @WebMethod (operationName = "crearEmpleado") public void crearEmpleado(@WebParam(name = "registroEmpleado") Empleado registroe){ empleadoFacade.insertarEmpleado(registroe); } @WebMethod (operationName = "crearProyecto") public void crearProyecto(@WebParam(name = "registroProyecto") Proyecto registrop){ proyectoFacade.insertarProyecto(registrop); } //Metodos para contar y actualizar los valores de las tablas @WebMethod (operationName = "listarCargo") public int listarCargo(){ return cargoFacade.count(); } @WebMethod (operationName = "encontrarCargo") public List<Cargo> encontrarCargo(@WebParam(name = "sortF") String sortF,@WebParam(name = "sortB") boolean sortB, @WebParam(name = "range") List<Integer> range, @WebParam(name = "fil") Map<String, String> filters,@WebParam(name = "cad") String cadena ) { int vector[]= new int[2]; vector[0]=range.get(0); vector[1]=range.get(1); return cargoFacade.findRange(sortF, sortB, vector, filters, cadena); } @WebMethod (operationName = "listarDepartamento") public int listarDepartamento(){ return departamentoFacade.count(); } @WebMethod (operationName = "encontrarDepartamento") public List<Departamento> encontrarDepartamento(@WebParam(name = "sortF") String sortF,@WebParam(name = "sortB") boolean sortB, @WebParam(name = "range") List<Integer> range, @WebParam(name = "fil") Map<String, String> filters,@WebParam(name = "cad") String cadena ) { int vector[]= new int[2]; vector[0]=range.get(0); vector[1]=range.get(1); return departamentoFacade.findRange(sortF, sortB, vector, filters, cadena); } @WebMethod (operationName = "listarEmpleado") public int listarEmpleado(){ return empleadoFacade.count(); } @WebMethod (operationName = "encontrarEmpleado") public List<Empleado> encontrarEmpleado(@WebParam(name = "sortF") String sortF,@WebParam(name = "sortB") boolean sortB, @WebParam(name = "range") List<Integer> range, @WebParam(name = "fil") Map<String, String> filters,@WebParam(name = "cad") String cadena ) { int vector[]= new int[2]; vector[0]=range.get(0); vector[1]=range.get(1); return empleadoFacade.findRange(sortF, sortB, vector, filters, cadena); } @WebMethod (operationName = "listarProyecto") public int listarProyecto(){ return proyectoFacade.count(); } @WebMethod (operationName = "encontrarProyecto") public List<Proyecto> encontrarProeycto(@WebParam(name = "sortF") String sortF,@WebParam(name = "sortB") boolean sortB, @WebParam(name = "range") List<Integer> range, @WebParam(name = "fil") Map<String, String> filters,@WebParam(name = "cad") String cadena ) { int vector[]= new int[2]; vector[0]=range.get(0); vector[1]=range.get(1); return proyectoFacade.findRange(sortF, sortB, vector, filters, cadena); } }
true
106e17f18d4ec54559d5dc7f2e8573194e5d0bca
Java
Pwb-Ben/programLearning
/src/main/java/com/programlearning/learning/IO/SocketAIO.java
UTF-8
2,230
3.265625
3
[]
no_license
package com.programlearning.learning.IO; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.Future; public class SocketAIO { private AsynchronousServerSocketChannel serverSocketChannel; public static void main(String[] args) { try { SocketAIO socketAIO = new SocketAIO(); } catch (Exception e) { e.printStackTrace(); } } public SocketAIO() throws Exception { serverSocketChannel = AsynchronousServerSocketChannel.open(); serverSocketChannel.bind(new InetSocketAddress("127.0.0.1", 12306)); serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() { @Override public void completed(AsynchronousSocketChannel socketChannel, Object attachment) { System.out.println("服务器接受连接"); try { sendDataToClient(socketChannel); serverSocketChannel.accept(null, this); } catch (Exception e) { e.printStackTrace(); } } @Override public void failed(Throwable t, Object attachment) { t.printStackTrace(); } }); // AIO非阻塞,需要在主进程阻塞,否则进程退出导致套接字关闭,服务器接受不到任何连接。 try { Thread.sleep(Integer.MAX_VALUE); } catch (InterruptedException e) { e.printStackTrace(); } } private void sendDataToClient(AsynchronousSocketChannel socketChannel) throws Exception { System.out.println("服务器与" + socketChannel.getRemoteAddress() + "建立连接"); ByteBuffer buffer = ByteBuffer.wrap("zhangphil".getBytes()); Future<Integer> write = socketChannel.write(buffer); while (!write.isDone()) { Thread.sleep(10); } System.out.println("服务器发送数据完毕."); socketChannel.close(); } }
true
3d5b2579b13f4003ee309094c4cb0cbf6c222812
Java
ChunWai279321/QUIZZES
/Quiz/src/Quiz2.java
UTF-8
1,145
3.515625
4
[]
no_license
package Quiz2; public class Quiz2 { public static void main(String[] args) { Question1(); Question2(); Question3(); Question4(); } public static void Question1() { System.out.println("Question 1: "); int n=1; while (n<=5) { System.out.println(n); n++; } System.out.println(); } public static void Question2() { System.out.println("Question 2: "); int number=1; int total=25; while (number<=(total/2)) { total=total-number; System.out.println(total+" "+number); number++; } System.out.println(); } public static void Question3() { System.out.println("Question 3: "); int a=1; while (a<=2) { int b=1;{ while (b<=3) { int c=1;{ while (c<=4) { System.out.print("*"); c++; } }System.out.print("!"); b++; } }System.out.println(); a++; }System.out.println(); } public static void Question4() { System.out.println("Question 4: "); int number=4; int count=1; while(count<=number) { System.out.println(number); number=number/2; count++; } } }
true
1868a49cfee1ac4f8013902b8dd950e0129547e3
Java
thcha907/mini
/src/main/java/com/thcha/mini/repository/CompanyCustomerRepository.java
UTF-8
1,810
2.25
2
[]
no_license
package com.thcha.mini.repository; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import com.thcha.mini.entity.CompanyCustomer; import org.springframework.stereotype.Repository; import lombok.RequiredArgsConstructor; @Repository @RequiredArgsConstructor public class CompanyCustomerRepository { @PersistenceContext private final EntityManager em; public Long save(CompanyCustomer companyCustomer) { if (companyCustomer.getId() == null) { em.persist(companyCustomer); } else { em.merge(companyCustomer); } return companyCustomer.getId(); } public CompanyCustomer findOne(Long id) { return em.find(CompanyCustomer.class, id); } public List<CompanyCustomer> findAll() { return em.createQuery("select c from companyCustomer c", CompanyCustomer.class) .getResultList(); } public List<CompanyCustomer> findByName(String name) { return em.createQuery("select c from companyCustomer c where c.name = :name", CompanyCustomer.class) .setParameter("name", name) .getResultList(); } public List<CompanyCustomer> findByPersonSsn(String companyBizNo) { return em.createQuery("select c from companyCustomer c where c.companyBizNo = :companyBizNo", CompanyCustomer.class) .setParameter("companyBizNo", companyBizNo) .getResultList(); } public List<CompanyCustomer> findByCompanyBizNo(String companyBizNo) { return em.createQuery("select c from companyCustomer c where c.companyBizNo = :companyBizNo", CompanyCustomer.class) .setParameter("companyBizNo", companyBizNo) .getResultList(); } }
true
c068241ba85689fc02d39f1f86244f60db1a67bb
Java
ashru344/java-projects
/user-onboarding/src/main/java/com/carrernet/app/exception/UserAlreadyRegisteredException.java
UTF-8
313
1.960938
2
[]
no_license
package com.carrernet.app.exception; public class UserAlreadyRegisteredException extends BaseException { private static final long serialVersionUID = 5932067407679034332L; public UserAlreadyRegisteredException() { super(); } public UserAlreadyRegisteredException(String message) { super(message); } }
true
6392ed009f3a7a9ab82899a3b8d5227d83db7d12
Java
deanclark/DeanFly
/src/java/WorldItem.java
UTF-8
2,215
2.40625
2
[]
no_license
import java.awt.Color; import java.awt.Polygon; /** * * @author dean.clark * */ class WorldItem { final Color fixedColor = new Color(250, 220, 100); public final static int OBJECT_POINTS = 5000; // max number of points per object public final static int POLYS = 5000; // max number of polygons per object public final static int POLY_POINTS = 200; // max number of points for each polygon // real world co-ords String objectName; double RealX[] = new double[OBJECT_POINTS]; double RealY[] = new double[OBJECT_POINTS]; double RealZ[] = new double[OBJECT_POINTS]; double RealH[] = new double[OBJECT_POINTS]; // object points in the real measures int scaleFactor; Polygon poly[] = new Polygon[POLYS]; Color polyColour[] = new Color[POLYS]; int polys; // number of polygons boolean hiddenObject; boolean hiddenPolys[] = new boolean[POLYS]; int polylist[][] = new int[POLYS][POLY_POINTS]; // list of object faces int sorted_list[] = new int[POLYS]; // sorted list of polys int vertices; // number of polygons double rotx; double roty; double rotz; // object rotation int posx; int posy; int posz; // world possition double newX[] = new double[OBJECT_POINTS]; double newY[] = new double[OBJECT_POINTS]; double newZ[] = new double[OBJECT_POINTS]; double averageZposition; // holds the average Z value for all points in the object, this is used to sort objects double averageXposition; double averageDistanceFromViewer; // Array of points used to create the polys of a WorldItem. These will change if Clipped int points; double xtemp[] = new double[POLY_POINTS]; double ytemp[] = new double[POLY_POINTS]; double xpoints[] = new double[POLY_POINTS]; double ypoints[] = new double[POLY_POINTS]; double zpoints[] = new double[POLY_POINTS]; boolean updated[] = new boolean[POLY_POINTS]; int xpoly[] = new int[POLY_POINTS]; int ypoly[] = new int[POLY_POINTS]; // Initial coordinates int discardDegRotation = 0; int initX = 0, initY = 0, initZ = 0; double preRotation = 0.0; int scale = 0; }
true
c80283489a21aea698a7b5b4d3c31f3fb62d29bf
Java
ravenscroftj/ADM
/src/com/funkymonkeysoftware/adm/download/ADMDownloader.java
UTF-8
1,463
3.125
3
[]
no_license
package com.funkymonkeysoftware.adm.download; import java.util.LinkedList; /** * Abstract implementation of the IDownloader interface with event dispatch * * @author James Ravenscroft * */ public abstract class ADMDownloader implements IDownloader { protected LinkedList<IDownloadListener> listeners; public ADMDownloader(){ listeners = new LinkedList<IDownloadListener>(); } /** * Add a download listener from the downloader * * @param l <p>The listener to add to the list</p> */ public synchronized void addListener(IDownloadListener l){ listeners.add(l); } /** * Remove a download listener from the downloader * * @param l <p>The listener to be removed</p> */ public synchronized void removeListener(IDownloadListener l){ listeners.remove(l); } /** * Method called when progress is made on a specific download * * @param dl <p>The download that has progressed.</p> */ protected synchronized void fireDownloadProgressEvent(ADMDownload dl){ DownloadEvent evt = new DownloadEvent(this, dl); for(IDownloadListener l : listeners){ l.OnDownloadProgress(evt); } } /** * Method called when a download has finished downloading * * @param dl <p>The download that has finished.</p> */ protected synchronized void fireDownloadFinishedEvent(ADMDownload dl){ DownloadEvent evt = new DownloadEvent(this, dl); for(IDownloadListener l : listeners){ l.OnDownloadComplete(evt); } } }
true
b6396b2ac86091d97b46cfd97e3574ff06d5e31d
Java
mikka22pl/glossa-backend
/src/main/java/org/ulv/pro/langen/model/SentenceStructure.java
UTF-8
823
2.015625
2
[]
no_license
package org.ulv.pro.langen.model; public class SentenceStructure extends BaseEntity { private static final long serialVersionUID = 3302033152422268722L; private Integer structureId; private Integer ordering; private LexerLang functionWord; private Integer type; public Integer getStructureId() { return structureId; } public void setStructureId(Integer structureId) { this.structureId = structureId; } public Integer getOrdering() { return ordering; } public void setOrdering(Integer ordering) { this.ordering = ordering; } public LexerLang getFunctionWord() { return functionWord; } public void setFunctionWord(LexerLang functionWord) { this.functionWord = functionWord; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } }
true
560d2582f492dbff72f539484f8ba64719a22a4f
Java
nicopatoco/designPatterns-java
/src/com/company/patterns/pokemonStrategy/HydroPumpAttackStrategy.java
UTF-8
253
2.703125
3
[]
no_license
package com.company.patterns.pokemonStrategy; public class HydroPumpAttackStrategy implements Attack { @Override public void executeAttack(Pokemon firstPokemon, Pokemon secondPokemon) { System.out.println("Hydro Pump Attack!"); } }
true
4b78f65d6ba9df3591d786cae835f7357ca0dac2
Java
lvhill/pro
/base-web/src/main/java/cn/sky/test/webservice/client/scws/dto/ScWsService.java
UTF-8
2,641
1.921875
2
[]
no_license
package cn.sky.test.webservice.client.scws.dto; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */ @WebServiceClient(name = "ScWsService", targetNamespace = "http://webservice.test.sky.cn/", wsdlLocation = "http://localhost:9090/base-web/ws/ScWs?wsdl") public class ScWsService extends Service { private final static URL SCWSSERVICE_WSDL_LOCATION; private final static WebServiceException SCWSSERVICE_EXCEPTION; private final static QName SCWSSERVICE_QNAME = new QName("http://webservice.test.sky.cn/", "ScWsService"); static { URL url = null; WebServiceException e = null; try { url = new URL("http://localhost:9090/base-web/ws/ScWs?wsdl"); } catch (MalformedURLException ex) { e = new WebServiceException(ex); } SCWSSERVICE_WSDL_LOCATION = url; SCWSSERVICE_EXCEPTION = e; } public ScWsService() { super(__getWsdlLocation(), SCWSSERVICE_QNAME); } public ScWsService(WebServiceFeature... features) { super(__getWsdlLocation(), SCWSSERVICE_QNAME, features); } public ScWsService(URL wsdlLocation) { super(wsdlLocation, SCWSSERVICE_QNAME); } public ScWsService(URL wsdlLocation, WebServiceFeature... features) { super(wsdlLocation, SCWSSERVICE_QNAME, features); } public ScWsService(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } public ScWsService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { super(wsdlLocation, serviceName, features); } /** * * @return returns ScWs */ @WebEndpoint(name = "ScWsPort") public ScWs getScWsPort() { return super.getPort(new QName("http://webservice.test.sky.cn/", "ScWsPort"), ScWs.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure * on the proxy. Supported features not in the * <code>features</code> parameter will have their default * values. * @return returns ScWs */ @WebEndpoint(name = "ScWsPort") public ScWs getScWsPort(WebServiceFeature... features) { return super.getPort(new QName("http://webservice.test.sky.cn/", "ScWsPort"), ScWs.class, features); } private static URL __getWsdlLocation() { if (SCWSSERVICE_EXCEPTION != null) { throw SCWSSERVICE_EXCEPTION; } return SCWSSERVICE_WSDL_LOCATION; } }
true
bc07b12db21afdb5d7fd3c390adcb4c267de6c6a
Java
CS2103-Aug2015-w15-4j/main
/test/GuiShortcutTest.java
UTF-8
3,609
2.484375
2
[]
no_license
package test; import static org.junit.Assert.*; import org.junit.Test; import gui.ShortcutManager; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import gui.ShortcutManager.CommandType; //@@author A0122534R public class GuiShortcutTest { boolean isShiftDown = false; boolean isControlDown = false; boolean isAltDown = false; KeyEvent keyEvent = null; @Test public void focusModeTest01() { // BACK_SLASH (\) only keyEvent = new KeyEvent(null, null, null, KeyCode.BACK_SLASH, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.FOCUS_MODE, ShortcutManager.processKeyEvent(keyEvent)); } @Test public void focusModeTest02() { // Ctrl + BACK_SLASH (\) only isControlDown = true; keyEvent = new KeyEvent(null, null, null, KeyCode.BACK_SLASH, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.FOCUS_MODE, ShortcutManager.processKeyEvent(keyEvent)); } @Test public void focusModeClearTest01() { // BACK_SPACE only keyEvent = new KeyEvent(null, null, null, KeyCode.BACK_SPACE, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.FOCUS_MODE_CLEAR, ShortcutManager.processKeyEvent(keyEvent)); } @Test public void focusModeClearTest02() { // Shift + BACK_SLASH (\) only isShiftDown = true; keyEvent = new KeyEvent(null, null, null, KeyCode.BACK_SLASH, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.FOCUS_MODE_CLEAR, ShortcutManager.processKeyEvent(keyEvent)); } @Test public void helpTest01() { // F1 only keyEvent = new KeyEvent(null, null, null, KeyCode.F1, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.HELP, ShortcutManager.processKeyEvent(keyEvent)); } @Test public void searchTest01() { // Ctrl + F only isControlDown = true; keyEvent = new KeyEvent(null, null, null, KeyCode.F, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.SEARCH, ShortcutManager.processKeyEvent(keyEvent)); } @Test public void switchTest01() { // Alt + T only isAltDown = true; keyEvent = new KeyEvent(null, null, null, KeyCode.T, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.SWITCH, ShortcutManager.processKeyEvent(keyEvent)); } @Test public void inputFieldTest01() { // Ctrl + T only isControlDown = true; keyEvent = new KeyEvent(null, null, null, KeyCode.T, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.INPUT_FIELD, ShortcutManager.processKeyEvent(keyEvent)); } @Test public void undoTest01() { // Ctrl + Z only isControlDown = true; keyEvent = new KeyEvent(null, null, null, KeyCode.Z, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.UNDO, ShortcutManager.processKeyEvent(keyEvent)); } @Test public void pinTest01() { // Ctrl + P only isControlDown = true; keyEvent = new KeyEvent(null, null, null, KeyCode.P, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.PIN, ShortcutManager.processKeyEvent(keyEvent)); } @Test public void unpinTest01() { // Ctrl + U only isControlDown = true; keyEvent = new KeyEvent(null, null, null, KeyCode.U, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.UNPIN, ShortcutManager.processKeyEvent(keyEvent)); } @Test public void invalidTest01() { // Ctrl + Q only isControlDown = true; keyEvent = new KeyEvent(null, null, null, KeyCode.Q, isShiftDown, isControlDown, isAltDown, false); assertEquals(CommandType.NONE, ShortcutManager.processKeyEvent(keyEvent)); } }
true
703cc3f488ef8426dfc53809bd6212919b25467d
Java
jiep/SM
/Metaheurísticas/Práctica III/codigo/Práctica3/src/es/urjc/phub/InstanciaPHub.java
ISO-8859-1
2,144
3.078125
3
[]
no_license
package es.urjc.phub; import java.util.Random; public class InstanciaPHub { /* * Nmero de nodos de la instancia */ private int nodos; /* * Nmero total de servidores */ private int servidores; /* * Matriz de distancias entre todos los nodos aplicando la distancia * eucldea */ private double[][] distancia; /* * Vector con la demanda de cada nodo */ private double[] demanda; /* * Capacidad de los servidores (todos con la misma) */ private int capacidad; public InstanciaPHub(int nodos, int servidores, double[][] distancia, double[] demanda, int capacidad) { this.nodos = nodos; this.servidores = servidores; this.distancia = distancia; this.demanda = demanda; this.setCapacidad(capacidad); } public InstanciaPHub(){ } public double[][] getDistancia() { return distancia; } public double[] getDemanda() { return demanda; } public int getCapacidad() { return capacidad; } public void setCapacidad(int capacidad) { this.capacidad = capacidad; } public int getNodos() { return nodos; } public int getServidores() { return servidores; } public Solucin generarSolucinAleatoria() { Solucin s1 = null; Random x = new Random(); // Para poder reproducir los resultados x.setSeed(0); do{ x = new Random(); int nodos = this.getNodos(); int num_servidores = 0; boolean[] sol = new boolean[nodos]; boolean[][] ady = new boolean[nodos][nodos]; // Elegimos al azar los servidores while (num_servidores < this.getServidores()) { int aleatorio = 0; do { aleatorio = x.nextInt(nodos); } while (sol[aleatorio]); sol[aleatorio] = true; num_servidores++; } // Generamos las aristas for (int i = 0; i < nodos; i++) { if (!sol[i]) { // Seleccionamos el servidor ms cercano que nos encontremos int serv = Utils.seleccionarServidor(i, sol, this.getDistancia()); ady[i][serv] = true; ady[serv][i] = true; } } s1 = new Solucin(sol, ady, this.getDistancia()); }while(!Utils.esSolucinVlida(s1, this)); return s1 ; } }
true
d4d04c7f5f03f731b7c85723a0b09a26091bd6fb
Java
DhruvGala/Cryptography_sample_codes
/MyDES.java
UTF-8
13,521
3.109375
3
[]
no_license
import java.util.Scanner; /* * filename: MyDES.java * * version: 1.0 10/06/2015 * 1.1 10/07/2015 * * Log: <version 1.0> * implemented the S-box logic along with f function logic * and IP and inverse IP logic involved in DES. * Now working on developing the entire runs that will call f-function * 16 times throughout to run the DES algorithm. * * <version 1.1> * implemented the complete functionality of the DES algorithm * now testing and debugging code to update if any error found. * Also working now on making the code compact and more * object oriented. */ /** * The following code is the basic implementation of the DES algorithm * to encrypt the data using plain text of 64bits and a key k of 64 bits. * * @author DhruvGala * */ public class MyDES { static int[] keyDash; /** * This method is a generalized method for implementing bitwise XOR operator. * * @param a * @param b * @return */ public static int[] XOR(int[] a, int[] b){ int len = a.length; int[] c = new int[len]; for(int i = 0;i < len; i++){ if(a[i] == b[i]){ c[i] = 0; } else{ c[i] = 1; } } //String result = new String(c); return c; } /** * This method implements the initial permutation logic involved in the * DES algorithm. * * @param x * @return */ public static int[] IP(int[] x){ int lookUpTableIP[] = { 58,50,42,34,26,18,10,2, 60,52,44,36,28,20,12,4, 62,54,46,38,30,22,14,6, 64,56,48,40,32,24,16,8, 57,49,41,33,25,17,9,1, 59,51,43,35,27,19,11,3, 61,53,45,37,29,21,13,5, 63,55,47,39,31,23,15,7}; int IPed[] = new int[x.length]; for(int i=0;i<x.length;i++){ IPed[i] = x[lookUpTableIP[i]-1]; } return IPed; } /** * This method implements the inverse of initial permutation logic involved in the * DES algorithm. * * @param x * @return */ public static int[] inverseIP(int[] x){ int lookUpTableInverseIP[] = { 40,8,48,16,56,24,64,32, 39,7,47,15,55,23,63,31, 38,6,46,14,54,22,62,30, 37,5,45,13,53,21,61,29, 36,4,44,12,52,20,60,28, 35,3,43,11,51,19,59,27, 34,2,42,10,50,18,58,26, 33,1,41,9,49,17,57,25}; int IPedInv[] = new int[x.length]; for(int i=0;i<x.length;i++){ IPedInv[i] = x[lookUpTableInverseIP[i]-1]; } return IPedInv; } /** * This method implements the Expansion logic involved in DES algorithm, * where the 32 bit R is expanded to 48 bit. * * @param R * @return */ public static int[] Expansion(int[] R){ int ExpansionTable[] = { 32,1,2,3,4,5, 4,5,6,7,8,9, 8,9,10,11,12,13, 12,13,14,15,16,17, 16,17,18,19,20,21, 20,21,22,23,24,25, 24,25,26,27,28,29, 28,29,30,31,32,1}; int ExR[] = new int[48]; for(int j=0; j<ExpansionTable.length;j++){ ExR[j] = R[ExpansionTable[j]-1]; } return ExR; } /*public static int[] convertSixBitToFourBit(int whichBox, int[] result){ }*/ /** * The heart of the S-box logic is implemented in here. * * @param x * @return */ public static int[] Sbox(int[] x){ int[][] Sresult = new int[8][6]; int[][] S1 ={ {14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7}, {0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8}, {4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0}, {15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13} }; int[][] S2 ={ {15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10}, {3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5}, {0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15}, {13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9} }; int[][] S3 ={ {10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8}, {13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1}, {13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7}, {1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12} }; int[][] S4 ={ {7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15}, {13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9}, {10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4}, {3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14} }; int[][] S5 ={ {2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9}, {14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6}, {4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14}, {11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3} }; int[][] S6 ={ {12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11}, {10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8}, {9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6}, {4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13} }; int[][] S7 ={ {4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1}, {13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6}, {1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2}, {6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12} }; int[][] S8 ={ {13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7}, {1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2}, {7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8}, {2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11} }; for(int i=0;i<8;i++){ for(int j=0;j<6;j++){ Sresult[i][j] = x[j]; } } int[] result = new int[32],binary; int position = 0,number; for(int i=0;i<8;i++){ int row = (int) (Sresult[i][0]*2 + Sresult[i][5]); int column = (int) (Sresult[i][1]*Math.pow(2, 3) + Sresult[i][2]*Math.pow(2, 2) + Sresult[i][3]*2 + Sresult[i][4]); // System.out.println("\niteration:"+(i+1)+" row:"+row+" column:"+column); /** * The switch logic implements the nonlinear part of the DES algorithm, * i.e. the S-boxes. * */ switch(i){ case 0: number = S1[row][column]; binary = convertToBinary(number); for(int j=0;j<4;j++){ result[position++] = binary[j]; //System.out.print(binary[j]); } break; case 1: number = S2[row][column]; binary = convertToBinary(number); for(int j=0;j<4;j++){ result[position++] = binary[j]; } break; case 2: number = S3[row][column]; binary = convertToBinary(number); for(int j=0;j<4;j++){ result[position++] = binary[j]; } break; case 3: number = S4[row][column]; binary = convertToBinary(number); for(int j=0;j<4;j++){ result[position++] = binary[j]; } break; case 4: number = S5[row][column]; binary = convertToBinary(number); for(int j=0;j<4;j++){ result[position++] = binary[j]; } break; case 5: number = S6[row][column]; binary = convertToBinary(number); for(int j=0;j<4;j++){ result[position++] = binary[j]; } break; case 6: number = S7[row][column]; binary = convertToBinary(number); for(int j=0;j<4;j++){ result[position++] = binary[j]; } break; case 7: number = S8[row][column]; binary = convertToBinary(number); for(int j=0;j<4;j++){ result[position++] = binary[j]; } break; } } return result; } /** * This method converts the number to its binary equivalent in integer array format. * * @param thisNumber * @return */ public static int[] convertToBinary(int thisNumber){ String binary = Integer.toString(thisNumber,2); if(binary.length() != 4){ switch(binary.length()){ case 3: binary = "0" + binary; break; case 2: binary = "00" + binary; break; case 1: binary = "000" + binary; break; case 0: binary = "0000"; break; } } //System.out.println("In convert ->"+binary); //System.out.print("result->"); int[] result = new int[4]; if(binary.charAt(0) == 0){ result[0] =0; } else { result[0] =1; } for(int i=1;i<binary.length();i++){ result[i] = Integer.parseInt(binary.substring(i-1,i)); //System.out.println(result[i]); } //System.out.println(); return result; } /** * This method performs the permutation function involved after the S-boxes logic * in the DES algorithm. * * @param thisData * @return */ public static int[] Permutation(int[] thisData){ int Permutation[] = { 16,7,20,21,29,12,28,17, 1,15,23,26,5,18,31,10, 2,8,24,14,32,27,3,9, 19,13,30,6,22,11,4,25 }; int result[] = new int[thisData.length]; for(int i=0;i<thisData.length;i++){ result[i] = thisData[Permutation[i]-1]; } return result; } /** * This method implements the f-function logic involved in the DES algorithm. * * @param R * @param k * @return */ public static int[] functionF(int[] R,int[] k){ int[] ExR = Expansion(R); /*System.out.println("----------After Expansion----------"); for(int i=0;i<ExR.length;i++){ System.out.print(ExR[i]); } System.out.println("\nlength->"+ExR.length);*/ int[] result = XOR(ExR,k); /*System.out.println("\n----------After XOR----------"); for(int i=0;i<result.length;i++){ System.out.print(result[i]); } System.out.println("\nlength->"+result.length);*/ result = Sbox(result); /*System.out.println("\n----------After S-boxes----------"); for(int i=0;i<result.length;i++){ System.out.print(result[i]); } System.out.println("\nlength->"+result.length);*/ result = Permutation(result); /*System.out.println("\n----------After Permutation----------"); for(int i=0;i<result.length;i++){ System.out.print(result[i]); } System.out.println("\nlength->"+result.length);*/ return result; } /** * This method takes the input of 64 bit plaintext and key. * * @return */ public static int[][] feedInput(){ Scanner takeInput = new Scanner(System.in); int[][] sendThis = new int[2][64]; //System.out.print("Enter the plaintext: "); String input = takeInput.nextLine(); if(input.charAt(0) == 0){ sendThis[0][0] =0; } else { sendThis[0][0] =1; } for(int i=1;i<input.length();i++){ sendThis[0][i] = Integer.parseInt(input.substring(i-1,i)); } //System.out.print("Enter the key:"); input = takeInput.nextLine(); if(input.charAt(0) == 0){ sendThis[1][0] =0; } else { sendThis[1][0] =1; } for(int i=1;i<input.length();i++){ sendThis[1][i] = Integer.parseInt(input.substring(i-1,i)); } takeInput.close(); return sendThis; } /** * This method is the actual logic of defining the PC-1 to generate the keys * * @param k * @return */ public static int[] PC1(int[] k){ int PC1table[] = { 57,49,41,33,25,17,9,1, 58,50,42,34,26,18,10,2, 59,51,43,35,27,19,11,3, 60,52,44,36,63,55,47,39, 31,23,15,7,62,54,46,38, 30,22,14,6,61,53,45,37, 29,21,13,5,28,20,12,4 }; int key[] = new int[56]; for(int i=0;i<PC1table.length;i++){ key[i] = k[PC1table[i]-1]; } return key; } /** * This method is the logic to implement the PC2 mechanism * for generating the keys. * * @param k * @return */ public static int[] PC2(int[] k){ //System.out.println("i/p length:"+k.length); int PC2table[] = { 14,17,11,24,1,5,3,28, 15,6,21,10,23,19,12,4, 26,8,16,7,27,20,13,2, 41,52,31,37,47,55,30,40, 51,45,33,48,44,49,39,56, 34,53,46,42,50,36,29,32 }; int key[] = new int[48]; for(int i=0;i<PC2table.length;i++){ key[i] = k[PC2table[i]-1]; } return key; } /** * This method performs the left shift operation on the input bitstream * * @param bitstream * @return */ public static int[] LS1(int[] bitstream){ int temp = bitstream[0]; for(int i=1;i<bitstream.length;i++){ bitstream[i-1] = bitstream[i]; } bitstream[bitstream.length-1] = temp; return bitstream; } /** * this method carries out the transformation on the key side logic. * * @return */ public static int[] transform1(){ int[] C = new int[28],D = new int[28]; /** * first we split the input key into two parts. * */ for(int i =0;i<keyDash.length/2;i++){ C[i] = keyDash[i]; D[i] = keyDash[i+28]; } C = LS1(C); D = LS1(D); int[] returnThis = new int[56]; for(int i=0;i<28;i++){ returnThis[i] = C[i]; returnThis[i+28] = D[i]; } keyDash = returnThis; int[] result = PC2(returnThis); return result; } /** * This method generates all the different keys needed for each rounds. * * @return */ public static int[] geenerateKeys(){ int[] key = transform1(); //int[] keyD = PC2(key); return key; } /** * This method carries out the actual DES process by calling other functional methods. * * @param plaintext * @param key * @return */ public static int[] carryOutDES(int[] plaintext, int[] key){ keyDash = PC1(key); int[] x = IP(plaintext); for(int iterations = 0 ; iterations<16; iterations++){ key = geenerateKeys(); x = Rounds(x, key); } x = inverseIP(x); return x; } /** * The logic of this method is to manipulate the bits and proceed with the * encryption process of DES algorithm. * * @param x * @param k * @return */ public static int[] Rounds(int[] x,int[] k ){ int[] L = new int[32],R = new int[32]; for(int i =0;i<x.length/2;i++){ L[i] = x[i]; R[i] = x[i+32]; } //int[] Lnext = R; int[] temp = functionF(R, k); int[] result = XOR(temp, L); int[] returnThis = new int[64]; //returnThis = R; for(int i=0;i<32;i++){ returnThis[i] = R[i]; returnThis[i+32] = result[i]; } return returnThis; } /** * * @param args */ public static void main(String[] args) { int[][] data = feedInput(); int[] x = data[0]; int[] k = data[1]; int[] ciphertext = carryOutDES(x, k); System.out.println("The encrypted cipher text: "); for(int i=0;i<ciphertext.length;i++){ System.out.print(ciphertext[i]); } } }
true
6e67edd9c820667ef8defc53c1d33f62f1655534
Java
aliyun/aliyun-openapi-java-sdk
/aliyun-java-sdk-mpserverless/src/main/java/com/aliyuncs/mpserverless/model/v20190615/ListFunctionDeploymentResponse.java
UTF-8
4,979
1.609375
2
[ "Apache-2.0" ]
permissive
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.mpserverless.model.v20190615; import java.util.List; import com.aliyuncs.AcsResponse; import com.aliyuncs.mpserverless.transform.v20190615.ListFunctionDeploymentResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class ListFunctionDeploymentResponse extends AcsResponse { private String httpStatusCode; private Boolean success; private String code; private String message; private String requestId; private List<DataListItem> dataList; private Paginator paginator; public String getHttpStatusCode() { return this.httpStatusCode; } public void setHttpStatusCode(String httpStatusCode) { this.httpStatusCode = httpStatusCode; } public Boolean getSuccess() { return this.success; } public void setSuccess(Boolean success) { this.success = success; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public List<DataListItem> getDataList() { return this.dataList; } public void setDataList(List<DataListItem> dataList) { this.dataList = dataList; } public Paginator getPaginator() { return this.paginator; } public void setPaginator(Paginator paginator) { this.paginator = paginator; } public static class DataListItem { private String deploymentId; private String versionNo; private String createdAt; private String modifiedAt; private String downloadSignedUrl; private Status status; public String getDeploymentId() { return this.deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getVersionNo() { return this.versionNo; } public void setVersionNo(String versionNo) { this.versionNo = versionNo; } public String getCreatedAt() { return this.createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getModifiedAt() { return this.modifiedAt; } public void setModifiedAt(String modifiedAt) { this.modifiedAt = modifiedAt; } public String getDownloadSignedUrl() { return this.downloadSignedUrl; } public void setDownloadSignedUrl(String downloadSignedUrl) { this.downloadSignedUrl = downloadSignedUrl; } public Status getStatus() { return this.status; } public void setStatus(Status status) { this.status = status; } public static class Status { private String message; private String status; private String label; public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public String getLabel() { return this.label; } public void setLabel(String label) { this.label = label; } } } public static class Paginator { private Integer pageSize; private Integer pageNum; private Integer total; private Integer pageCount; public Integer getPageSize() { return this.pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getPageNum() { return this.pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } public Integer getTotal() { return this.total; } public void setTotal(Integer total) { this.total = total; } public Integer getPageCount() { return this.pageCount; } public void setPageCount(Integer pageCount) { this.pageCount = pageCount; } } @Override public ListFunctionDeploymentResponse getInstance(UnmarshallerContext context) { return ListFunctionDeploymentResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
true
c2a86e2752c41a239e1fc1112494d871ca138ade
Java
Kiamambo/CIRdemo
/CIRdemoApp/src/CIRMS/Database/DatabaseHandler.java
UTF-8
47,359
2.421875
2
[]
no_license
package CIRMS.Database; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JOptionPane; import CIRMS.Components.CompBProperty; import CIRMS.Components.CompCProperty; import CIRMS.Components.CompProperty; import CIRMS.Components.Component; import CIRMS.Components.ComponentTypeB; import CIRMS.Components.ComponentTypeC; import CIRMS.Equpments.Equipment; import CIRMS.Equpments.EquipmentProperty; import CIRMS.Student.StudentTableController.StudentProperty; import javafx.application.Platform; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; public class DatabaseHandler { private static final String DB_URL = "jdbc:derby:DBCIRMS;create=true"; // creating the URL to the database private static Connection conn = null; private static Statement stmt = null; private static DatabaseHandler handler = null; private static Equipment equip; private static Component component; private static ComponentTypeB compTypeB; private static ComponentTypeC compTypeC; /** * Create Constructor */ private DatabaseHandler() { createConnection(); // Student createBtechStudentTable(); createMasterStudentTable(); createSettingTable(); // Equipment createBreadboardTable(); createComputerTable(); createFunctionGeneratorTable(); createMultimeterTable(); createOscilloscopeTable(); createPowerSuppliersTable(); createToolsTable(); createIssueEquipmentsTable(); // Components createBananaPlugsTable(); createDataSocketsTable(); createDinConnectorsTable(); createlLedsTable(); createDisplayTable(); createCrocClipsTable(); createETDClipsTable(); createBNCTable(); createInsulatorsTable(); createFusesHoldersTable(); createLogicGatesTable(); createMicrophoneTable(); createICTable(); createIGBTTable(); createHighSpeedDiodesTable(); createDCMotorsTable(); createPowerHoleConnectorsTable(); createOpAmpsTable(); createTemperatureDeviceTable(); createTransistorsTable(); createZenerDiodesTable(); } /** * * @return */ public static DatabaseHandler getInstance() { if (handler == null) { handler = new DatabaseHandler(); } return handler; } /** * Method CreateConnnection will log the drivers and create the database * connection. */ public void createConnection() { try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); conn = DriverManager.getConnection(DB_URL); } catch (Exception e) { dialogBox("Error Occured", "Error: " +e.getCause()+" Please close the program and open again"); } } public static Equipment getEquip() { return equip; } public static void setEquip(Equipment equip) { DatabaseHandler.equip = equip; } public static Component getComponent() { return component; } public static void setComponent(Component component) { DatabaseHandler.component = component; } public static ComponentTypeB getCompTypeB() { return compTypeB; } public static void setCompTypeB(ComponentTypeB compTypeB) { DatabaseHandler.compTypeB = compTypeB; } public static ComponentTypeC getCompTypeC() { return compTypeC; } /** * method setCompTypeC will set the component type c. * @param compTypeC */ public static void setCompTypeC(ComponentTypeC compTypeC) { DatabaseHandler.compTypeC = compTypeC; } /** * Method createSettingTable will deal with settings button to create user and password */ public void createSettingTable() { String TABLE_NAME = "SETTING"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " Username varchar(50), \n" + " Password varchar(30), \n" + " primary key(Username)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createZenerDiodesTable will create the zener diodes table. */ public void createZenerDiodesTable() { String TABLE_NAME = "ZENERDIODES"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " ZENEReferece varchar(50), \n" + " ZENEPartNumber varchar(30), \n" + " ZENEPackage varchar(30), \n" + " ZENEBin varchar(30), \n " + " ZENETotal integer, \n" + " ZENEOrder boolean default false, \n" + " ZENEDataSheet varchar(15), \n" + " ZENELabelColour varchar(20), \n" + " ZENERsComponents varchar(30), \n" + " ZENEMantech varchar(30), \n" + " ZENECommunica varchar(30), \n" + " ZENEJpElectronics varchar(30), \n" + " ZENEElectrocComp varchar(30), \n" + " primary key(ZENEReferece, ZENEBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method will create the transistor table */ public void createTransistorsTable() { String TABLE_NAME = "TRANSISTORS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " TRANSIReferece varchar(50), \n" + " TRANSIPartNumber varchar(30), \n" + " TRANSIPackage varchar(30), \n" + " TRANSIBin varchar(30), \n " + " TRANSITotal integer, \n" + " TRANSIOrder boolean default false, \n" + " TRANSIDataSheet varchar(15), \n" + " TRANSILabelColour varchar(20), \n" + " TRANSIRsComponents varchar(30), \n" + " TRANSIMantech varchar(30), \n" + " TRANSICommunica varchar(30), \n" + " TRANSIJpElectronics varchar(30), \n" + " TRANSIElectrocComp varchar(30), \n" + " primary key(TRANSIReferece, TRANSIBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createTemperatureDeviceTable will create temperature device table */ public void createTemperatureDeviceTable() { String TABLE_NAME = "TEMPERATUREDEVICE"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " TEMPEReferece varchar(50), \n" + " TEMPEPartNumber varchar(30), \n" + " TEMPEPackage varchar(30), \n" + " TEMPEBin varchar(30), \n " + " TEMPETotal integer, \n" + " TEMPEOrder boolean default false, \n" + " TEMPEDataSheet varchar(15), \n" + " TEMPESupplier varchar(30), \n" + " primary key(TEMPEReferece, TEMPEBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createOpAmpsTable will create Op-Amps table */ public void createOpAmpsTable() { String TABLE_NAME = "OPAMPS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " OPAReferece varchar(50), \n" + " OPAPartNumber varchar(30), \n" + " OPAPackage varchar(30), \n" + " OPABin varchar(30), \n " + " OPATotal integer, \n" + " OPAOrder boolean default false, \n" + " OPADataSheet varchar(15), \n" + " OPASupplier varchar(30), \n" + " primary key(OPAReferece, OPABin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createLogicGatesTable will create the Logic Gates table */ public void createLogicGatesTable() { String TABLE_NAME = "LOGICGATES"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " LGReferece varchar(50), \n" + " LGPartNumber varchar(30), \n" + " LGPackage varchar(30), \n" + " LGBin varchar(30), \n " + " LGTotal integer, \n" + " LGOrder boolean default false, \n" + " LGDataSheet varchar(15), \n" + " LGSupplier varchar(30), \n" + " primary key(LGReferece, LGBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createICTable will create integrated circuit table */ public void createICTable() { String TABLE_NAME = "INTEGRATEDCIRCUIT"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " ICTReferece varchar(200), \n" + " ICTPartNumber varchar(30), \n" + " ICTPackage varchar(30), \n" + " ICTBin varchar(30), \n " + " ICTTotal integer, \n" + " ICTOrder boolean default false, \n" + " ICTDataSheet varchar(15), \n" + " ICTSupplier varchar(30), \n" + " primary key(ICTReferece, ICTBin)" + " )"); } }catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createIGBTTable will create the IGBT table */ public void createIGBTTable() { String TABLE_NAME = "IGBTtable"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " IGBReferece varchar(200), \n" + " IGBPartNumber varchar(30), \n" + " IGBPackage varchar(30), \n" + " IGBBin varchar(30), \n " + " IGBTotal integer, \n" + " IGBOrder boolean default false, \n" + " IGBDataSheet varchar(15), \n" + " IGBLabelColour varchar(20), \n" + " IGBRsComponents varchar(30), \n" + " IGBMantech varchar(300), \n" + " IGBCommunica varchar(300), \n" + " IGBJpElectronics varchar(300), \n" + " IGBElectrocComp varchar(300), \n" + " primary key(IGBReferece, IGBBin)" + " )"); } }catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createHighSpeedDiodesTable will create high speed diodes table */ public void createHighSpeedDiodesTable() { String TABLE_NAME = "HIGHSPEEDDIODES"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " HSDReferece varchar(50), \n" + " HSDPartNumber varchar(30), \n" + " HSDPackage varchar(30), \n" + " HSDBin varchar(30), \n " + " HSDTotal integer, \n" + " HSDOrder boolean default false, \n" + " HSDataSheet varchar(15), \n" + " HSDLabelColour varchar(20), \n" + " HSDRsComponents varchar(30), \n" + " HSDMantech varchar(30), \n" + " HSDCommunica varchar(30), \n" + " HSDJpElectronics varchar(30), \n" + " HSDElectrocComp varchar(30), \n" + " primary key(HSDReferece, HSDBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createPowerHoleConnectorsTable will create power hole connectors table */ public void createPowerHoleConnectorsTable() { String TABLE_NAME = "POWERHOLECONNECTOR"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " PHReferece varchar(200) , \n" + " PHTotal integer, \n" + " PHBin varchar(30),\n " + " PHLabelColour varchar(20)," + " PHOrder boolean default false,\n" + " primary key(PHReferece, PHBin)" + " )"); } }catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createDCMotorsTable will create the DC Motos table */ public void createDCMotorsTable() { String TABLE_NAME = "DC_MOTORS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " DCMReferece varchar(50) , \n" + " DCMTotal integer, \n" + " DCMBin varchar(30),\n " + " DCMLabelColour varchar(20)," + " DCMOrder boolean default false,\n" + " primary key(DCMReferece, DCMBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createMicrophoneTable will create the Microphone table */ public void createMicrophoneTable() { String TABLE_NAME = "MICROPHONE"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " MICROReferece varchar(50) , \n" + " MICROTotal integer, \n" + " MICROBin varchar(30),\n " + " MICROLabelColour varchar(20)," + " MICROOrder boolean default false,\n" + " primary key(MICROReferece, MICROBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createFusesHoldersTable will create the fuse holders tables */ public void createFusesHoldersTable() { String TABLE_NAME = "FUSES_HOLDERS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " FHReferece varchar(50) , \n" + " FHTotal integer, \n" + " FHBin varchar(30),\n " + " FHLabelColour varchar(20)," + " FHOrder boolean default false,\n" + " primary key(FHReferece, FHBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createInsulatorsTable will create the Insulator table. */ public void createInsulatorsTable() { String TABLE_NAME = "INSULATORS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " INSReferece varchar(50) , \n" + " INSTotal integer, \n" + " INSBin varchar(30),\n " + " INSLabelColour varchar(20)," + " INSOrder boolean default false,\n" + " primary key(INSReferece, INSBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createBNCTable will create the BNC connectors */ public void createBNCTable() { String TABLE_NAME = "BNC"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " BNCReferece varchar(60) , \n" + " BNCTotal integer, \n" + " BNCBin varchar(20),\n " + " BNCLabelColour varchar(20)," + " BNCOrder boolean default false,\n" + " primary key(BNCReferece, BNCBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createETDClipsTable will create the ETD Clips table */ public void createETDClipsTable() { String TABLE_NAME = "ETD_CLIPS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " ECReferece varchar(50) , \n" + " ECTotal integer, \n" + " ECBin varchar(50),\n " + " ECLabelColour varchar(30)," + " ECOrder boolean default false,\n" + " primary key(ECReferece, ECBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createCrocClipsTable will create the Croc clips table */ public void createCrocClipsTable() { String TABLE_NAME = "CROC_CLIPS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " CCReferece varchar(50) , \n" + " CCTotal integer, \n" + " CCBin varchar(50),\n " + " CCLabelColour varchar(30)," + " CCOrder boolean default false,\n" + " primary key(CCReferece, CCBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createDataSocketsTable will create the data socket table */ public void createDataSocketsTable() { String TABLE_NAME = "DATASOCKETS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " DAReferece varchar(50) , \n" + " DATotal integer, \n" + " DABin varchar(50),\n " + " DALabelColour varchar(30)," + " DAOrder boolean default false,\n" + " primary key(DAReferece, DABin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createDinConnectorsTable will create the din connectors table */ public void createDinConnectorsTable() { String TABLE_NAME = "DINCONNECTORS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " DINReferece varchar(50) , \n" + " DINTotal integer, \n" + " DINBin varchar(50),\n " + " DINLabelColour varchar(30)," + " DINOrder boolean default false,\n" + " primary key(DINReferece, DINBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createBananaPlugsTable will create the banana plugs table */ public void createBananaPlugsTable() { String TABLE_NAME = "BANANAPLUGS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " BANPReferece varchar(50) , \n" + " BANPTotal integer, \n" + " BANPBin varchar(50),\n " + " BANPLabelColour varchar(30)," + " BANPOrder boolean default false,\n" + " primary key(BANPReferece, BANPBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createDisplayTable will create the display */ public void createDisplayTable() { String TABLE_NAME = "DISPLAY"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " disReferece varchar(50) , \n" + " disTotal integer, \n" + " disBin varchar(50),\n " + " disLabelColour varchar(30)," + " disOrder boolean default false,\n" + " primary key(disReferece, disBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createlLedsTable will create the leds table */ public void createlLedsTable() { String TABLE_NAME = "LEDS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " ledReferece varchar(50) , \n" + " ledTotal integer, \n" + " ledBin varchar(50),\n " + " ledLabelColour varchar(30)," + " ledOrder boolean default false,\n" + " primary key(ledReferece, ledBin)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } public boolean deleteComponent(String tableName, String key1, String key2, CompProperty comptProperty) { String deleteStatement = "DELETE FROM " + tableName + " WHERE " + key1 + " = ? AND " + key2 + " = ?"; try { PreparedStatement stmt = conn.prepareStatement(deleteStatement); stmt.setString(1, comptProperty.getReference()); stmt.setString(2, comptProperty.getBin()); int res = stmt.executeUpdate(); if (res == 1) return true; } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); } return false; } /**_____________________(Equipments Tables)____________________________*/ /** *Method createToolsTable will create tools table */ public void createToolsTable() { String TABLE_NAME = "TOOLS"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " TAssetNumber varchar(50) , \n" + " TName varchar(200),\n" + " TModel varchar(50),\n" + " TSerialNumber varchar(50),\n " + " TNotes varchar(100), \n" + " TTotal integer,\n" + " TAvailable boolean default true,\n" + " primary key(TModel, TAssetNumber)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createComputerTable will create computer table. */ public void createComputerTable() { String TABLE_NAME = "COMPUTER"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " CompAssetNumber varchar(50), \n" + " CompName varchar(200),\n" + " CompModel varchar(50),\n" + " CompSerialNumber varchar(50),\n " + " CompNotes varchar(100), \n" + " CompTotal integer, \n" + " CompAvailable boolean default true,\n" + " primary key(CompModel, CompAssetNumber)" + ")"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createPowerSuppliersTable will create a power supplier table */ public void createPowerSuppliersTable() { String TABLE_NAME = "POWERSUPPLY"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " PSAssetNumber varchar(50), \n" + " PSName varchar(30),\n" + " PSModel varchar(50),\n" + " PSSerialNumber varchar(50),\n " + " PSNotes varchar(200), \n" + " PSTotal integer,\n" + " PSAvailable boolean default true,\n" + " PRIMARY KEY(PSModel, PSAssetNumber)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createOscilloscopeTable will create oscilloscope table */ public void createOscilloscopeTable() { String TABLE_NAME = "OSCILLOSCOPE"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " OSCIAssetNumber varchar(50), \n" + " OSCIName varchar(30) ,\n" + " OSCIModel varchar(50) ,\n" + " OSCISerialNumber varchar(50) ,\n " + " OSCINotes varchar(200), \n" + " OSCITotal integer, \n" + " OSCIAvailable boolean default true,\n" + " PRIMARY KEY(OSCIModel, OSCIAssetNumber)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createMultimeterTable will create Multimeter table */ public void createMultimeterTable() { String TABLE_NAME = "MULTIMETER"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " MAssetNumber varchar(50), \n" + " MName varchar(60),\n" + " MModel varchar(50) ,\n" + " MSerialNumber varchar(50) ,\n " + " MNotes varchar(200), \n" + " MdTotal integer, \n" + " MdAvailable boolean default true,\n" + " PRIMARY KEY(MModel, MAssetNumber)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createBreadboardTable will create a breadboard */ public void createBreadboardTable() { String TABLE_NAME = "BREADBOARD"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " BdAssetNumber varchar(50), \n" + " BdName varchar(200),\n" + " BdModel varchar(50) ,\n" + " BdSerialNumber varchar(50),\n " + " BdNotes varchar(200), \n" + " BdTotal integer, \n" + " BdAvailable boolean default true,\n" + " PRIMARY KEY(BdModel, BdAssetNumber)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** *Method createFunctionGeneratorTable will create a function generator */ public void createFunctionGeneratorTable() { String TABLE_NAME = "FUNCTIONGENERATOR"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " FgAssetNumber varchar(50),\n" + " FgName varchar(30),\n" + " FgModel varchar(50),\n" + " FgSerialNumber varchar(50),\n " + " FgNotes varchar(200), \n" + " FgTotal integer, \n" + " FgAvailable boolean default true,\n" + " PRIMARY KEY(FgModel, FgAssetNumber)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } /** * Method createIssueEquipmentsTable will create Issue table */ public void createIssueEquipmentsTable() { String TABLE_NAME = "ISSUE"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " modelNumber varchar(50) primary key,\n" + " assetNumber varchar(50),\n" + " studentNo varchar(25),\n" + " issueTime timestamp default CURRENT_TIMESTAMP,\n" + " renewCount integer default 0,\n" + " FOREIGN KEY (studentNo) REFERENCES BTECHSTUDENT(studentNoB),\n" + " FOREIGN KEY (modelNumber, assetNumber) REFERENCES FUNCTIONGENERATOR(FgModel, FgAssetNumber)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); }finally{ } } public boolean deleteComponentTypeC(String tableName, String reference, String bin, CompCProperty selectedForDeletion) { String deleteCstatement = "DELETE FROM " +tableName+ " WHERE " + reference +" = ? AND " + bin + " = ?"; System.out.println(deleteCstatement); try { PreparedStatement stmt = conn.prepareStatement(deleteCstatement); stmt.setString(1, selectedForDeletion.getReference()); stmt.setString(2, selectedForDeletion.getBin()); int res = stmt.executeUpdate(); if (res == 1) return true; } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); } return false; } public boolean deleteEquipment(String tableName, String key1, String key2, EquipmentProperty equipmentProperty) { String deleteStatement = "DELETE FROM " + tableName + " WHERE " + key1 + " = ? AND " + key2 + " = ?"; try { PreparedStatement stmt = conn.prepareStatement(deleteStatement); stmt.setString(1, equipmentProperty.getModel()); stmt.setString(2, equipmentProperty.getAssetNumber()); int res = stmt.executeUpdate(); if (res == 1) return true; } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); } return false; } /**______________________________________(End of Equipments Tables)____________________________*/ /** * Method execQuery this method is usefully to execute query like select statement * and return the query. * @param query * @return <code>ResultSet</code> specify statement. */ public ResultSet execQuery(String query) { ResultSet result; try{ stmt = conn.createStatement(); result = stmt.executeQuery(query); }catch (SQLException ex){ dialogBox("Error Occured", "Error: " +ex.getLocalizedMessage()); return null; }finally{ } return result; } /** * Method execAction is usefully to doing something */ public boolean execAction(String qu) { try { stmt = conn.createStatement(); stmt.execute(qu); return true; } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getCause()); return false; }finally { } } /** * Method createBtechStudentTable will create a table in the database to store * information about the Btech students. */ public void createBtechStudentTable() { String TABLE_NAME = "BTECHSTUDENT"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " studentNoB varchar(25) primary key, \n" + " nameB varchar(50),\n" + " surnameB varchar(50),\n" + " supervisorB varchar(50),\n " + " emailB varchar(100), \n" + " cellphoneNoB varchar(20),\n" + " stationB varchar(20),\n" + " courseB varchar(20)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getMessage()); }finally{ } } /** *Method createMasterStudentTable will create a table to store information about *the master students */ public void createMasterStudentTable() { String TABLE_NAME = "MASTERSTUDENT"; try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null); if (tables.next()) { //System.out.println("Table " + TABLE_NAME +" already exits. Ready for go!"); }else { stmt.execute("CREATE TABLE " + TABLE_NAME + "(" + " studentNoM varchar(25) primary key, \n" + " nameM varchar(50),\n" + " surnameM varchar(50),\n" + " supervisorM varchar(50),\n " + " emailM varchar(100), \n" + " cellphoneNoM varchar(20),\n" + " stationM varchar(20),\n" + " courseM varchar(20)" + " )"); } } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getMessage()); }finally{ } } /** * Method deleteStudentB will receive a selected row and * delete from the database table. * @param studentB * @return<code> boolean </code> specify statement. */ public boolean deleteStudentB(StudentProperty studentB) { try { String deleteStmt ="DELETE FROM BTECHSTUDENT WHERE STUDENTNOB = ?"; PreparedStatement stmt = conn.prepareStatement(deleteStmt); stmt.setString(1, studentB.getStudendID()); int result = stmt.executeUpdate(); if(result == 1) return true; } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getMessage()); } return false; } /** * Method deleteMasterStudent will receive the selected row from the table * and delete from the database table. * @param masterStudent * @return<code>boolean</code> specify statement. */ public boolean deleteMasterStudent(StudentProperty masterStudent) { try { String deleteStmt ="DELETE FROM MASTERSTUDENT WHERE STUDENTNOM = ?"; PreparedStatement stmt = conn.prepareStatement(deleteStmt); stmt.setString(1, masterStudent.getStudendID()); int result = stmt.executeUpdate(); if(result == 1) return true; } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getMessage()); } return false; } /** *Method updateBstudent will update the table with edit value in the selected row on *the Btech student table. * @param Bstudent * @return <code> boolean </code> specify statement. */ public boolean updateBstudent(StudentProperty Bstudent) { try { String update = "UPDATE BTECHSTUDENT SET NAMEB=?, SURNAMEB=?, SUPERVISORB=?, EMAILB=?, CELLPHONENOB=?, STATIONB=? , COURSEB=? WHERE STUDENTNOB=?"; PreparedStatement stmt = conn.prepareStatement(update); stmt.setString(1, Bstudent.getName()); stmt.setString(2, Bstudent.getSurname()); stmt.setString(3, Bstudent.getSupervisor()); stmt.setString(4, Bstudent.getEmail()); stmt.setString(5, Bstudent.getCellphone()); stmt.setString(6, Bstudent.getStation()); stmt.setString(7, Bstudent.getCourse()); stmt.setString(8, Bstudent.getStudendID()); int result = stmt.executeUpdate(); return (result > 0); } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getMessage()); } return false; } /** *Method updateMasterstudent will update the table with edit value in the selected row on *the Master student table. * @param Mstudent * @return <code> boolean </code> specify statement. */ public boolean updateMasterstudent(StudentProperty Mstudent) { try { String update = "UPDATE MASTERSTUDENT SET NAMEM=?, SURNAMEM=?, SUPERVISORM=?, EMAILM=?, CELLPHONENOM=?, STATIONM=? , COURSEM=? WHERE STUDENTNOM=?"; PreparedStatement stmt = conn.prepareStatement(update); stmt.setString(1, Mstudent.getName()); stmt.setString(2, Mstudent.getSurname()); stmt.setString(3, Mstudent.getSupervisor()); stmt.setString(4, Mstudent.getEmail()); stmt.setString(5, Mstudent.getCellphone()); stmt.setString(6, Mstudent.getStation()); stmt.setString(7, Mstudent.getCourse()); stmt.setString(8, Mstudent.getStudendID()); int result = stmt.executeUpdate(); return (result > 0); } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getMessage()); } return false; } /** * Method updateEquipments will update the equipment information in the table * @param equipProperty * @return */ public boolean updateEquipments(EquipmentProperty equipProperty) { String update = "UPDATE "+ getEquip().getTableName()+ " SET "+ getEquip().getEquipName()+ " =?, " +getEquip().getSerialNumber()+ " =?, "+getEquip().getNotes()+" =?, "+getEquip().getTotal() +" =?, "+getEquip().getAvail()+" =? WHERE "+getEquip().getModel()+" =? AND "+getEquip().getAssetNumber()+" =?"; try { PreparedStatement stmt = conn.prepareStatement(update); stmt.setString(1, equipProperty.getName()); stmt.setString(2, equipProperty.getSerialNumber()); stmt.setString(3, equipProperty.getNotes()); stmt.setInt(4, equipProperty.getTotal()); stmt.setBoolean(5, equipProperty.getAvailable()); stmt.setString(6, equipProperty.getModel()); stmt.setString(7, equipProperty.getAssetNumber()); int result = stmt.executeUpdate(); return (result > 0); } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getMessage()); } return false; } /** * Method updateComponentTypeA will update the component information type A. * @param editCompProperty * @return */ public boolean updateComponentTypeA(CompProperty editCompProperty) { try { String update = "UPDATE "+ getComponent().getTableName() +" SET "+ getComponent().getTotal() +"=?, "+ getComponent().getLabelColour() +"=?, " +getComponent().getOrder()+ " =? WHERE " + getComponent().getReference() +" =? AND "+ getComponent().getBin() + "=?"; PreparedStatement stmt = conn.prepareStatement(update); stmt.setInt(1, editCompProperty.getTotal()); stmt.setString(2, editCompProperty.getLabelColour()); stmt.setBoolean(3, Boolean.valueOf(editCompProperty.getOrder())); stmt.setString(4, editCompProperty.getReference()); stmt.setString(5, editCompProperty.getBin()); int result = stmt.executeUpdate(); return (result > 0); } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getMessage()); } return false; } /** *Method updateComponentTypeC will update the information of component *named by type C. * @param editTypeCPropeerty * @return */ public boolean updateComponentTypeC(CompCProperty editTypeCPropeerty) { String update = "UPDATE "+getCompTypeC().getTableName()+ " SET " +getCompTypeC().getTotal() +" =?, "+ getCompTypeC().getLabelColour()+ "= ?, "+getCompTypeC().getOrder()+ " =?, "+ getCompTypeC().getPartNumber()+ " =?, "+getCompTypeC().getPaCkage()+ " =?, "+ getCompTypeC().getDatasheet()+ "=?, "+getCompTypeC().getRsComponents()+ "=?, "+getCompTypeC().getMantech()+ "=?, "+ getCompTypeC().getCommunic()+ "=?, "+getCompTypeC().getJpElectronics()+ "=?, "+getCompTypeC().getElectronicComp()+ " =? WHERE " +getCompTypeC().getReference()+ " =? AND "+getCompTypeC().getBin()+ " =?"; try { PreparedStatement stmt = conn.prepareStatement(update); stmt.setInt(1, editTypeCPropeerty.getTotal()); stmt.setString(2, editTypeCPropeerty.getLabelColour()); stmt.setBoolean(3, editTypeCPropeerty.getOrder()); stmt.setString(4, editTypeCPropeerty.getPartNumber()); stmt.setString(5, editTypeCPropeerty.getPacKage()); stmt.setString(6, editTypeCPropeerty.getDatasheet()); stmt.setString(7, editTypeCPropeerty.getRsComponent()); stmt.setString(8, editTypeCPropeerty.getMantech()); stmt.setString(9, editTypeCPropeerty.getCommunica()); stmt.setString(10, editTypeCPropeerty.getJpElectonics()); stmt.setString(11, editTypeCPropeerty.getElectrocComp()); stmt.setString(12, editTypeCPropeerty.getReference()); stmt.setString(13, editTypeCPropeerty.getBin()); int result = stmt.executeUpdate(); return (result > 0); } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getMessage()); } return false; } /** * Method updateComponenTypeB will update the component named type B * @param editTypeBProperty * @return */ public boolean updateComponenTypeB(CompBProperty editTypeBProperty) { try { String update = "UPDATE "+getCompTypeB().getTableName()+" SET "+getCompTypeB().getPartNumber()+ " =?, "+getCompTypeB().getPaCkage()+" =?, "+getCompTypeB().getTotal()+" =?, "+ getCompTypeB().getOrdar()+" =?, "+getCompTypeB().getDatasheet()+" =?, "+ getCompTypeB().getSupplier()+" =? WHERE "+getCompTypeB().getReference()+" =? AND " +getCompTypeB().getBin()+" =?"; PreparedStatement stmt = conn.prepareStatement(update); stmt.setString(1, editTypeBProperty.getPartNumber()); stmt.setString(2, editTypeBProperty.getPackageComp()); stmt.setInt(3, editTypeBProperty.getTotal()); stmt.setBoolean(4, editTypeBProperty.getOrder()); stmt.setString(5, editTypeBProperty.getDatasheet()); stmt.setString(6, editTypeBProperty.getSupplier()); stmt.setString(7, editTypeBProperty.getReference()); stmt.setString(8, editTypeBProperty.getBin()); int result = stmt.executeUpdate(); return (result > 0); } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getMessage()); } return false; } /** * Method deleteComponentTypeB will delete the component named type B * @param tableName * @param reference * @param bin * @param selectedForDeletion * @return */ public boolean deleteComponentTypeB(String tableName, String reference, String bin, CompBProperty selectedForDeletion) { String deleteCstatement = "DELETE FROM " +tableName+ " WHERE " + reference +" = ? AND " + bin + " = ?"; System.out.println(deleteCstatement); try { PreparedStatement stmt = conn.prepareStatement(deleteCstatement); stmt.setString(1, selectedForDeletion.getReference()); stmt.setString(2, selectedForDeletion.getBin()); int res = stmt.executeUpdate(); if (res == 1) return true; } catch (SQLException e) { dialogBox("Error Occured", "Error: " +e.getMessage()); } return false; } private void dialogBox(String title, String context) { Platform.runLater(()->{ Alert alert = new Alert(AlertType.ERROR); alert.setTitle(title); alert.setContentText(context); alert.show(); }); } }
true
0d3d00f2f1e958a2f4fbe3921e57291429b0618b
Java
shanekirwan1/RMPClient
/test/com/rmp/rmpclient/controller/politician/profile/PoliticianProfileTest.java
UTF-8
931
2.546875
3
[]
no_license
package com.rmp.rmpclient.controller.politician.profile; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.Test; import com.rmp.rmpclient.politician.Image; import com.rmp.rmpclient.politician.Politician; public class PoliticianProfileTest { private PoliticianProfile profile; @Before public void setUp() throws Exception { final Politician politician = new Politician(100, "alan", "shearer", "newcastle", "boring-party"); profile = new PoliticianProfile(politician); } @Test public void testGetPoltician() { final Politician politician = profile.getPolitician(); assertNotNull(politician); // No need to test extensively, will be tested in its own class assertEquals("alan", politician.getFirstName()); } @Test public void testGetImage(){ final Image image = profile.getImage(); assertNotNull(image); } }
true
2b9dce3af22579768ffb2f2beb423f600d620e17
Java
mohamed-bourkha/Gestion-de-Commande
/src/main/java/org/sid/demo/dao/impl/LigneVenteDaoImpl.java
UTF-8
212
1.523438
2
[]
no_license
package org.sid.demo.dao.impl; import org.sid.demo.dao.ILigneVenteDao; import org.sid.demo.entities.LigneVente; public class LigneVenteDaoImpl extends GenericDaoImpl<LigneVente> implements ILigneVenteDao { }
true
4706af5f23df7c3e20b264756ca5d1e9a568dcd8
Java
Baresse/corpmanager
/src/main/java/eve/corp/manager/common/dto/Connection.java
UTF-8
3,720
2.84375
3
[ "MIT" ]
permissive
package eve.corp.manager.common.dto; import eve.corp.manager.common.enums.ConnectionOrigin; import eve.corp.manager.common.model.AuditedCharacter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * The class is used to keep a track of any connection found in the EVE API. * <p> * There are 3 types of connections : characterConnections, corporationConnections and allianceConnections. * Note a Character found as a connection by the audit will in general add a Corporation connection (his corporation) * and eventually an alliance connection (should his corp belongs to an alliance). */ public class Connection { /** * Map of character connections with characterId as Key and a ConnectionOrigin as value */ private Map<Long, Set<ConnectionOrigin>> characterConnections = new HashMap<>(); /** * Map of corporation connections with characterId as Key and a ConnectionOrigin as value */ private Map<Long, Set<ConnectionOrigin>> corporationConnections = new HashMap<>(); /** * Map of alliance connections with characterId as Key and a ConnectionOrigin as value */ private Map<Long, Set<ConnectionOrigin>> allianceConnections = new HashMap<>(); /** * Default constructor */ public Connection() { } //----------------------- Getters / Setters public Map<Long, Set<ConnectionOrigin>> getCorporationConnections() { return this.corporationConnections; } public Map<Long, Set<ConnectionOrigin>> getCharacterConnections() { return this.characterConnections; } public Map<Long, Set<ConnectionOrigin>> getAllianceConnections() { return this.allianceConnections; } /** * Add an AuditedCharacted to the connections found during the audit. * * @param character AuditedCharacted to be added as a (new) connection * @param origin Orign of the connection for this AuditedCharacted */ public void addConnection(AuditedCharacter character, ConnectionOrigin origin) { if (character != null) { long characterId = character.getCharacterID(); if (characterId != 0L) { Set<ConnectionOrigin> corporationIDs; if (!this.characterConnections.containsKey(characterId)) { corporationIDs = new HashSet<>(); this.characterConnections.put(characterId, corporationIDs); } else { corporationIDs = this.characterConnections.get(characterId); } corporationIDs.add(origin); } long corporationId = character.getCorporationID(); if (corporationId != 0L) { Set<ConnectionOrigin> allianceIDs; if (!this.corporationConnections.containsKey(corporationId)) { allianceIDs = new HashSet<>(); this.corporationConnections.put(corporationId, allianceIDs); } else { allianceIDs = this.corporationConnections.get(corporationId); } allianceIDs.add(origin); } Long allianceId = character.getAllianceID(); if (allianceId != null) { Set<ConnectionOrigin> allianceOrigins; if (!this.allianceConnections.containsKey(allianceId)) { allianceOrigins = new HashSet<>(); this.allianceConnections.put(allianceId, allianceOrigins); } else { allianceOrigins = this.allianceConnections.get(allianceId); } allianceOrigins.add(origin); } } } }
true
269548e8eff05df43f12aa6bcfdc37c262fbdf4b
Java
ALEJANDRAPONCE2116/APDM_U1
/EVA3_1_HILOS/app/src/main/java/com/example/eva3_1_multitarea/MainActivity.java
UTF-8
1,174
3.09375
3
[]
no_license
package com.example.eva3_1_multitarea; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //linux --> proceso --> tiene un hilo de ejecuciopn principal, ciclo para que bloquee el programa cierto tiempo for (int i = 0; i<10; i++){ try { Thread.sleep(1000);//DETIENE LA EJECUCI'ON DEL HILO ACTUAL 10 seg, durante 1000ms pausamos instrucciones Log.wtf("HILO PRINCIPAL", "i= "+(i+1)); //msm que muestra que el hilo principal sigue funcionando } catch (InterruptedException e) { e.printStackTrace(); } } } } //hilo de ejecucion (Thread): secuencia de instrucciones que corre el programa //hay un hilo de ejecucion principal, que controla la interfaz grafica //cuando demandamos una funcion muy pesada, se pierde la interfaz grafica porque el hilo no funciona correctamente //multitarea: multiples
true
bc8c626fe6784fb3b3a3c132140a9e45e2a3b21b
Java
saymon83/api-restful-demo
/src/main/java/com/demoapp/ptg/repositories/UserRepository.java
UTF-8
701
2.140625
2
[]
no_license
package com.demoapp.ptg.repositories; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.demoapp.ptg.models.User; public interface UserRepository extends JpaRepository<User, Long> { @Query("SELECT u FROM User u WHERE u.email = ?1") public User findByEmail(String email); @Query(" select usuario " + " from User usuario " + " where usuario.email = ?1" + " and usuario.password = ?2") Optional<User> findByEmailESenha(@Param("email") String email, @Param("password") String senha); }
true
d66a2631f306fc1aa74001ef8962a424b9a2ecca
Java
nozuonodienobb/dragger2Test
/app/src/main/java/me/xiaobai/test/dragger/ui/base/BaseActivityPresenter.java
UTF-8
647
2.1875
2
[]
no_license
package me.xiaobai.test.dragger.ui.base; import android.content.Context; import android.util.Log; import javax.inject.Inject; /** * Created by tianqing on 2018/3/1. */ public class BaseActivityPresenter<V extends BaseActivity> { protected V view; // public BaseActivityPresenter(Context context) { // this. = checkNotNull(view, "view can't to be null"); // } @Inject public BaseActivityPresenter() {} public void onDestory() { Log.i("onDestory", "ondestory"); view = null; } public void setView(V view) { Log.i("oncreate", "setView"); this.view = view; } }
true
b5a7169c36c02a1684b80a40dde959b2dd023597
Java
DongtaiS/CCCSolutions
/S2020_4.java
UTF-8
3,361
3.09375
3
[]
no_license
package cccpractice; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class S2020_4 { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int aCount = 0; int bCount = 0; int cCount = 0; StringBuffer str = new StringBuffer(br.readLine()); for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } } int total = 0; int[][] counts = new int[3][3]; List<int[][]> data = new ArrayList<>(); Arrays.fill(counts[0], 0); Arrays.fill(counts[1], 0); Arrays.fill(counts[2], 0); for (int k = 0; k < aCount; k++) { counts[0][str.codePointAt(k)-65]++; } for (int k = aCount; k < aCount+bCount; k++) { counts[1][str.codePointAt(k)-65]++; } for (int k = aCount; k < aCount+cCount; k++) { counts[2][str.codePointAt(k)-65]++; } int tempBest; int best = Math.min(aCount - counts[0][0] + bCount - counts[1][1] - Math.min(counts[0][1],counts[1][0]), aCount - counts[0][0] + cCount - counts[2][2] - Math.min(counts[0][2],counts[2][0])); for (int k = 0; k < str.length(); k++) { counts[0][str.codePointAt(k)-65]--; counts[0][str.codePointAt(checkOver(k + aCount, str.length()))-65]++; counts[1][str.codePointAt(checkOver(k + aCount, str.length()))-65]--; counts[1][str.codePointAt(checkOver(k + aCount + bCount, str.length()))-65]++; counts[2][str.codePointAt(checkOver(k + aCount, str.length()))-65]--; counts[2][str.codePointAt(checkOver(k + aCount + cCount, str.length()))-65]++; tempBest = Math.min(aCount - counts[0][0] + bCount - counts[1][1] - Math.min(counts[0][1],counts[1][0]), aCount - counts[0][0] + cCount - counts[2][2] - Math.min(counts[0][2],counts[2][0])); best = Math.min(tempBest, best); int temp = Math.max(1, (best - tempBest) / 2); if (temp > 1) { for (int i = 1; i < temp; i++) { counts[0][str.codePointAt(k+i)-65]--; counts[0][str.codePointAt(checkOver(k + aCount + i, str.length()))-65]++; counts[1][str.codePointAt(checkOver(k + aCount + i,str.length()))-65]--; counts[1][str.codePointAt(checkOver(k + aCount + bCount + i, str.length()))-65]++; } k += temp; } } System.out.println(best); } static int checkOver(int in, int limit) { if (in >= limit) { return in - limit; } else if (in < 0) { return in + limit; } return in; } }
true
361d74e66b0780651bcdf2ed0d49c3c68112bbce
Java
lgringo/dokuJClient
/src/main/java/dw/cli/commands/Searcher.java
UTF-8
1,818
2.453125
2
[ "Apache-2.0" ]
permissive
package dw.cli.commands; import java.util.List; import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.JSAPException; import com.martiansoftware.jsap.Switch; import com.martiansoftware.jsap.UnflaggedOption; import dw.xmlrpc.DokuJClient; import dw.xmlrpc.SearchResult; import dw.xmlrpc.exception.DokuException; public class Searcher extends ItemListToStringCommand<SearchResult> { @Override protected void registerParameters(JSAP jsap) throws JSAPException { jsap.registerParameter(new UnflaggedOption("searchQuery").setRequired(true)); addLongFormatSwitch(jsap); jsap.registerParameter(new Switch("snippet").setLongFlag("snippet")); } @Override protected List<SearchResult> query(DokuJClient dokuClient) throws DokuException { return dokuClient.search(_config.getString("searchQuery")); } @Override protected String itemToString(SearchResult searchResult) { String result; if ( _config.getBoolean("longFormat") ){ result = searchResultToLongString(searchResult); } else { result = searchResultToString(searchResult); } if ( _config.getBoolean("snippet") ){ result += "\n" + addSnippet( searchResult); } return result; } private String addSnippet(SearchResult searchResult) { LineConcater concater = new LineConcater(); for ( String line : searchResult.snippet().split("\n")){ concater.addLine("> " + line); } concater.addLine(""); return concater.toString(); } private String searchResultToString(SearchResult searchResult) { return searchResult.id(); } private String searchResultToLongString(SearchResult searchResult) { return searchResult.score() + " " + searchResult.mtime() + " " + searchResult.rev() + " " + searchResult.title() + " " + searchResult.size() + " " + searchResult.id(); } }
true
d378f84117335023d9ac54e83a66f048797c0ff0
Java
Abrar051/ArrayList
/ArrayList-master/MultipleInterface/Interface1.java
UTF-8
115
2.46875
2
[]
no_license
package MultipleInterface; interface Interface1 { public void printInfo1 (); public void printInfo2 (); }
true
5b1899d27cda6620dcad780b667628a810afbf95
Java
yogitamagar/SPOS
/A1_AssemblerPassOne/src/Pass1.java
UTF-8
4,940
2.84375
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; class Pass1{ int LC; String[][] opcode= new String[100][4] ; HashMap<String, String> Symbol; HashMap<String, String> lit_table; ArrayList<Integer>pool_table; ArrayList<String>index_in_lit_table ; ArrayList<String>index_in_sym_table ; Pass1(){ LC = 0; Symbol=new HashMap<String, String>(); lit_table=new HashMap<String, String>(); pool_table = new ArrayList<Integer>(); index_in_lit_table = new ArrayList<String>(); index_in_sym_table = new ArrayList<String>(); } String print() { StringBuilder s= new StringBuilder(); for(int i = 0;i<40;i++) { boolean status = false; for(int j = 0 ; j<4;j++) { if(opcode[i][j]!=null) { s.append(opcode[i][j]+" "); status = true; } } if(!status)break; s.append("\n"); } return s.toString(); } String printLIT() { StringBuilder s = new StringBuilder(); s.append("Index\tLiteral\tAddress\n"); for(int i = 0;i<index_in_lit_table.size();i++) { s.append(i+"\t"+index_in_lit_table.get(i)+"\t"+lit_table.get(index_in_lit_table.get(i))+"\n"); } return s.toString(); } String printSym() { StringBuilder s = new StringBuilder(); s.append("Index\tSymbol\tAddress\n"); for(int i = 0;i<index_in_sym_table.size();i++) { s.append(i+"\t"+index_in_sym_table.get(i)+"\t"+Symbol.get(index_in_sym_table.get(i))+"\n"); } return s.toString(); } String printpool() { StringBuilder s = new StringBuilder(); for(int i : pool_table) { s.append("#"+i+"\n"); } return s.toString(); } public int expr(String str) { int temp = 0; if (str.contains("+")) { String splits[] = str.split("\\+"); temp = Integer.parseInt(Symbol.get(splits[0])) + Integer.parseInt(splits[1]); } else if (str.contains("-")) { String splits[] = str.split("\\-"); temp = Integer.parseInt(Symbol.get(splits[0])) - Integer.parseInt(splits[1]); } else if (Symbol.containsKey(str)) { temp = Integer.parseInt(Symbol.get(str)); } else { temp = Integer.parseInt(str); } return temp; } void calculate(BufferedReader br) throws IOException { OpcodeTable opTab = new OpcodeTable(); int line_count = 0; String line; while((line = br.readLine()) != null) { String[] split_words = line.split("\\t"); if(line_count == 0 ) { if(split_words.length>1) { LC = Integer.parseInt(split_words[1]); opcode[line_count][2] = "(C,"+split_words[1]+")"; } opcode[line_count][0] = "---"; opcode[line_count][1] = "(AD,01)"; LC = LC++; } else { //if label field is not null if(split_words[0].length()>0) { if(!Symbol.containsKey(split_words[0])) index_in_sym_table.add(split_words[0]); Symbol.put(split_words[0], String.valueOf(LC)); } if(opTab.imperative.containsKey(split_words[1])) { opcode[line_count][0]=String.valueOf(LC); opcode[line_count][1]= "(IS,"+opTab.imperative.get(split_words[1])+ ")"; if(split_words.length>2) { opcode[line_count][2]= "("+opTab.impSub.get(split_words[2])+ ")"; if (split_words[3]. charAt(0)== '=') { if(!lit_table.containsKey(split_words[3])) { lit_table.put(split_words[3], "999"); index_in_lit_table.add(split_words[3]); } opcode[line_count][3]= "(L,"+index_in_lit_table.indexOf(split_words[3])+ ")"; }else { if(!Symbol.containsKey(split_words[3])) { Symbol.put(split_words[3], "999"); index_in_sym_table.add(split_words[3]); } opcode[line_count][3]= "(S,"+index_in_sym_table.indexOf(split_words[3])+ ")"; } } LC++; } else if (opTab.declarative.containsKey(split_words[1])) { opcode[line_count][0]=String.valueOf(LC); opcode[line_count][1]= "(DL,"+opTab.declarative.get(split_words[1])+ ")"; opcode[line_count][2]= "(C,"+split_words[2]+ ")"; if(split_words[1].equals("DS")) LC = LC + Integer.parseInt(split_words[2]); else LC++; } else if(opTab.directive.containsKey(split_words[1])) { opcode[line_count][0]="---"; opcode[line_count][1]= "(AD,"+opTab.directive.get(split_words[1])+ ")"; if(split_words[1].equals("LTORG") || split_words[1].equals("END")) { if(pool_table.size()==0) { pool_table.add(0); } else { pool_table.add(lit_table.size()); } for(int i = 0 ; i<index_in_lit_table.size();i++) { String addr = lit_table.get(index_in_lit_table.get(i)); if(addr.equals("999")) { lit_table.put(index_in_lit_table.get(i),String.valueOf(LC)); LC++; } } } if(split_words[1].equals("ORIGIN")) { LC = expr(split_words[2]); } if(split_words[1].equals("EQU")) { int addr = expr(split_words[2]); Symbol.put(split_words[0],String.valueOf(addr)); LC++; } } } line_count++; } } }
true
559c7c7a32495cb5ee34986c30e7d3edb0a4ef38
Java
Yarin78/advent-of-code
/src/year2015/Day17.java
UTF-8
1,028
2.765625
3
[]
no_license
package year2015; import lib.AoCBase; import lib.Kattio; public class Day17 extends AoCBase { public static void main(String[] args) { // new Day17().runStdin(); // new Day17().runSample(); // new Day17().runSampleUntilEOF(); new Day17().runTestcase(); } public void run(Kattio io) { int[] cap = new int[20]; int n = 0; for (String line : io.getLines()) { cap[n++] = Integer.parseInt(line); } int cnt = 0, best = 100; for (int i = 0; i < (1 << n); i++) { int sum = 0, t = 0; for (int j = 0; j < n; j++) { if (((1<<j) & i) > 0) { sum += cap[j]; t++; } } if (sum == 150) { if (t < best) { best = t; cnt = 1; } else if (t == best) { cnt++; } } } io.println(cnt); } }
true
d26215f9489a82170ee1f196a6ffbca6bdb6e99f
Java
seasarorg/s2directory
/s2directory/s2-directory/src/main/java/org/seasar/directory/NamingEnumerationHandler.java
UTF-8
1,256
2.09375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2005-2014 the Seasar Foundation and the Others. * * 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 org.seasar.directory; import javax.naming.NamingEnumeration; import javax.naming.NamingException; /** * 検索結果を扱うインタフェースです。 * * @author Jun Futagawa (Integsystem Corporation) */ public interface NamingEnumerationHandler { /** * 指定された検索結果を処理し、結果オブジェクトを返します。 * * @param results * 検索結果 * @param baseDn * 基底の識別名 * @return 結果オブジェクト * @throws NamingException */ public Object handle(NamingEnumeration results, String baseDn) throws NamingException; }
true
5887b6abac45e103a338e2d91e76b0997db9104e
Java
DLozanoNavas/ObjectOrientedUB
/GeometricShapes_1/src/LOGICA/cuadrado.java
UTF-8
680
2.796875
3
[]
no_license
package LOGICA; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class cuadrado { static BufferedReader entrada=new BufferedReader(new InputStreamReader(System.in)); private int lado; public cuadrado () { } public int getLado () { return lado; } public void setLado (int val) { this.lado = val; } public int areaCuadrado () { int res; res=lado*lado; return res; } public void perimetroCuadrado () { int res,num; res=4*lado; System.out.println("El perimetro del cuadrado es:"+res); } }
true
876e277d7b99738b4768c606240cbcc5cc69d256
Java
ShahmanTeh/MiFit-Java
/cn/com/smartdevices/bracelet/shoes/ui/C0659p.java
UTF-8
386
1.617188
2
[]
no_license
package cn.com.smartdevices.bracelet.shoes.ui; import android.view.View; import android.view.View.OnClickListener; class C0659p implements OnClickListener { final /* synthetic */ ShoesBindTestActivity a; C0659p(ShoesBindTestActivity shoesBindTestActivity) { this.a = shoesBindTestActivity; } public void onClick(View view) { this.a.finish(); } }
true
636bfbcf581dcab0560ae25769fb1b933fc24bf1
Java
acostarodrigo/iop-blockchain-premining
/src/org/fermat/transaction/Utils.java
UTF-8
3,117
2.71875
3
[ "MIT" ]
permissive
package org.fermat.transaction; import com.google.common.base.Preconditions; import org.fermat.Main; import org.fermatj.core.*; /** * Created by rodrigo on 7/25/16. */ public class Utils { public static final long preminedAmount = 2100000; public static void validateGenesisTransaction(Transaction tx) throws GenesisTransactionNotValidException { Preconditions.checkNotNull(tx); // if we are testing we won't require many blocks to confirm transactions. int confirmationBlockDepth; if (Main.isIsTestExecution()) confirmationBlockDepth = 1; else confirmationBlockDepth = 6; // ifg this is a test execution I will leave and ignore the conditions validation if (Main.isIsTestExecution()) return; // is already confirmed? if (tx.getConfidence().getConfidenceType() != TransactionConfidence.ConfidenceType.BUILDING || tx.getConfidence().getDepthInBlocks() < confirmationBlockDepth) throw new GenesisTransactionNotValidException("GenesisTransaction is not yet confirmed (" + tx.getConfidence().getDepthInBlocks() + "/" + confirmationBlockDepth + " blocks)! let's avoid risks and use it when confirmed."); // has only one input? if (tx.getInputs().size() != 1) throw new GenesisTransactionNotValidException("GenesisTransaction must have only one input with the total amount of funds."); } public static void validateOutgoingTransaction(Transaction tx, ECKey privateKey) throws TransactionErrorException{ // has only one input? if (tx.getInputs().size() != 1) throw new TransactionErrorException("Outgoing transaction must only have one input."); // too many outputs? if (tx.getOutputs().size() > 50) throw new TransactionErrorException("Outgoing transaction can't have more than 50 outputs."); // too few outputs. if (tx.getOutputs().size() < 2) throw new TransactionErrorException("Outgoing transaction must have at least 2 outputs! change and destination outputs are required"); // one output must be to the privateKey address. At least until we exhaust the premined funds boolean correctChange = false; for (TransactionOutput output : tx.getOutputs()){ if (output.getScriptPubKey().isSentToAddress()) if (output.getScriptPubKey().getToAddress(tx.getParams()).equals(privateKey.toAddress(tx.getParams()))) correctChange = true; } if (!correctChange) throw new TransactionErrorException("At least one output must return some funds to our own private key."); } public static ECKey getKey(String dumpedKey){ Preconditions.checkNotNull(dumpedKey); DumpedPrivateKey dumpedPrivateKey = null; try { dumpedPrivateKey = new DumpedPrivateKey(Main.getNetworkParameters(), dumpedKey); } catch (AddressFormatException e) { e.printStackTrace(); } return dumpedPrivateKey.getKey(); } }
true
ec2e3d3570c10f404106a0b358466328143cf71a
Java
chanyaz/ewe-android-hack
/project/src/main/java/com/expedia/bookings/data/trips/ItineraryManager.java
UTF-8
64,227
1.703125
2
[]
no_license
package com.expedia.bookings.data.trips; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.TimeZone; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.content.Context; import android.os.AsyncTask; import android.text.TextUtils; import android.text.format.DateUtils; import com.expedia.account.data.FacebookLinkResponse; import com.expedia.bookings.BuildConfig; import com.expedia.bookings.R; import com.expedia.bookings.data.Db; import com.expedia.bookings.data.FlightLeg; import com.expedia.bookings.data.FlightTrip; import com.expedia.bookings.data.HotelSearchParams; import com.expedia.bookings.data.PushNotificationRegistrationResponse; import com.expedia.bookings.data.User; import com.expedia.bookings.data.pos.PointOfSale; import com.expedia.bookings.data.trips.ItinShareInfo.ItinSharable; import com.expedia.bookings.data.trips.Trip.LevelOfDetail; import com.expedia.bookings.data.trips.TripComponent.Type; import com.expedia.bookings.notification.GCMRegistrationKeeper; import com.expedia.bookings.notification.Notification; import com.expedia.bookings.notification.PushNotificationUtils; import com.expedia.bookings.server.ExpediaServices; import com.expedia.bookings.server.PushRegistrationResponseHandler; import com.expedia.bookings.tracking.OmnitureTracking; import com.expedia.bookings.utils.HotelCrossSellUtils; import com.expedia.bookings.utils.JodaUtils; import com.expedia.bookings.utils.ServicesUtil; import com.expedia.bookings.widget.itin.ItinContentGenerator; import com.mobiata.android.Log; import com.mobiata.android.json.JSONUtils; import com.mobiata.android.json.JSONable; import com.mobiata.android.util.IoUtils; import com.mobiata.android.util.SettingUtils; import com.mobiata.flightlib.data.Flight; import rx.functions.Action1; /** * This singleton keeps all of our itinerary data together. It loads, syncs and stores all itin data. * <p/> * Make sure to call init() before using in the app! In addition, make sure to call startSync() * before manipulating data. * <p/> * An explanation about how the syncs happen: in order to allow syncs to be modified mid-execution, we implemented * a priority Operation queue which re-orders a series of instructions to perform a sync. * <p/> * There are essentially four steps to how Operations worked: * <p/> * 1. Initial load. This can be safely called whenever. * 2. Refresh/load trips. These steps load data from all sources. * 3. Load ancillary data about trips. For example, flight stats data about trips. Any calls beyond * our normal refresh should go here. Also, anyone who loads trip data in #2 should make sure to call * these ancillary data calls. * 4. Post-processing operations; these assume that all of the data in the itins have been loaded. These * operations include saving the loaded data to disk, generating data for the app to consume, and * registering loaded data with notifications. * <p/> * For more information, check out the Operation enum comments. */ public class ItineraryManager implements JSONable { private static final long UPDATE_CUTOFF = DateUtils.MINUTE_IN_MILLIS; // At most once a minute private static final String LOGGING_TAG = "ItineraryManager"; private static final ItineraryManager sManager = new ItineraryManager(); private ItineraryManager() { // Cannot be instantiated } public static ItineraryManager getInstance() { return sManager; } // Should be initialized from the Application so that this does not leak a component private Context mContext; // Don't try refreshing too often private long mLastUpdateTime; private Map<String, Trip> mTrips; // This is an in-memory representation of the trips. It is not // saved, but rather reproduced from the trip list. It updates // each time a sync occurs. // // It can be assumed that it is sorted at all times. private List<ItinCardData> mItinCardDatas = new ArrayList<ItinCardData>(); // These are lists of all trip start and end times; unlike mTrips, they will be loaded at app startup, so you can use them to // determine whether you should launch in itin or not. private List<DateTime> mStartTimes = new ArrayList<DateTime>(); private List<DateTime> mEndTimes = new ArrayList<DateTime>(); /** * Adds a guest trip to the itinerary list. * <p/> * Automatically starts to try to get info on the trip from the server. If a sync is already * in progress it will queue the guest trip for refresh; otherwise it will only refresh this * single guest trip. */ public void addGuestTrip(String email, String tripNumber) { Log.i(LOGGING_TAG, "Adding guest trip, email=" + email + " tripNum=" + tripNumber); if (mTrips == null) { Log.w(LOGGING_TAG, "ItineraryManager - Attempt to add guest trip, mTrips == null. Init"); mTrips = new HashMap<String, Trip>(); } Trip trip = new Trip(email, tripNumber); mTrips.put(tripNumber, trip); mSyncOpQueue.add(new Task(Operation.REFRESH_TRIP, trip)); mSyncOpQueue.add(new Task(Operation.SAVE_TO_DISK)); mSyncOpQueue.add(new Task(Operation.GENERATE_ITIN_CARDS)); mSyncOpQueue.add(new Task(Operation.SCHEDULE_NOTIFICATIONS)); mSyncOpQueue.add(new Task(Operation.REGISTER_FOR_PUSH_NOTIFICATIONS)); startSyncIfNotInProgress(); } public void removeGuestTrip(String tripNumber) { Trip trip = mTrips.get(tripNumber); if (trip == null) { Log.w(LOGGING_TAG, "Tried to remove a guest tripNumber that doesn't exist: " + tripNumber); } else if (!trip.isGuest()) { Log.w(LOGGING_TAG, "Tried to remove a non-guest trip, DENIED because only the ItinManager is allowed to do that: " + tripNumber); } else { Log.i(LOGGING_TAG, "Removing guest trip, tripNum=" + tripNumber); mTrips.remove(tripNumber); // Do not inform of removal if it was never valid (since we never informed of adding in the first place) if (trip.getLevelOfDetail() != LevelOfDetail.NONE) { onTripRemoved(trip); deletePendingNotification(trip); } } } /** * Get a list of the current Trips. * <p/> * Be warned: these Trips will be updated from a sync * operation. If this behavior seems wrong, talk with * DLew since he's open to the idea of changing this * behavior. */ public Collection<Trip> getTrips() { if (mTrips != null) { return mTrips.values(); } return null; } public List<ItinCardData> getItinCardData() { return mItinCardDatas; } /** * Get a TripComponent object from a flightHistoryId * This is useful for push notifications which provide us with a flightHistoryId as * the only identifier * <p/> * Note: We are only searching the mItinCardDatas collection, so only itins displayed * in the itin list will be searched * * @param fhid - flightHistoryId from flightstats * @return TripComponent containing the flight with the matching historyId or null */ public TripFlight getTripComponentFromFlightHistoryId(int fhid) { synchronized (mItinCardDatas) { for (ItinCardData data : mItinCardDatas) { if (data instanceof ItinCardDataFlight) { ItinCardDataFlight fData = (ItinCardDataFlight) data; if (BuildConfig.RELEASE || !SettingUtils.get(mContext, mContext.getString(R.string.preference_push_notification_any_flight), false)) { FlightLeg flightLeg = fData.getFlightLeg(); for (Flight segment : flightLeg.getSegments()) { if (segment.mFlightHistoryId == fhid) { return (TripFlight) fData.getTripComponent(); } } } else { Log.d(LOGGING_TAG, "PushNotifications returning the first flight in the itin list. Check Settings"); return (TripFlight) fData.getTripComponent(); } } } } return null; } /** * Get a ItinCardData object from a flightHistoryId * This is useful for push notifications which provide us with a flightHistoryId as * the only identifier * <p/> * Note: We are only searching the mItinCardDatas collection, so only itins displayed * in the itin list will be searched * * @param fhid - flightHistoryId from flightstats * @return ItinCardData containing the flight with the matching historyId or null */ public ItinCardData getItinCardDataFromFlightHistoryId(int fhid) { TripFlight tripFlight = getTripComponentFromFlightHistoryId(fhid); if (tripFlight != null) { synchronized (mItinCardDatas) { for (ItinCardData data : mItinCardDatas) { if (data.getTripComponent() == tripFlight) { return data; } } } } return null; } /** * Get an ItinCardData object from all known itins given a known data.getId() * * @param itinId * @return first ItinCardData found matching the passed id or null */ public ItinCardData getItinCardDataFromItinId(String itinId) { synchronized (mItinCardDatas) { for (ItinCardData data : mItinCardDatas) { if (data.getId().equals(itinId)) { return data; } } } return null; } /** * Get the Flight instances represented in our Itineraries * <p/> * Note: We are only searching the mItinCardDatas collection, so only itins displayed * in the itin list will be searched * * @param shared - if true, we return a list of shared itin flights, if false we return a list of normal itin flights * @return a list of Flight instances */ public List<Flight> getItinFlights(boolean shared) { List<Flight> retFlights = new ArrayList<Flight>(); synchronized (mItinCardDatas) { for (ItinCardData data : mItinCardDatas) { if (data.getTripComponentType() != null && data.getTripComponentType() == Type.FLIGHT && data.getTripComponent() != null && data instanceof ItinCardDataFlight) { ItinCardDataFlight dataFlight = (ItinCardDataFlight) data; boolean flightIsShared = dataFlight.getTripComponent().getParentTrip() != null && dataFlight.getTripComponent().getParentTrip().isShared(); if ((flightIsShared && shared) || (!shared && !flightIsShared)) { FlightLeg leg = dataFlight.getFlightLeg(); if (leg != null && leg.getSegments() != null) { retFlights.addAll(leg.getSegments()); } } } } } return retFlights; } /** * Clear all data from the itinerary manager. Used on sign out or * when private data is cleared. */ public void clear() { if (isSyncing()) { // If we're syncing, cancel the sync (then let the canceled task // do the sign out once it's finished). mSyncTask.cancel(true); mSyncTask.cancelDownloads(); } else { doClearData(); } } private void doClearData() { Log.i(LOGGING_TAG, "Clearing all data from ItineraryManager..."); // Delete the file, so it can't be reloaded later File file = mContext.getFileStreamPath(MANAGER_PATH); if (file.exists()) { file.delete(); } mStartTimes.clear(); mEndTimes.clear(); deleteStartAndEndTimes(); mLastUpdateTime = 0; synchronized (mItinCardDatas) { mItinCardDatas.clear(); } if (mTrips == null) { return; } Log.d(LOGGING_TAG, "Informing the removal of " + mTrips.size() + " trips due to clearing of ItineraryManager..."); for (Trip trip : mTrips.values()) { onTripRemoved(trip); } Notification.deleteAll(mContext); mTrips.clear(); // As we have no trips, we unregister all of our push notifications PushNotificationUtils.unRegister(mContext, GCMRegistrationKeeper.getInstance(mContext).getRegistrationId(mContext)); PushNotificationUtils.clearPayloadMap(); } ////////////////////////////////////////////////////////////////////////// // Data private static final String MANAGER_PATH = "itin-manager.dat"; private static final String MANAGER_START_END_TIMES_PATH = "itin-starts-and-ends.dat"; /** * Must be called before using ItineraryManager for the first time. * <p/> * I expect this to be called from the Application. That way the * context won't leak. */ public void init(Context context) { long start = System.nanoTime(); mContext = context; loadStartAndEndTimes(); Log.d(LOGGING_TAG, "Initialized ItineraryManager in " + ((System.nanoTime() - start) / 1000000) + " ms"); } private void save() { Log.i(LOGGING_TAG, "Saving ItineraryManager data..."); saveStartAndEndTimes(); try { IoUtils.writeStringToFile(MANAGER_PATH, toJson().toString(), mContext); } catch (IOException e) { Log.w(LOGGING_TAG, "Could not save ItineraryManager data", e); } } private void load() { if (mTrips == null) { File file = mContext.getFileStreamPath(MANAGER_PATH); if (file.exists()) { try { JSONObject obj = new JSONObject(IoUtils.readStringFromFile(MANAGER_PATH, mContext)); fromJson(obj); Log.i(LOGGING_TAG, "Loaded " + mTrips.size() + " trips from disk."); } catch (Exception e) { Log.w(LOGGING_TAG, "Could not load ItineraryManager data, starting from scratch again...", e); file.delete(); } } } if (mTrips == null) { mTrips = new HashMap<String, Trip>(); Log.i(LOGGING_TAG, "Starting a fresh set of itineraries."); } } ////////////////////////////////////////////////////////////////////////// // Start times data public List<DateTime> getStartTimes() { return mStartTimes; } public List<DateTime> getEndTimes() { return mEndTimes; } private void saveStartAndEndTimes() { // Sync start times whenever we save to disk mStartTimes.clear(); mEndTimes.clear(); for (Trip trip : mTrips.values()) { DateTime startDate = trip.getStartDate(); DateTime endDate = trip.getEndDate(); if (startDate != null) { mStartTimes.add(startDate); if (endDate != null) { mEndTimes.add(endDate); } else { //We want a valid date object even if it is bunk DateTime fakeEnd = new DateTime(0); mEndTimes.add(fakeEnd); } } } if (mStartTimes.size() <= 0 && mEndTimes.size() <= 0) { deleteStartAndEndTimes(); } else { try { // Save to disk JSONObject obj = new JSONObject(); JodaUtils.putDateTimeListInJson(obj, "startDateTimes", mStartTimes); JodaUtils.putDateTimeListInJson(obj, "endDateTimes", mEndTimes); IoUtils.writeStringToFile(MANAGER_START_END_TIMES_PATH, obj.toString(), mContext); } catch (Exception e) { Log.w(LOGGING_TAG, "Could not save start and end times", e); } } } private void loadStartAndEndTimes() { Log.d(LOGGING_TAG, "Loading start and end times..."); File file = mContext.getFileStreamPath(MANAGER_START_END_TIMES_PATH); if (file.exists()) { try { JSONObject obj = new JSONObject(IoUtils.readStringFromFile(MANAGER_START_END_TIMES_PATH, mContext)); mStartTimes = JodaUtils.getDateTimeListFromJsonBackCompat(obj, "startDateTimes", "startTimes"); mEndTimes = JodaUtils.getDateTimeListFromJsonBackCompat(obj, "endDateTimes", "endTimes"); } catch (Exception e) { Log.w(LOGGING_TAG, "Could not load start times", e); file.delete(); } } } private void deleteStartAndEndTimes() { File file = mContext.getFileStreamPath(MANAGER_START_END_TIMES_PATH); if (file.exists()) { file.delete(); } } ////////////////////////////////////////////////////////////////////////// // Itin card data private static final int CUTOFF_HOURS = 48; private void generateItinCardData() { synchronized (mItinCardDatas) { mItinCardDatas.clear(); DateTime pastCutOffDateTime = DateTime.now().minusHours(CUTOFF_HOURS); for (Trip trip : mTrips.values()) { if (trip.getTripComponents() != null) { List<TripComponent> components = trip.getTripComponents(true); for (TripComponent comp : components) { List<ItinCardData> items = ItinCardDataFactory.generateCardData(comp); if (items != null) { for (ItinCardData item : items) { DateTime endDate = item.getEndDate(); if (endDate != null && endDate.isAfter(pastCutOffDateTime)) { mItinCardDatas.add(item); } } } } } } Collections.sort(mItinCardDatas, mItinCardDataComparator); } } private Comparator<ItinCardData> mItinCardDataComparator = new Comparator<ItinCardData>() { @Override public int compare(ItinCardData dataOne, ItinCardData dataTwo) { // Sort by: // 1. "checkInDate" (but ignoring the time) // 2. Type (flight < car < activity < hotel < cruise) // 3. "checkInDate" (including time) // 4. Unique ID long startMillis1 = getStartMillisUtc(dataOne); long startMillis2 = getStartMillisUtc(dataTwo); int startDate1 = Integer.parseInt(SORT_DATE_FORMATTER.format(startMillis1)); int startDate2 = Integer.parseInt(SORT_DATE_FORMATTER.format(startMillis2)); // 1 int comparison = startDate1 - startDate2; if (comparison != 0) { return comparison; } // 2 comparison = dataOne.getTripComponentType().ordinal() - dataTwo.getTripComponentType().ordinal(); if (comparison != 0) { return comparison; } // 3 long millisComp = startMillis1 - startMillis2; if (millisComp > 0) { return 1; } else if (millisComp < 0) { return -1; } // 4 comparison = dataOne.getId().compareTo(dataTwo.getId()); return comparison; } }; private long getStartMillisUtc(ItinCardData data) { DateTime date = data.getStartDate(); if (date == null) { return 0; } return date.withZoneRetainFields(DateTimeZone.UTC).getMillis(); } @SuppressLint("SimpleDateFormat") private static final DateFormat SORT_DATE_FORMATTER = new SimpleDateFormat("yyyyMMdd"); static { // Try to format in UTC for comparison purposes TimeZone tz = TimeZone.getTimeZone("UTC"); if (tz != null) { SORT_DATE_FORMATTER.setTimeZone(tz); } } ////////////////////////////////////////////////////////////////////////// // Sync listener public enum SyncError { OFFLINE, USER_LIST_REFRESH_FAILURE, CANCELLED, } public interface ItinerarySyncListener { /** * Notes when a trip is added with basic info. * <p/> * Note: Guest trips will not have this called right when you add them * (because they have no meaningful info at that point, and may not * even be a valid trip). */ void onTripAdded(Trip trip); /** * Each Trip that is updated during a sync gets its own callback * so that you can update the UI before the entire sync process * is complete. * <p/> * Not all Trips may get an updated trip call (e.g., a trip doesn't * need an update because it was just updated a few minutes ago). */ void onTripUpdated(Trip trip); /** * Notification when a trip failed to update * <p/> * This can be particularly useful to know when a guest trip that * was added can't be updated at all. * <p/> * POSSIBLE TODO: info on why the update failed? */ void onTripUpdateFailed(Trip trip); public void onTripFailedFetchingGuestItinerary(); /** * Notification for when a Trip has been removed, either automatically * from a logged in user account or manually for guest trips. */ void onTripRemoved(Trip trip); /** * Notification for when a Trip added by the user is already completed + 48h */ void onCompletedTripAdded(Trip trip); /** * Notification for when a Trip added by the user has a cancelled status */ void onCancelledTripAdded(Trip trip); /** * Notification if sync itself has a failure. There can be multiple * failures during the sync process. onSyncFinished() will still * be called at the end. */ void onSyncFailure(SyncError error); /** * Once the sync process is done it returns the list of Trips as * it thinks exists. Returns all trips currently in the ItineraryManager. */ void onSyncFinished(Collection<Trip> trips); } // Makes it so you don't have to implement everything from the interface public static class ItinerarySyncAdapter implements ItinerarySyncListener { public void onTripAdded(Trip trip) { } public void onTripUpdated(Trip trip) { } public void onTripUpdateFailed(Trip trip) { } public void onTripFailedFetchingGuestItinerary() { } public void onTripRemoved(Trip trip) { } public void onCompletedTripAdded(Trip trip) { } public void onCancelledTripAdded(Trip trip) { } public void onSyncFailure(SyncError error) { } public void onSyncFinished(Collection<Trip> trips) { } } private Set<ItinerarySyncListener> mSyncListeners = new HashSet<ItineraryManager.ItinerarySyncListener>(); public void addSyncListener(ItinerarySyncListener listener) { mSyncListeners.add(listener); } public void removeSyncListener(ItinerarySyncListener listener) { mSyncListeners.remove(listener); } private void onTripAdded(Trip trip) { Set<ItinerarySyncListener> listeners = new HashSet<ItineraryManager.ItinerarySyncListener>(mSyncListeners); for (ItinerarySyncListener listener : listeners) { listener.onTripAdded(trip); } } private void onTripUpdated(Trip trip) { Set<ItinerarySyncListener> listeners = new HashSet<ItineraryManager.ItinerarySyncListener>(mSyncListeners); for (ItinerarySyncListener listener : listeners) { listener.onTripUpdated(trip); } } private void onTripUpdateFailed(Trip trip) { Set<ItinerarySyncListener> listeners = new HashSet<ItineraryManager.ItinerarySyncListener>(mSyncListeners); for (ItinerarySyncListener listener : listeners) { listener.onTripUpdateFailed(trip); } } private void onTripFailedFetchingGuestItinerary() { Set<ItinerarySyncListener> listeners = new HashSet<ItineraryManager.ItinerarySyncListener>(mSyncListeners); for (ItinerarySyncListener listener : listeners) { listener.onTripFailedFetchingGuestItinerary(); } } private void onTripRemoved(Trip trip) { Set<ItinerarySyncListener> listeners = new HashSet<ItineraryManager.ItinerarySyncListener>(mSyncListeners); for (ItinerarySyncListener listener : listeners) { listener.onTripRemoved(trip); } } private void onCompletedTripAdded(Trip trip) { Set<ItinerarySyncListener> listeners = new HashSet<ItineraryManager.ItinerarySyncListener>(mSyncListeners); for (ItinerarySyncListener listener : listeners) { listener.onCompletedTripAdded(trip); } } private void onCancelledTripAdded(Trip trip) { Set<ItinerarySyncListener> listeners = new HashSet<ItineraryManager.ItinerarySyncListener>(mSyncListeners); for (ItinerarySyncListener listener : listeners) { listener.onCancelledTripAdded(trip); } } private void onSyncFailed(SyncError error) { Set<ItinerarySyncListener> listeners = new HashSet<ItineraryManager.ItinerarySyncListener>(mSyncListeners); for (ItinerarySyncListener listener : listeners) { listener.onSyncFailure(error); } } private void onSyncFinished(Collection<Trip> trips) { Set<ItinerarySyncListener> listeners = new HashSet<ItineraryManager.ItinerarySyncListener>(mSyncListeners); for (ItinerarySyncListener listener : listeners) { listener.onSyncFinished(trips); } } ////////////////////////////////////////////////////////////////////////// // Data syncing // // Syncing is implemented as an operation queue. Operations are added // to the queue, then sorted in priority order. There is a sync looper // which executes each in order. // // There are a few advantages to this setup: // // 1. It allows anyone to enqueue operations while a sync is in progress. // No matter where you are in the sync, new operations can be added // safely and will get executed. // // 2. It allows for flexible updates. If you just need to do a deep // refresh of a single trip, that's possible using the same code that // refreshes all data. // // 3. It makes updating routes easier. For example, getting cached // details in the user list update can still get images/flight status // updates without wonky sync code. // !!!!! // // SUPER IMPORTANT, READ THIS OR I WILL HURT YOU: // The order of operations in this enum determines the priorities of each item; // the looper will pick the highest order operation to execute next. // // !!!!!! private enum Operation { LOAD_FROM_DISK, // Loads saved trips from disk, if we're just starting up REAUTH_FACEBOOK_USER, // Autologin for facebook users REFRESH_USER, // If logged in, refreshes the trip list of the user GATHER_TRIPS, // Enqueues all trips for later operation // Refresh ancillary parts of a trip; these are higher priority so that they're // completed after each trip is refreshed (for lazy loading purposes) REFRESH_TRIP_FLIGHT_STATUS, // Refreshes trip statuses on trip PUBLISH_TRIP_UPDATE, // Publishes that we've updated a trip // Refreshes trip DEEP_REFRESH_TRIP, // Refreshes a trip (deep) REFRESH_TRIP, // Refreshes a trip FETCH_SHARED_ITIN, // Fetches the shared itin data REMOVE_ITIN, // Deletes the selected itin. Currently we can only delete a shared itin. DEDUPLICATE_TRIPS, // Remove shared trip if it matches one associated to a user SHORTEN_SHARE_URLS, //We run the url shortener for itins that do not yet have shortened urls. SAVE_TO_DISK, // Saves state of ItineraryManager to disk GENERATE_ITIN_CARDS, // Generates itin card data for use SCHEDULE_NOTIFICATIONS, // Schedule local notifications REGISTER_FOR_PUSH_NOTIFICATIONS, //Tell the push server which flights to notify us about } private class Task implements Comparable<Task> { Operation mOp; Trip mTrip; String mTripNumber; public Task(Operation op) { this(op, null, null); } public Task(Operation op, Trip trip) { this(op, trip, null); } public Task(Operation op, String tripNumber) { this(op, null, tripNumber); } public Task(Operation op, Trip trip, String tripNumber) { mOp = op; mTrip = trip; mTripNumber = tripNumber; } @Override public int compareTo(Task another) { if (mOp != another.mOp) { return mOp.ordinal() - another.mOp.ordinal(); } // We can safely assume that if the ops are the same, they will both have a Trip associated if (mTrip != null) { return mTrip.compareTo(another.mTrip); } return 0; } @Override public boolean equals(Object o) { if (!(o instanceof Task)) { return false; } return compareTo((Task) o) == 0; } @Override public String toString() { String str = "task " + mOp; String tripKey = mTripNumber; if (TextUtils.isEmpty(tripKey) && mTrip != null) { tripKey = mTrip.getItineraryKey(); } if (!TextUtils.isEmpty(tripKey)) { str += " trip=" + tripKey; } return str; } } // Priority queue that doesn't allow duplicates to be added @SuppressWarnings("serial") private static class TaskPriorityQueue extends PriorityQueue<Task> { @Override public boolean add(Task o) { if (!contains(o)) { return super.add(o); } return false; } } private Queue<Task> mSyncOpQueue = new TaskPriorityQueue(); private SyncTask mSyncTask; private static final long REFRESH_TRIP_CUTOFF = 15 * DateUtils.MINUTE_IN_MILLIS; private static final long MINUTE = DateUtils.MINUTE_IN_MILLIS; private static final long HOUR = DateUtils.HOUR_IN_MILLIS; /** * Start a sync operation. * <p/> * If a sync is already in progress then calls to this are ignored. * * @return true if the sync started or is in progress, false if it never started */ public boolean startSync(boolean forceRefresh) { return startSync(forceRefresh, true, true); } public boolean startSync(boolean forceRefresh, boolean load, boolean update) { if (!forceRefresh && DateTime.now().getMillis() < UPDATE_CUTOFF + mLastUpdateTime) { Log.d(LOGGING_TAG, "ItineraryManager sync started too soon since last one; ignoring."); return false; } else if (mTrips != null && mTrips.size() == 0 && !User.isLoggedIn(mContext) && !hasFetchSharedInQueue()) { Log.d(LOGGING_TAG, "ItineraryManager sync called, but there are no guest nor shared trips and the user is not logged in, so" + " we're not starting a formal sync; but we will call onSyncFinished() with no results"); onSyncFinished(mTrips.values()); return false; } else if (isSyncing()) { Log.d(LOGGING_TAG, "Tried to start a sync while one is already in progress."); return true; } else { Log.i(LOGGING_TAG, "Starting an ItineraryManager sync..."); // Add default sync operations if (load) { mSyncOpQueue.add(new Task(Operation.LOAD_FROM_DISK)); } if (update) { mSyncOpQueue.add(new Task(Operation.REAUTH_FACEBOOK_USER)); mSyncOpQueue.add(new Task(Operation.REFRESH_USER)); mSyncOpQueue.add(new Task(Operation.GATHER_TRIPS)); mSyncOpQueue.add(new Task(Operation.DEDUPLICATE_TRIPS)); mSyncOpQueue.add(new Task(Operation.SHORTEN_SHARE_URLS)); mSyncOpQueue.add(new Task(Operation.SAVE_TO_DISK)); mSyncOpQueue.add(new Task(Operation.GENERATE_ITIN_CARDS)); mSyncOpQueue.add(new Task(Operation.SCHEDULE_NOTIFICATIONS)); mSyncOpQueue.add(new Task(Operation.REGISTER_FOR_PUSH_NOTIFICATIONS)); } startSyncIfNotInProgress(); return true; } } private static final long DEEP_REFRESH_RATE_LIMIT = DateUtils.MINUTE_IN_MILLIS; public boolean deepRefreshTrip(Trip trip) { return deepRefreshTrip(trip.getItineraryKey(), false); } public boolean deepRefreshTrip(String key, boolean doSyncIfNotFound) { Trip trip = mTrips.get(key); if (trip == null) { if (doSyncIfNotFound) { Log.i(LOGGING_TAG, "Deep refreshing trip " + key + ", trying a full refresh just in case."); // We'll try to refresh the user to find the trip mSyncOpQueue.add(new Task(Operation.REFRESH_USER)); // Refresh the trip via tripNumber; does not guarantee it will be found // by the time we get here (esp. if the user isn't logged in). mSyncOpQueue.add(new Task(Operation.DEEP_REFRESH_TRIP, key)); } else { Log.w(LOGGING_TAG, "Tried to deep refresh a trip which doesn't exist."); return false; } } else { Log.i(LOGGING_TAG, "Deep refreshing trip " + key); mSyncOpQueue.add(new Task(Operation.DEEP_REFRESH_TRIP, trip)); } // We're set to sync; add the rest of the ops and go mSyncOpQueue.add(new Task(Operation.SHORTEN_SHARE_URLS)); mSyncOpQueue.add(new Task(Operation.SAVE_TO_DISK)); mSyncOpQueue.add(new Task(Operation.GENERATE_ITIN_CARDS)); mSyncOpQueue.add(new Task(Operation.SCHEDULE_NOTIFICATIONS)); mSyncOpQueue.add(new Task(Operation.REGISTER_FOR_PUSH_NOTIFICATIONS)); startSyncIfNotInProgress(); return true; } public boolean fetchSharedItin(String shareableUrl) { Log.i(LOGGING_TAG, "Fetching SharedItin " + shareableUrl); mSyncOpQueue.add(new Task(Operation.LOAD_FROM_DISK)); mSyncOpQueue.add(new Task(Operation.FETCH_SHARED_ITIN, shareableUrl)); mSyncOpQueue.add(new Task(Operation.DEDUPLICATE_TRIPS)); mSyncOpQueue.add(new Task(Operation.SHORTEN_SHARE_URLS)); mSyncOpQueue.add(new Task(Operation.SAVE_TO_DISK)); mSyncOpQueue.add(new Task(Operation.GENERATE_ITIN_CARDS)); mSyncOpQueue.add(new Task(Operation.SCHEDULE_NOTIFICATIONS)); mSyncOpQueue.add(new Task(Operation.REGISTER_FOR_PUSH_NOTIFICATIONS)); startSyncIfNotInProgress(); return true; } public boolean removeItin(String tripNumber) { Log.i(LOGGING_TAG, "Removing Itin num = " + tripNumber); mSyncOpQueue.add(new Task(Operation.REMOVE_ITIN, tripNumber)); mSyncOpQueue.add(new Task(Operation.SAVE_TO_DISK)); mSyncOpQueue.add(new Task(Operation.GENERATE_ITIN_CARDS)); mSyncOpQueue.add(new Task(Operation.REGISTER_FOR_PUSH_NOTIFICATIONS)); startSyncIfNotInProgress(); return true; } private void startSyncIfNotInProgress() { if (!isSyncing()) { Log.i(LOGGING_TAG, "Starting a sync..."); mSyncTask = new SyncTask(); mSyncTask.execute(); } } public boolean isSyncing() { return mSyncTask != null && mSyncTask.getStatus() != AsyncTask.Status.FINISHED && !mSyncTask.finished(); } private class SyncTask extends AsyncTask<Void, ProgressUpdate, Collection<Trip>> { /* * Implementation note - we regularly check if the sync has been * cancelled (after every service call). If it has been cancelled, * then we exit out quickly. If you add any service calls, also * check afterwards (since the service calls are where the app * will get hung up during a cancel). */ private ExpediaServices mServices; // If we have not yet loaded itineraries from disk, then we skip whatever the system // requested and do a "quick sync" instead. A quick sync only loads what was on the disk // before and then organizes the data. It then calls a normal, full sync, which // will actually do a refresh in the background. private boolean mQuickSync = false; // Used for determining whether to publish an "added" or "update" when we refresh a guest trip private Set<String> mGuestTripsNotYetLoaded = new HashSet<String>(); // Earlier versions of AsyncTask do not tell you when they are cancelled correctly. // This will let us know when the AsyncTask has fully completed its mission (even // if it was cancelled). private boolean mFinished = false; // These variables are used for stat tracking private Map<Operation, Integer> mOpCount = new HashMap<ItineraryManager.Operation, Integer>(); private int mTripsRefreshed = 0; private int mTripRefreshFailures = 0; private int mTripsAdded = 0; private int mTripsRemoved = 0; private int mFlightsUpdated = 0; public SyncTask() { mServices = new ExpediaServices(mContext); for (Operation op : Operation.values()) { mOpCount.put(op, 0); } } @Override protected void onPreExecute() { if (mTrips == null) { Log.i(LOGGING_TAG, "Sync called with mTrips == null. Clearing queue and performing quick sync."); mQuickSync = true; mSyncOpQueue.clear(); mSyncOpQueue.add(new Task(Operation.LOAD_FROM_DISK)); mSyncOpQueue.add(new Task(Operation.GENERATE_ITIN_CARDS)); } } @Override protected Collection<Trip> doInBackground(Void... params) { while (!mSyncOpQueue.isEmpty()) { Task nextTask = mSyncOpQueue.remove(); Log.v(LOGGING_TAG, "Processing " + nextTask + " mQuickSync=" + mQuickSync); switch (nextTask.mOp) { case LOAD_FROM_DISK: load(); break; case REAUTH_FACEBOOK_USER: reauthFacebookUser(); break; case REFRESH_USER: refreshUserList(); break; case GATHER_TRIPS: gatherTrips(); break; case REFRESH_TRIP_FLIGHT_STATUS: updateFlightStatuses(nextTask.mTrip); break; case PUBLISH_TRIP_UPDATE: publishTripUpdate(nextTask.mTrip); break; case DEEP_REFRESH_TRIP: Trip trip = nextTask.mTrip; if (trip == null && !TextUtils.isEmpty(nextTask.mTripNumber)) { // Try to retrieve a trip here trip = mTrips.get(nextTask.mTripNumber); if (trip == null) { Log.w(LOGGING_TAG, "Could not deep refresh trip # " + nextTask.mTripNumber + "; it was not loaded as a guest trip nor user trip"); } } if (trip != null) { refreshTrip(trip, true); } break; case REFRESH_TRIP: refreshTrip(nextTask.mTrip, false); break; case DEDUPLICATE_TRIPS: deduplicateTrips(); break; case SHORTEN_SHARE_URLS: shortenSharableUrls(); break; case FETCH_SHARED_ITIN: downloadSharedItinTrip(nextTask.mTripNumber); break; case REMOVE_ITIN: removeTrip(nextTask.mTripNumber); break; case SAVE_TO_DISK: save(); break; case GENERATE_ITIN_CARDS: generateItinCardData(); break; case SCHEDULE_NOTIFICATIONS: scheduleLocalNotifications(); break; case REGISTER_FOR_PUSH_NOTIFICATIONS: registerForPushNotifications(); break; } // Update stats mOpCount.put(nextTask.mOp, mOpCount.get(nextTask.mOp) + 1); // After each task, check if we've been cancelled if (isCancelled()) { return null; } } // If we get down to here, we can assume that the operation queue is finished // and we return a list of the existing Trips. return mTrips.values(); } @Override protected void onProgressUpdate(ProgressUpdate... values) { super.onProgressUpdate(values); ProgressUpdate update = values[0]; switch (update.mType) { case ADDED: onTripAdded(update.mTrip); break; case UPDATED: onTripUpdated(update.mTrip); break; case UPDATE_FAILED: onTripUpdateFailed(update.mTrip); break; case FAILED_FETCHING_GUEST_ITINERARY: onTripFailedFetchingGuestItinerary(); break; case REMOVED: onTripRemoved(update.mTrip); break; case SYNC_ERROR: onSyncFailed(update.mError); break; case USER_ADDED_COMPLETED_TRIP: onCompletedTripAdded(update.mTrip); break; case USER_ADDED_CANCELLED_TRIP: onCancelledTripAdded(update.mTrip); break; } } @Override protected void onPostExecute(Collection<Trip> trips) { super.onPostExecute(trips); onSyncFinished(trips); logStats(); if (mQuickSync) { Log.i(LOGGING_TAG, "Quick sync completed. Starting force sync."); mFinished = true; startSync(true); } else if (User.isLoggedIn(mContext) || (trips != null && trips.size() > 0)) { // Only remember the last update time if there was something actually updated; // either the user was logged in (but had no trips) or there are guest trips // present. Also, don't bother doing this w/ quick sync as we'll just be // starting a new sync immediately (which should trigger this) mLastUpdateTime = DateTime.now().getMillis(); } } @Override protected void onCancelled() { // Currently, the only reason we are canceled is if // the user signs out mid-update. So continue // the signout in that case. doClearData(); onSyncFailed(SyncError.CANCELLED); onSyncFinished(null); logStats(); mFinished = true; } // Should be called in addition to cancel(boolean), in order // to cancel the update mid-download public void cancelDownloads() { mServices.onCancel(); } public boolean finished() { return mFinished; } private void logStats() { Log.d(LOGGING_TAG, "Sync Finished; stats below."); for (Operation op : Operation.values()) { Log.d(LOGGING_TAG, op.name() + ": " + mOpCount.get(op)); } Log.i(LOGGING_TAG, "# Trips=" + (mTrips == null ? 0 : mTrips.size()) + "; # Added=" + mTripsAdded + "; # Removed=" + mTripsRemoved); Log.i(LOGGING_TAG, "# Refreshed=" + mTripsRefreshed + "; # Failed Refresh=" + mTripRefreshFailures); Log.i(LOGGING_TAG, "# Flights Updated=" + mFlightsUpdated); } ////////////////////////////////////////////////////////////////////// // Operations private void updateFlightStatuses(Trip trip) { long now = DateTime.now().getMillis(); for (TripComponent tripComponent : trip.getTripComponents(true)) { if (tripComponent.getType() == Type.FLIGHT) { TripFlight tripFlight = (TripFlight) tripComponent; FlightTrip flightTrip = tripFlight.getFlightTrip(); for (int i = 0; i < flightTrip.getLegCount(); i++) { FlightLeg fl = flightTrip.getLeg(i); for (Flight segment : fl.getSegments()) { long takeOff = segment.getOriginWaypoint().getMostRelevantDateTime().getMillis(); long landing = segment.getArrivalWaypoint().getMostRelevantDateTime().getMillis(); long timeToTakeOff = takeOff - now; long timeSinceLastUpdate = now - segment.mLastUpdated; if (segment.mFlightHistoryId == -1) { // we have never got data from FS, so segment.mLastUpdated is unreliable at best timeSinceLastUpdate = Long.MAX_VALUE; } // Logic for whether to update; this could be compacted, but I've left it // somewhat unwound so that it can actually be understood. boolean update = false; String status = segment.mStatusCode; if (!status.equals(Flight.STATUS_CANCELLED) && !status.equals(Flight.STATUS_DIVERTED)) { // only worth updating if we haven't already hit a final state (Cancelled, Diverted) // we will potentially check after LANDED as we get updated arrival info for a little while after landing if (timeToTakeOff > 0) { if ((timeToTakeOff < HOUR * 12 && timeSinceLastUpdate > 5 * MINUTE) || (timeToTakeOff < HOUR * 24 && timeSinceLastUpdate > HOUR) || (timeToTakeOff < HOUR * 72 && timeSinceLastUpdate > 12 * HOUR)) { update = true; } } else if (now < landing && timeSinceLastUpdate > 5 * MINUTE) { update = true; } else if (now > landing) { if (now < (landing + (7 * DateUtils.DAY_IN_MILLIS)) && timeSinceLastUpdate > (now - (landing + DateUtils.HOUR_IN_MILLIS)) && timeSinceLastUpdate > 5 * MINUTE) { // flight should have landed some time in the last seven days // AND the last update was less than 1 hour after the flight should have landed (or did land) // AND the last update was more than 5 minutes ago update = true; } } } if (update) { Flight updatedFlight = mServices.getUpdatedFlight(segment); if (isCancelled()) { return; } segment.updateFrom(updatedFlight); mFlightsUpdated++; } } } } } } private void publishTripUpdate(Trip trip) { // We only consider a guest trip added once it has some meaningful info if (trip.isGuest() && mGuestTripsNotYetLoaded.contains(trip.getTripNumber())) { publishProgress(new ProgressUpdate(ProgressUpdate.Type.ADDED, trip)); mTripsAdded++; } else { publishProgress(new ProgressUpdate(ProgressUpdate.Type.UPDATED, trip)); } // POSSIBLE TODO: Only call tripUpated() when it's actually changed } private void reauthFacebookUser() { ServicesUtil.generateAccountService(mContext) .facebookReauth(mContext).doOnNext(new Action1<FacebookLinkResponse>() { @Override public void call(FacebookLinkResponse linkResponse) { if (linkResponse != null && linkResponse.isSuccess()) { Log.w(LOGGING_TAG, "FB: Autologin success"); } } }); } private void refreshTrip(Trip trip, boolean deepRefresh) { // It's possible for a trip to be removed during refresh (if it ends up being canceled // during the refresh). If it's been somehow queued for multiple refreshes (e.g., // deep refresh called during a sync) then we want to skip trying to refresh it twice. if (!mTrips.containsKey(trip.getItineraryKey())) { return; } boolean gatherAncillaryData = true; // Only update if we are outside the cutoff long now = DateTime.now().getMillis(); if (now - REFRESH_TRIP_CUTOFF > trip.getLastCachedUpdateMillis() || deepRefresh) { // Limit the user to one deep refresh per DEEP_REFRESH_RATE_LIMIT. Use cache refresh if user attempts to // deep refresh within the limit. if (now - trip.getLastFullUpdateMillis() < DEEP_REFRESH_RATE_LIMIT) { deepRefresh = false; } TripDetailsResponse response = null; if (trip.isShared()) { if (trip.hasExpired(CUTOFF_HOURS)) { Log.w(LOGGING_TAG, "Removing a shared trip because it is completed and past the cutoff. tripNum=" + trip.getItineraryKey()); Trip removeTrip = mTrips.remove(trip.getItineraryKey()); publishProgress(new ProgressUpdate(ProgressUpdate.Type.REMOVED, removeTrip)); mTripsRemoved++; return; } response = mServices.getSharedItin(trip.getShareInfo().getSharableDetailsApiUrl()); } else { response = mServices.getTripDetails(trip, !deepRefresh); } if (response == null || response.hasErrors()) { boolean isTripGuestAndFailedToRetrieve = false; if (response != null && response.hasErrors()) { Log.w(LOGGING_TAG, "Error updating trip " + trip.getItineraryKey() + ": " + response.gatherErrorMessage(mContext)); // If it's a guest trip, and we've never retrieved info on it, it may be invalid. // As such, we should remove it (but don't remove a trip if it's ever been loaded // or it's not a guest trip). if (trip.isGuest() && trip.getLevelOfDetail() == LevelOfDetail.NONE) { if (response.getErrors().size() > 0) { Log.w(LOGGING_TAG, "Tried to load guest trip, but failed, so we're removing it. Email=" + trip.getGuestEmailAddress() + " itinKey=" + trip.getItineraryKey()); mTrips.remove(trip.getItineraryKey()); isTripGuestAndFailedToRetrieve = true; } } } if (isTripGuestAndFailedToRetrieve) { publishProgress(new ProgressUpdate(ProgressUpdate.Type.FAILED_FETCHING_GUEST_ITINERARY, trip)); } else { publishProgress(new ProgressUpdate(ProgressUpdate.Type.UPDATE_FAILED, trip)); } gatherAncillaryData = false; mTripRefreshFailures++; } else { Trip updatedTrip = response.getTrip(); BookingStatus bookingStatus = updatedTrip.getBookingStatus(); if (bookingStatus == BookingStatus.SAVED && trip.getLevelOfDetail() == LevelOfDetail.NONE && trip.getLastCachedUpdateMillis() == 0) { // Normally we'd filter this out; but there is a special case wherein a guest trip is // still in a SAVED state right after booking (when we'd normally add it). So we give // any guest trip a one-refresh; if we see that it's already been tried once, we let it // die a normal death Log.w(LOGGING_TAG, "Would have removed guest trip, but it is SAVED and has never been updated."); trip.markUpdated(false); gatherAncillaryData = false; } else if (BookingStatus.filterOut(updatedTrip.getBookingStatus())) { Log.w(LOGGING_TAG, "Removing a trip because it's being filtered by booking status. tripNum=" + updatedTrip.getItineraryKey() + " status=" + bookingStatus); gatherAncillaryData = false; Trip removeTrip = mTrips.remove(updatedTrip.getItineraryKey()); publishProgress(new ProgressUpdate(ProgressUpdate.Type.REMOVED, removeTrip)); mTripsRemoved++; } else { // Update trip trip.updateFrom(updatedTrip); trip.markUpdated(deepRefresh); mTripsRefreshed++; } } } // We don't want to try to gather ancillary data if we don't have any data on the trips themselves if (trip.getLevelOfDetail() == LevelOfDetail.SUMMARY_FALLBACK) { gatherAncillaryData = false; } if (gatherAncillaryData) { mSyncOpQueue.add(new Task(Operation.REFRESH_TRIP_FLIGHT_STATUS, trip)); mSyncOpQueue.add(new Task(Operation.PUBLISH_TRIP_UPDATE, trip)); } } // If the user is logged in, retrieve a listing of current trips for logged in user private void refreshUserList() { if (!User.isLoggedIn(mContext)) { Log.d(LOGGING_TAG, "User is not logged in, not refreshing user list."); } else { // We only want to get the first N cached details if it's been more than // REFRESH_TRIP_CUTOFF since the last refresh. If we've refreshed more // recently, then we only want to update individual trips as is necessary // (so that the summary call goes out quickly). boolean getCachedDetails = DateTime.now().getMillis() - REFRESH_TRIP_CUTOFF > mLastUpdateTime; Log.d(LOGGING_TAG, "User is logged in, refreshing the user list. Using cached details call: " + getCachedDetails); TripResponse response = mServices.getTrips(getCachedDetails); if (isCancelled()) { return; } if (response == null || response.hasErrors()) { if (response != null && response.hasErrors()) { Log.w(LOGGING_TAG, "Error updating trips: " + response.gatherErrorMessage(mContext)); } publishProgress(new ProgressUpdate(SyncError.USER_LIST_REFRESH_FAILURE)); } else { Set<String> currentTrips = new HashSet<String>(mTrips.keySet()); for (Trip trip : response.getTrips()) { if (BookingStatus.filterOut(trip.getBookingStatus())) { continue; } String tripKey = trip.getItineraryKey(); LevelOfDetail lod = trip.getLevelOfDetail(); boolean hasFullDetails = lod == LevelOfDetail.FULL || lod == LevelOfDetail.SUMMARY_FALLBACK; if (!mTrips.containsKey(tripKey)) { mTrips.put(tripKey, trip); publishProgress(new ProgressUpdate(ProgressUpdate.Type.ADDED, trip)); mTripsAdded++; } else if (hasFullDetails) { mTrips.get(tripKey).updateFrom(trip); } if (hasFullDetails) { // If we have full details, mark this as recently updated so we don't // refresh it below trip.markUpdated(false); mTripsRefreshed++; } if (trip.getAirAttach() != null && !trip.isShared()) { Db.getTripBucket().setAirAttach(trip.getAirAttach()); } currentTrips.remove(tripKey); } // Remove all trips that were not returned by the server (not including guest trips or imported shared trips) for (String tripNumber : currentTrips) { Trip trip = mTrips.get(tripNumber); if (!trip.isGuest() && !trip.isShared()) { trip = mTrips.remove(tripNumber); publishProgress(new ProgressUpdate(ProgressUpdate.Type.REMOVED, trip)); mTripsRemoved++; } } } } } // Add all trips to be updated, even ones that may not need to be refreshed // (so we can see if any of the ancillary data needs to be refreshed). private void gatherTrips() { Log.i(LOGGING_TAG, "Gathering " + mTrips.values().size() + " trips..."); for (Trip trip : mTrips.values()) { mSyncOpQueue.add(new Task(Operation.REFRESH_TRIP, trip)); if (trip.isGuest() && trip.getLevelOfDetail() == LevelOfDetail.NONE) { mGuestTripsNotYetLoaded.add(trip.getTripNumber()); } } } private void deduplicateTrips() { Map<String, String> sharedTripsMap = new HashMap<String, String>(); Set<String> sharedTripsToRemove = new HashSet<String>(); // Collect all of the shared trips for (Trip trip : mTrips.values()) { if (trip.isShared()) { sharedTripsMap.put(trip.getTripComponents().get(0).getUniqueId(), trip.getItineraryKey()); } } // Check each "regular" trip and see if it matches one of the shared trips for (Trip trip : mTrips.values()) { if (!trip.isShared()) { for (TripComponent tc : trip.getTripComponents()) { if (sharedTripsMap.keySet().contains(tc.getUniqueId())) { sharedTripsToRemove.add(sharedTripsMap.get(tc.getUniqueId())); } } } } // Remove the shared trips Trip trip; for (String key : sharedTripsToRemove) { Log.i(LOGGING_TAG, "Removing duplicate shared itin key=" + key); trip = mTrips.remove(key); publishProgress(new ProgressUpdate(ProgressUpdate.Type.REMOVED, trip)); mTripsRemoved++; } } private void removeTrip(String tripNumber) { Trip trip = mTrips.get(tripNumber); if (trip == null) { Log.w(LOGGING_TAG, "Tried to remove a tripNumber that doesn't exist: " + tripNumber); } else if (!trip.isShared()) { Log.w(LOGGING_TAG, "Tried to remove a non-shared trip, DENIED because we can only remove sharedItins # " + tripNumber); } else { Log.i(LOGGING_TAG, "Removing trip with # " + tripNumber); mTrips.remove(tripNumber); publishProgress(new ProgressUpdate(ProgressUpdate.Type.REMOVED, trip)); // Delete notifications if any. deletePendingNotification(trip); mTripsRemoved++; } } private void downloadSharedItinTrip(String shareableUrl) { Log.i(LOGGING_TAG, "Creating shared itin placeholder " + shareableUrl); // Create a placeholder trip for this shared itin so that the ItineraryManager knows to // notify the UI to show loading indicator. Trip trip = new Trip(); trip.setIsShared(true); trip.getShareInfo().setSharableDetailsUrl(shareableUrl); mTrips.put(shareableUrl, trip); Log.i(LOGGING_TAG, "Fetching shared itin " + shareableUrl); // We need to replace the /m with /api to get the json response. String shareableAPIUrl = ItinShareInfo.convertSharableUrlToApiUrl(shareableUrl); TripDetailsResponse response = mServices.getSharedItin(shareableAPIUrl); if (isCancelled()) { return; } if (response == null || response.hasErrors()) { if (response != null && response.hasErrors()) { Log.w(LOGGING_TAG, "Error fetching shared itin : " + response.gatherErrorMessage(mContext)); } removeItin(shareableUrl); } else { Trip sharedTrip = response.getTrip(); sharedTrip.setIsShared(true); // Stuff the URL in the parent trip for later retrieval in case the sharee wants to become a sharer. // This response does not contain any shareable url, so, we gotta save it for later on our own. sharedTrip.getShareInfo().setSharableDetailsUrl(shareableUrl); if (sharedTrip.hasExpired(CUTOFF_HOURS)) { publishProgress(new ProgressUpdate(ProgressUpdate.Type.USER_ADDED_COMPLETED_TRIP, sharedTrip)); // Remove placeholder for loading removeItin(shareableUrl); return; } if (sharedTrip.getBookingStatus() == BookingStatus.CANCELLED) { publishProgress(new ProgressUpdate(ProgressUpdate.Type.USER_ADDED_CANCELLED_TRIP, sharedTrip)); // Remove placeholder for loading removeItin(shareableUrl); return; } LevelOfDetail lod = sharedTrip.getLevelOfDetail(); boolean hasFullDetails = lod == LevelOfDetail.FULL || lod == LevelOfDetail.SUMMARY_FALLBACK; if (!mTrips.containsKey(shareableUrl)) { mTrips.put(shareableUrl, sharedTrip); publishProgress(new ProgressUpdate(ProgressUpdate.Type.ADDED, sharedTrip)); mTripsAdded++; } else if (hasFullDetails) { mTrips.get(shareableUrl).updateFrom(sharedTrip); } if (hasFullDetails) { // If we have full details, mark this as recently updated so we don't // refresh it below sharedTrip.markUpdated(false); mTripsRefreshed++; mSyncOpQueue.add(new Task(Operation.REFRESH_TRIP_FLIGHT_STATUS, sharedTrip)); } if (trip.getAirAttach() != null && !trip.isShared()) { Db.getTripBucket().setAirAttach(trip.getAirAttach()); } // Note: In the future, we may be getting these parameters from the URL. Currently, we do not, thus we just // send the generic "AppShare" event any time that we import a shared itin. Ideally, the URL will contain // some more info pertaining to tracking and we'd send something like "AppShare.Facebook". OmnitureTracking.setDeepLinkTrackingParams("brandcid", "AppShare"); } } private void shortenSharableUrls() { Log.d(LOGGING_TAG, "ItineraryManager.shortenSharableUrls"); for (Trip trip : mTrips.values()) { for (TripComponent tripComp : trip.getTripComponents()) { //For packages we have to shorten the share urls of the individual pieces. if (tripComp.getType() == Type.PACKAGE) { TripPackage pack = (TripPackage) tripComp; for (TripComponent packComp : pack.getTripComponents()) { if (packComp.getType() == Type.FLIGHT) { //For flights we have to shorten share urls for individual legs shortenSharableFlightUrls((TripFlight) packComp); } else { shortenSharableUrl(packComp); } } } else if (tripComp.getType() == Type.FLIGHT) { //For flights we have to shorten share urls for individual legs shortenSharableFlightUrls((TripFlight) tripComp); } } //Shorten the trip share url shortenSharableUrl(trip); } } private void shortenSharableFlightUrls(TripFlight trip) { if (trip.getFlightTrip() != null && trip.getFlightTrip().getLegCount() > 0) { for (FlightLeg leg : trip.getFlightTrip().getLegs()) { shortenSharableUrl(leg); } } } private void shortenSharableUrl(ItinSharable itinSharable) { if (itinSharable.getSharingEnabled() && itinSharable.getShareInfo().hasSharableDetailsUrl() && !itinSharable.getShareInfo().hasShortSharableDetailsUrl()) { String shareUrl = itinSharable.getShareInfo().getSharableDetailsUrl(); String shortenedUrl = null; Log.i(LOGGING_TAG, "Shortening share url:" + shareUrl); TripShareUrlShortenerResponse response = mServices.getShortenedShareItinUrl(shareUrl); if (response != null) { shortenedUrl = response.getShortUrl(); } if (!TextUtils.isEmpty(shortenedUrl)) { Log.i(LOGGING_TAG, "Successfully shortened url - original:" + shareUrl + " short:" + shortenedUrl); itinSharable.getShareInfo().setShortSharableDetailsUrl(shortenedUrl); } else { Log.w(LOGGING_TAG, "Failure to shorten url:" + shareUrl); } } } } private static class ProgressUpdate { public enum Type { ADDED, UPDATED, UPDATE_FAILED, FAILED_FETCHING_GUEST_ITINERARY, REMOVED, SYNC_ERROR, USER_ADDED_COMPLETED_TRIP, USER_ADDED_CANCELLED_TRIP, } public Type mType; public Trip mTrip; public SyncError mError; public ProgressUpdate(Type type, Trip trip) { mType = type; mTrip = trip; } public ProgressUpdate(SyncError error) { mType = Type.SYNC_ERROR; mError = error; } } ////////////////////////////////////////////////////////////////////////// // Air Attach // // Note: This code was ripped from ItinCardDataAdapter.addAttachData // TODO consolidate implementations, write unit tests public HotelSearchParams getHotelSearchParamsForAirAttach() { List<ItinCardData> itinCardDatas = mItinCardDatas; // Nothing to do if there are no itineraries int len = itinCardDatas.size(); if (len == 0) { return null; } boolean isUserAirAttachQualified = Db.getTripBucket() != null && Db.getTripBucket().isUserAirAttachQualified(); for (int i = 0; i < len; i++) { ItinCardData data = itinCardDatas.get(i); if (data instanceof ItinCardDataFlight) { ItinCardDataFlight itinCardDataFlight = (ItinCardDataFlight) data; boolean showAirAttach = itinCardDataFlight.showAirAttach(); // Check if user qualifies for air attach if (isUserAirAttachQualified && showAirAttach) { return HotelCrossSellUtils .generateHotelSearchParamsFromItinData((TripFlight) itinCardDataFlight.getTripComponent(), itinCardDataFlight.getFlightLeg(), itinCardDataFlight.getNextFlightLeg()); } } } return null; } ////////////////////////////////////////////////////////////////////////// // Push Notifications private PushNotificationRegistrationResponse registerForPushNotifications() { Log.d(LOGGING_TAG, "ItineraryManager.registerForPushNotifications"); //NOTE: If this is the first time we are registering for push notifications, regId will likely be empty //we need to wait for a gcm callback before we will get a regid, so we just skip for now and wait for the next sync //at which time we should have a valid id (assuming network is up and running) String regId = GCMRegistrationKeeper.getInstance(mContext).getRegistrationId(mContext); Log.d(LOGGING_TAG, "ItineraryManager.registerForPushNotifications regId:" + regId); if (!TextUtils.isEmpty(regId)) { Log.d(LOGGING_TAG, "ItineraryManager.registerForPushNotifications regId:" + regId + " is not empty!"); ExpediaServices services = new ExpediaServices(mContext); int siteId = PointOfSale.getPointOfSale().getSiteId(); long userTuid = 0; if (User.isLoggedIn(mContext)) { if (Db.getUser() == null) { Db.loadUser(mContext); } if (Db.getUser() != null && Db.getUser().getPrimaryTraveler() != null) { userTuid = Db.getUser().getPrimaryTraveler().getTuid(); } } JSONObject payload = PushNotificationUtils.buildPushRegistrationPayload(mContext, regId, siteId, userTuid, getItinFlights(false), getItinFlights(true)); Log.d(LOGGING_TAG, "registerForPushNotifications payload:" + payload.toString()); PushNotificationRegistrationResponse resp = services.registerForPushNotifications( new PushRegistrationResponseHandler(mContext), payload, regId); Log.d(LOGGING_TAG, "registerForPushNotifications response:" + (resp == null ? "null" : resp.getSuccess())); return resp; } return null; } ////////////////////////////////////////////////////////////////////////// // Local Notifications private void scheduleLocalNotifications() { synchronized (mItinCardDatas) { for (ItinCardData data : mItinCardDatas) { // #2224 disable local notifications for shared itineraries. if (data.isSharedItin()) { continue; } ItinContentGenerator<?> generator = ItinContentGenerator.createGenerator(mContext, data); List<Notification> notifications = generator.generateNotifications(); if (notifications == null) { continue; } for (Notification notification : notifications) { // If we already have this notification, don't notify again. if (Notification.hasExisting(notification)) { Notification existing = Notification.findExisting(notification); // These things could possibly change on a new build. existing.setItinId(notification.getItinId()); existing.setTriggerTimeMillis(notification.getTriggerTimeMillis()); existing.setExpirationTimeMillis(notification.getExpirationTimeMillis()); existing.setIconResId(notification.getIconResId()); existing.setImageResId(notification.getImageResId()); existing.setTitle(notification.getTitle()); existing.setBody(notification.getBody()); existing.setTicker(notification.getTicker()); existing.setFlags(notification.getFlags()); notification = existing; } String time = com.expedia.bookings.utils.DateUtils .convertMilliSecondsForLogging(notification.getTriggerTimeMillis()); Log.i(LOGGING_TAG, "Notification scheduled for " + time); // This is just to get the notifications to show up frequently for development if (BuildConfig.DEBUG) { String which = SettingUtils.get(mContext, R.string.preference_which_api_to_use_key, ""); if (which.equals("Mock Mode")) { notification.setTriggerTimeMillis(System.currentTimeMillis() + 5000); notification.setExpirationTimeMillis(System.currentTimeMillis() + DateUtils.DAY_IN_MILLIS); notification.setStatus(com.expedia.bookings.notification.Notification.StatusType.NEW); } } notification.save(); } } } Notification.scheduleAll(mContext); Notification.cancelAllExpired(mContext); } private void deletePendingNotification(Trip trip) { List<TripComponent> components = trip.getTripComponents(true); if (components == null) { return; } for (TripComponent tc : components) { String itinId = tc.getUniqueId(); Notification.deleteAll(mContext, itinId); } } private boolean hasFetchSharedInQueue() { for (Task task : mSyncOpQueue) { if (task.mOp == Operation.FETCH_SHARED_ITIN) { return true; } } return false; } ////////////////////////////////////////////////////////////////////////// // JSONable // // Please don't actually try to serialize this object; this is mostly for // ease of being able to internally save/reproduce this manager. @Override public JSONObject toJson() { try { JSONObject obj = new JSONObject(); JSONUtils.putJSONableList(obj, "trips", mTrips.values()); return obj; } catch (JSONException e) { throw new RuntimeException(e); } } @Override public boolean fromJson(JSONObject obj) { mTrips = new HashMap<>(); List<Trip> trips = JSONUtils.getJSONableList(obj, "trips", Trip.class); for (Trip trip : trips) { mTrips.put(trip.getItineraryKey(), trip); } return true; } }
true
f838dd648c28b6d3fa5bfa9176ec138998421f78
Java
supercoeus/Fawns
/app/src/main/java/com/fawns/app/ui/base/BaseActivity.java
UTF-8
3,149
2.015625
2
[]
no_license
package com.fawns.app.ui.base; import android.content.Context; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import com.fawns.app.GlobalApplication; import com.fawns.app.R; import com.fawns.app.view.base.BaseView; import com.obsessive.library.base.BaseAppCompatActivity; import com.umeng.analytics.MobclickAgent; import butterknife.ButterKnife; /** * Project Fawns * Package com.fawns.app.ui.base * Author Mengjiaxin * Date 2016/4/11 14:41 * Desc 通用的Activity */ public abstract class BaseActivity extends BaseAppCompatActivity implements BaseView { protected Toolbar mToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (isApplyKitKatTranslucency()) { setSystemBarTintDrawable(getResources().getDrawable(R.drawable.sr_primary)); } } @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); mToolbar = ButterKnife.findById(this, R.id.common_toolbar); if (null != mToolbar) { setTitle(setToolbarTitle()); setSupportActionBar(mToolbar); if(isBackHomeButtonEnabled()){ getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } } @Override protected void onResume() { super.onResume(); // 通过umeng统计页面访问次数 MobclickAgent.onPageStart(setToolbarTitle()); MobclickAgent.onResume(this); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPageEnd(setToolbarTitle()); MobclickAgent.onPause(this); } protected GlobalApplication getBaseApplication() { return (GlobalApplication) getApplication(); } @Override public void showError(String msg) { toggleShowError(true, msg, null); } @Override public void showException(String msg) { toggleShowError(true, msg, null); } @Override public void showNetError() { toggleNetworkError(true, null); } @Override public void showLoading(String msg) { toggleShowLoading(true, null); } @Override public void hideLoading() { toggleShowLoading(false, null); } protected abstract boolean isBackHomeButtonEnabled(); protected abstract boolean isApplyKitKatTranslucency(); /** * setTitle */ protected abstract String setToolbarTitle(); protected void hideKeyboard(EditText editText) { InputMethodManager imm = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); } protected void showKeyboard(EditText editText) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED); } }
true
60febdbc67aa9f7330d8e910603401df099fa5da
Java
bambuser/react-native-bambuser-player
/android/src/main/java/com/bambuserplayer/BambuserPlayerView.java
UTF-8
9,801
1.867188
2
[]
no_license
package com.bambuserplayer; import android.content.Context; import android.graphics.Color; import android.os.Handler; import android.os.Looper; import android.util.AttributeSet; import android.widget.RelativeLayout; import com.bambuser.broadcaster.BroadcastPlayer; import com.bambuser.broadcaster.PlayerState; import com.bambuser.broadcaster.SurfaceViewWithAutoAR; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.uimanager.ThemedReactContext; /** * Copyright Bambuser AB 2018 */ public class BambuserPlayerView extends RelativeLayout { BambuserPlayerViewViewManager manager; RelativeLayout mWrapperLayout; SurfaceViewWithAutoAR mVideoSurfaceView; BroadcastPlayer mBroadcastPlayer; String _resourceUri; String _applicationId; String _videoScaleMode = "aspectFit"; BroadcastPlayer.AcceptType _requiredBroadcastState = BroadcastPlayer.AcceptType.ANY; boolean _timeShiftMode = false; float _volume = 0.5f; int _duration = -1; BroadcastPlayer.LatencyMode _latencyMode = BroadcastPlayer.LatencyMode.LOW; final Handler mMainThreadHandler = new Handler(Looper.getMainLooper()); public BambuserPlayerView(ThemedReactContext context, BambuserPlayerViewViewManager manager) { super(context); this.manager = manager; init(null, 0); } public BambuserPlayerView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } private void init(AttributeSet attrs, int defStyle) { setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); mWrapperLayout = new RelativeLayout(getContext()); mWrapperLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); mWrapperLayout.setBackgroundColor(Color.parseColor("#000000")); addView(mWrapperLayout); mVideoSurfaceView = new SurfaceViewWithAutoAR(getContext()); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); mWrapperLayout.addView(mVideoSurfaceView, layoutParams); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { mWrapperLayout.layout(0, 0, right, bottom); if (indexOfChild(mWrapperLayout) != 0) { removeView(mWrapperLayout); addView(mWrapperLayout, 0); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); WritableMap event = new WritableNativeMap(); sendEvent(event, "onReady"); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); } boolean playerExists() { return (mBroadcastPlayer != null); } void play() { if (playerExists()) { if (mBroadcastPlayer.getState() != PlayerState.CLOSED) { mBroadcastPlayer.start(); return; } } loadAndPlay(); } void pause() { if (playerExists()) { if (mBroadcastPlayer.isPlaying()) { mBroadcastPlayer.pause(); } } } void stop() { if (playerExists()) { mBroadcastPlayer.close(); mBroadcastPlayerObserver.onStateChange(PlayerState.CLOSED); } } void seekTo(int position) { int positionInMs = position * 1000; if (positionInMs < 0) positionInMs = 0; if (playerExists()) { if (mBroadcastPlayer.getState() != PlayerState.CLOSED) { mBroadcastPlayer.seekTo(positionInMs); sendOnProgressUpdate(); } } } void setApplicationId(String applicationId) { if (applicationId != null) { _applicationId = applicationId; } } void setResourceUri(String resourceUri) { if (resourceUri != null) { _resourceUri = resourceUri; } } void setVideoScaleMode(String videoScaleMode) { if (videoScaleMode != null) { _videoScaleMode = videoScaleMode; } } void setRequiredBroadcastState(BroadcastPlayer.AcceptType requiredBroadcastState) { if (requiredBroadcastState != null) { _requiredBroadcastState = requiredBroadcastState; } } void setLatencyMode(BroadcastPlayer.LatencyMode latencyMode) { if (latencyMode != null) { _latencyMode = latencyMode; } } void setTimeShiftMode(boolean timeShiftMode) { _timeShiftMode = timeShiftMode; } void setVolume(float volume) { _volume = volume; if (playerExists()) { mBroadcastPlayer.setAudioVolume(_volume); } } void loadAndPlay() { if (playerExists()) { mBroadcastPlayer.close(); } switch (_videoScaleMode) { case "aspectFit": mVideoSurfaceView.setCropToParent(false); break; case "aspectFill": mVideoSurfaceView.setCropToParent(true); break; case "scaleToFill": mVideoSurfaceView.setCropToParent(false); break; } _duration = -1; mBroadcastPlayer = null; mBroadcastPlayer = new BroadcastPlayer(getContext(), _resourceUri, _applicationId, mBroadcastPlayerObserver); mBroadcastPlayer.setViewerCountObserver(mBroadcastViewerCountObserver); mBroadcastPlayer.setTimeshiftMode(_timeShiftMode); mBroadcastPlayer.setAcceptType(_requiredBroadcastState); mBroadcastPlayer.setLatencyMode(_latencyMode); mBroadcastPlayer.setSurfaceView(mVideoSurfaceView); mBroadcastPlayer.setAudioVolume(_volume); mBroadcastPlayer.load(); } void sendOnProgressUpdate() { if (playerExists()) { WritableMap event = new WritableNativeMap(); boolean live = mBroadcastPlayer.isTypeLive(); event.putString("live", String.valueOf(live)); int position = mBroadcastPlayer.getCurrentPosition(); event.putString("currentPosition", String.valueOf(position / 1000)); int duration = mBroadcastPlayer.getDuration(); if (duration > -1) { event.putString("duration", String.valueOf(duration / 1000)); } sendEvent(event, "onProgressUpdate"); } } private final Runnable mProgressRunnable = new Runnable() { @Override public void run() { sendOnProgressUpdate(); mMainThreadHandler.postDelayed(mProgressRunnable, 1000); } }; void startTimer() { stopTimer(); mMainThreadHandler.postDelayed(mProgressRunnable, 1000); } void stopTimer() { mMainThreadHandler.removeCallbacks(mProgressRunnable); } BroadcastPlayer.Observer mBroadcastPlayerObserver = new BroadcastPlayer.Observer() { @Override public void onStateChange(PlayerState playerState) { WritableMap event = new WritableNativeMap(); switch (playerState) { case CONSTRUCTION: break; case LOADING: sendEvent(event, "onLoading"); break; case BUFFERING: break; case PLAYING: sendEvent(event, "onPlaying"); startTimer(); break; case PAUSED: sendEvent(event, "onPaused"); stopTimer(); break; case COMPLETED: sendEvent(event, "onPlaybackComplete"); stopTimer(); break; case ERROR: sendEvent(event, "onPlaybackError"); stopTimer(); break; case CLOSED: sendEvent(event, "onStopped"); stopTimer(); break; } } @Override public void onBroadcastLoaded(boolean live, int width, int height) { requestLayout(); } }; BroadcastPlayer.ViewerCountObserver mBroadcastViewerCountObserver = new BroadcastPlayer.ViewerCountObserver() { @Override public void onCurrentViewersUpdated(long l) { WritableMap event = new WritableNativeMap(); event.putString("viewers", String.valueOf(l)); sendEvent(event, "onCurrentViewerCountUpdate"); } @Override public void onTotalViewersUpdated(long l) { WritableMap event = new WritableNativeMap(); event.putString("viewers", String.valueOf(l)); sendEvent(event, "onTotalViewerCountUpdate"); } }; @Override public void requestLayout() { super.requestLayout(); post(measureAndLayout); } private final Runnable measureAndLayout = new Runnable() { @Override public void run() { measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY)); layout(getLeft(), getTop(), getRight(), getBottom()); } }; private void sendEvent(WritableMap event, String name) { if (manager != null) { manager.pushEvent((ThemedReactContext) getContext(), this, name, event); } } }
true
aa7bc5036349412f292a6835b802ab66f634d9e5
Java
binduak/Transformers-service
/TW-Bootcamp/src/main/java/com/tw/dao/impl/CategoryDAOImpl.java
UTF-8
2,654
2.3125
2
[]
no_license
package com.tw.dao.impl; import java.util.List; import javax.persistence.NoResultException; import javax.persistence.Query; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Repository; import com.tw.dao.ICategoryDAO; import com.tw.entity.Category; import com.tw.exception.DAOException; import com.tw.exception.TakeAwayApplicationExceptionUtlility; import com.tw.utility.ApplicationUtility; @Repository("categoryDAO") public class CategoryDAOImpl extends AbstractEntityDAOImpl <Category, Long> implements ICategoryDAO { /* (non-Javadoc) * @see com.tw.dao.impl.CategoryDAO#fecthCategoryResponse() */ @SuppressWarnings("unchecked") @Override public List<Category> fecthAllCategory () { log.debug(ApplicationUtility.ENTER_METHOD + "fecthAllCategory"); try { Query getCategoryQuery = getEntityManager().createNamedQuery("getAllCategory"); List<Category> fetchedCategoryList =getCategoryQuery.getResultList(); if (fetchedCategoryList != null && fetchedCategoryList.size() >0) { log.debug(ApplicationUtility.EXIT_METHOD + "fecthAllCategory"); return fetchedCategoryList; } throw new DAOException(TakeAwayApplicationExceptionUtlility.NO_CATEGORY_FOUND_ERROR_MESSAGE, TakeAwayApplicationExceptionUtlility.NO_CATEGORY_FOUND_ERROR_CODE); }catch (DataAccessException exception) { log.error(exception); throw new DAOException(TakeAwayApplicationExceptionUtlility.DATABASE_ERROR_MESSAGE ,TakeAwayApplicationExceptionUtlility.DATABASE_ERROR_CODE,exception); } } @Override public boolean validateCategoryByNameAndId (Category toValidateCateegory) { log.debug(ApplicationUtility.ENTER_METHOD + "fecthAllCategory"); try { Query getCategoryValdiateQuery = getEntityManager().createNamedQuery("validateCategoryByNameAndId"); getCategoryValdiateQuery.setParameter("validateCategoryId", toValidateCateegory.getCategoryId()); getCategoryValdiateQuery.setParameter("validateCategoryName", toValidateCateegory.getCategoryName()); Category fetchedCategory = (Category) getCategoryValdiateQuery.getSingleResult(); if (fetchedCategory != null && fetchedCategory.getCategoryId() >0) { log.debug(ApplicationUtility.EXIT_METHOD + "fecthAllCategory"); return true; } return false; }catch (NoResultException noResultException) { log.warn( toValidateCateegory , noResultException); return false; }catch (DataAccessException exception) { log.error(exception); throw new DAOException(TakeAwayApplicationExceptionUtlility.DATABASE_ERROR_MESSAGE ,TakeAwayApplicationExceptionUtlility.DATABASE_ERROR_CODE,exception); } } }
true
80aded4b2f1254585a6a8124b3f3e890fbce2005
Java
sgraband/cmmn-editor
/server/resources.tests/src/org/eclipse/emfcloud/metamodel/CMMN/tests/DecoratorTest.java
UTF-8
1,428
1.90625
2
[]
no_license
/** */ package org.eclipse.emfcloud.metamodel.CMMN.tests; import junit.textui.TestRunner; import org.eclipse.emfcloud.metamodel.CMMN.CMMNFactory; import org.eclipse.emfcloud.metamodel.CMMN.Decorator; /** * <!-- begin-user-doc --> * A test case for the model object '<em><b>Decorator</b></em>'. * <!-- end-user-doc --> * @generated */ public class DecoratorTest extends CMMNElementTest { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static void main(String[] args) { TestRunner.run(DecoratorTest.class); } /** * Constructs a new Decorator test case with the given name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DecoratorTest(String name) { super(name); } /** * Returns the fixture for this Decorator test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected Decorator getFixture() { return (Decorator)fixture; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#setUp() * @generated */ @Override protected void setUp() throws Exception { setFixture(CMMNFactory.eINSTANCE.createDecorator()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#tearDown() * @generated */ @Override protected void tearDown() throws Exception { setFixture(null); } } //DecoratorTest
true
63a51ac016a02eded40536d0e9ee161d4d63c78f
Java
furkansefademirci/JavaCamp
/hrms/src/main/java/com/fsd/hrms/dataAccess/abstracts/UserDao.java
UTF-8
301
1.953125
2
[]
no_license
package com.fsd.hrms.dataAccess.abstracts; import com.fsd.hrms.entities.concretes.Users; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface UserDao extends JpaRepository<Users,Integer> { List<Users> findUsersByEmail(String email); }
true
8b4500eb3d8a1aa0781ac77cebd223416eb4e595
Java
HakimB/tamago
/TamagoCC/source/tamagocc/api/TState.java
UTF-8
394
2.15625
2
[]
no_license
package tamagocc.api; import java.util.Iterator; /** * This interface represents a state in the service behavior * @author Hakim BELHAOUARI */ public interface TState { /** * @return Return the name of the state */ String getState(); /** * @return Return an iterator with all allowed functionality */ Iterator<TAllow> getAllow(); }
true
b1a7a971f0333f1bc893a29af5833bdba45b383a
Java
ZiyingShao/cw1
/ImproperHeightException.java
UTF-8
131
2.140625
2
[]
no_license
public class ImproperHeightException extends Exception { public ImproperHeightException(String message) { super(message); } }
true
5ec059c88eb2579de96d4a53a0db5148ee1fb302
Java
AlexandraDI/Connections
/src/java/dao/definitions/UserDAO.java
UTF-8
527
2.21875
2
[]
no_license
package dao.definitions; import java.util.List; import model.User; public interface UserDAO { public User find(String email); public User find(Integer id); public List<User> list(); public void create(User user); public void update(Integer id, User user); public boolean remove(Integer id); public List<User> search(String what); public double[] buildVector(Integer user_pk, List<Integer> all_language_ids, List<Integer> all_skill_ids); }
true
a0ca48bec388dd61469563a813c6c97c3b3cd31e
Java
TangZhiTing666/Javaweb
/Hibernate/hibernateDemo2/src/com/Demo2/test/more2one.java
GB18030
1,941
2.8125
3
[]
no_license
package com.Demo2.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.Demo2.bean.Grade; import com.Demo2.bean2.Student; public class more2one { private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before public void init(){ //ö Configuration config = new Configuration().configure(); //ע ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //Ự sessionFactory = config.buildSessionFactory(serviceRegistry); //Ự session = sessionFactory.openSession(); // transaction = session.beginTransaction(); } @After public void destory(){ transaction.commit(); //ύ session.close(); //رջỰͷſܵݿӳ sessionFactory.close(); //رջỰ } /* * 򣩶һϵ * */ @Test public void save(){ Grade g = new Grade("Java","Javaվ"); Student stu1 = new Student("Russell.H",""); Student stu2 = new Student("ǧÿ","Ů"); stu1.setGrade(g); /*ѧࣩ༶һУ*/ stu2.setGrade(g); session.save(g); session.save(stu1); session.save(stu2); } @Test public void getGradeByStudent(){ Student stu = (Student)session.get(Student.class, 32); System.out.println("ѧ"+stu.getSname()+" Ա"+stu.getSex()); Grade g = stu.getGrade(); //һϵ System.out.println("ڰ༶"+g.getGname()); } }
true
ceab627465aace2119e77c3c6ab807ac7b96475c
Java
Jeko13/Porfolio
/portfolio/src/main/java/fr/cedricmoulard/photostore/model/bean/CartItem.java
UTF-8
714
2.875
3
[]
no_license
package fr.cedricmoulard.photostore.model.bean; /** * @author zkessentials store * * This class provides a representation of a {@code CartItem} * */ public class CartItem { private Product product; private Photo photo; private int amount; public CartItem(Photo photo,Product product) { super(); this.product = product; this.photo = photo; } public Product getProduct() { return product; } public int getAmount() { return amount; } public void add(int amount) { this.amount += amount; } public float getSubTotal() { return product.getPrice() * amount; } public Photo getPhoto() { return photo; } public void setPhoto(Photo photo) { this.photo = photo; } }
true
8f146a33941ae8f75abf2e120d990b5e7b8f8fa4
Java
kia1349/Med-Manager-1
/app/src/main/java/com/nwagu/medmanager/Constants.java
UTF-8
563
1.632813
2
[]
no_license
package com.nwagu.medmanager; interface Constants { String EXTRA_MED_INDEX = "med index"; String EXTRA_MED_NAME = "med name"; String EXTRA_MED_DESC = "med desc"; String EXTRA_MED_FREQ = "med freq"; String EXTRA_MED_START = "med start"; String EXTRA_MED_END = "med end"; String EXTRA_MED_LAST = "med last taken"; String DUE_PILL_NAME = "due pill"; int REQUEST_NEW_MED = 1; int REQUEST_PILL_EDIT = 2; int PILL_DISPLAY_COLOURS = 7; int RC_SIGN_IN = 9; int RESULT_MED_TAKE = 1; int RESULT_MED_DELETE = 2; }
true
2146312c01e63fe93c81607531a18d3939f8d651
Java
arnieel/mango
/src/main/java/com/tgp/view/stage/MainStage.java
UTF-8
531
2.328125
2
[]
no_license
package com.tgp.view.stage; import com.tgp.view.scene.MainScene; import javafx.application.Platform; import javafx.scene.Scene; import javafx.stage.Stage; public class MainStage extends Stage { public MainStage() { Scene mainScene = new MainScene(); setTitle(TITLE); setScene(mainScene); show(); setResizable(false); setOnCloseRequest(e -> { Platform.exit(); System.exit(0); }); } private static final String TITLE = "Time Tracker"; }
true
ed610fe9ce1e5514cee2383e96c989e505117c8b
Java
tmillsclare/zk
/zk/src/org/zkoss/zk/ui/Executions.java
UTF-8
41,430
2.109375
2
[]
no_license
/* Executions.java Purpose: Description: History: Fri Jun 3 17:55:08 2005, Created by tomyeh Copyright (C) 2005 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zk.ui; import java.util.Map; import java.io.Reader; import java.io.Writer; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import org.zkoss.idom.Document; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.metainfo.PageDefinition; import org.zkoss.zk.ui.metainfo.LanguageDefinition; import org.zkoss.zk.xel.Evaluator; import org.zkoss.zk.ui.sys.UiEngine; import org.zkoss.zk.ui.sys.WebAppCtrl; import org.zkoss.zk.ui.sys.DesktopCtrl; import org.zkoss.zk.ui.sys.ExecutionsCtrl; import org.zkoss.zk.ui.sys.ServerPush; /** * Utilities to access {@link Execution}. * * @author tomyeh */ public class Executions { /** Stores the current {@link Execution}. */ protected static final ThreadLocal _exec = new ThreadLocal(); /** Returns the current execution. */ public static final Execution getCurrent() { return (Execution)_exec.get(); } /** Returns the evaluator of the current execution. * It is usually used to parse the expression into {@link org.zkoss.xel.Expression} * or used with {@link org.zkoss.zk.xel.ExValue}. * for performance improvement. * * @param page the page that this evaluator is associated. * If null, the current page and then the first page is assumed. * @param expfcls the implementation of {@link org.zkoss.xel.ExpressionFactory}, * or null to use the default ({@link org.zkoss.zk.ui.util.Configuration#getExpressionFactoryClass}. * @since 3.0.0 */ public static final Evaluator getEvaluator(Page page, Class expfcls) { return getCurrent().getEvaluator(page, expfcls); } /** Returns the evaluator of the current execution. * It is a shortcut of getEvaluator(comp != null ? comp.getPage(): null) * * @param comp the component to retrieve the page for the evaluator * @param expfcls the implementation of {@link org.zkoss.xel.ExpressionFactory}, * or null to use the default ({@link org.zkoss.zk.ui.util.Configuration#getExpressionFactoryClass}. * @since 3.0.0 */ public static final Evaluator getEvaluator(Component comp, Class expfcls) { return getCurrent().getEvaluator(comp, expfcls); } /** Evluates the specified expression by use of the current context * ({@link #getCurrent}). * * <p>The function mapper is retrieved from component's page's function * mapper ({@link Page#getFunctionMapper}). * If null, the current page, if any, is used to retrieve * the mapper. * * <p>For better performance, you can use the instance returned by *{@link #getEvaluator} to parse and cached the parsed expression. * {@link org.zkoss.zk.xel.ExValue} is a utility class to simply * the task. * * @param comp as the self variable (ignored if null) */ public static final Object evaluate(Component comp, String expr, Class expectedType) { return getCurrent().evaluate(comp, expr, expectedType); } /** Evluates the specified expression with the resolver of the current * execution ({@link #getCurrent}). * * <p>The function mapper is retrieved from page's function * mapper ({@link Page#getFunctionMapper}). * If null, the current page, if any, is used to retrieve * the mapper. * * <p>For better performance, you can use the instance returned by *{@link #getEvaluator} to parse and cached the parsed expression. * {@link org.zkoss.zk.xel.ExValue} is a utility class to simply * the task. * * @param page used as the self variable and to retrieve the function * mapper if funmap is not defined. Ignored if null. */ public static final Object evaluate(Page page, String expr, Class expectedType) { return getCurrent().evaluate(page, expr, expectedType); } /** Encodes the specified URL. * * <p>It resolves "*" contained in URI, if any, to the proper Locale, * and the browser code. * Refer to {@link org.zkoss.web.servlet.Servlets#locate(javax.servlet.ServletContext, ServletRequest, String, Locator)} * for details. * * @exception NullPointerException if the current execution is not * available. * @see #encodeURL */ public static final String encodeURL(String uri) { return getCurrent().encodeURL(uri); } /** Encodes the specified URL into an instance of {@link URL}. * It is similar to {@link #encodeURL}, except it returns an instance * of {@link URL}. * * @exception NullPointerException if the current execution is not * available. * @exception MalformedURLException if failed to convert it to * a legal {@link URL} * @since 3.5.0 */ public static final URL encodeToURL(String uri) throws MalformedURLException { final Execution exec = getCurrent(); uri = exec.encodeURL(uri); if (uri.indexOf("://") < 0) { final StringBuffer sb = new StringBuffer(256) .append(exec.getScheme()).append("://") .append(exec.getServerName()); int port = exec.getServerPort(); if (port != 80) sb.append(':').append(port); if (uri.length() > 0 && uri.charAt(0) != '/') sb.append('/'); uri = sb.append(uri).toString(); } return new URL(uri); } /** Creates components from a page file specified by an URI. * Shortcut to {@link Execution#createComponents(String, Component, Map)}. * * @param parent the parent component, or null if you want it to be * a root component. If parent is null, the page is assumed to be * the current page, which is determined by the execution context. * In other words, the new component will be the root component * of the current page if parent is null. * @param arg a map of parameters that is accessible by the arg variable * in EL, or by {@link Execution#getArg}. * Ignored if null. * @return the first component being created. * @see #createComponents(PageDefinition, Component, Map) */ public static final Component createComponents( String uri, Component parent, Map arg) { return getCurrent().createComponents(uri, parent, arg); } /** Creates components based on the specified page definition. * Shortcut to {@link Execution#createComponents(PageDefinition, Component, Map)}. * * @param pagedef the page definition to use. It cannot be null. * @param parent the parent component, or null if you want it to be * a root component. If parent is null, the page is assumed to be * the current page, which is determined by the execution context. * In other words, the new component will be the root component * of the current page if parent is null. * @param arg a map of parameters that is accessible by the arg variable * in EL, or by {@link Execution#getArg}. * Ignored if null. * @return the first component being created. * @see #createComponents(String, Component, Map) */ public static final Component createComponents(PageDefinition pagedef, Component parent, Map arg) { return getCurrent().createComponents(pagedef, parent, arg); } /** Creates components from the raw content specified by a string. * Shortcut to {@link Execution#createComponentsDirectly(String, String, Component, Map)}. * * @param content the raw content of the page. It must be a XML and * compliant to the page format (such as ZUL). * @param extension the default extension if the content doesn't specify * an language. In other words, if * the content doesn't specify an language, {@link LanguageDefinition#getByExtension} * is called. * If extension is null and the content doesn't specify a language, * the language called "xul/html" is assumed. * @param parent the parent component, or null if you want it to be * a root component. If parent is null, the page is assumed to be * the current page, which is determined by the execution context. * In other words, the new component will be the root component * of the current page if parent is null. * @param arg a map of parameters that is accessible by the arg variable * in EL, or by {@link Execution#getArg}. * Ignored if null. * @return the first component being created. * @see #createComponents(PageDefinition, Component, Map) * @see #createComponents(String, Component, Map) * @see #createComponentsDirectly(Document, String, Component, Map) * @see #createComponentsDirectly(Reader, String, Component, Map) */ public static final Component createComponentsDirectly(String content, String extension, Component parent, Map arg) { return getCurrent().createComponentsDirectly(content, extension, parent, arg); } /** Creates components from the raw content specified by a DOM tree. * Shortcut to {@link Execution#createComponentsDirectly(Document, String, Component, Map)}. * * @param content the raw content in DOM. * @param extension the default extension if the content doesn't specify * an language. In other words, if * the content doesn't specify an language, {@link LanguageDefinition#getByExtension} * is called. * If extension is null and the content doesn't specify a language, * the language called "xul/html" is assumed. * @param parent the parent component, or null if you want it to be * a root component. If parent is null, the page is assumed to be * the current page, which is determined by the execution context. * In other words, the new component will be the root component * of the current page if parent is null. * @param arg a map of parameters that is accessible by the arg variable * in EL, or by {@link Execution#getArg}. * Ignored if null. * @return the first component being created. * @see #createComponents(PageDefinition, Component, Map) * @see #createComponents(String, Component, Map) * @see #createComponentsDirectly(String, String, Component, Map) * @see #createComponentsDirectly(Reader, String, Component, Map) */ public static final Component createComponentsDirectly(Document content, String extension, Component parent, Map arg) { return getCurrent().createComponentsDirectly(content, extension, parent, arg); } /** Creates components from the raw content read from the specified reader. * Shortcut to {@link Execution#createComponentsDirectly(Reader, String, Component, Map)}. * * <p>The raw content is loader and parsed to a page defintion by use of * {@link Execution#getPageDefinitionDirectly(Reader, String)}, and then * invokes {@link #createComponents(PageDefinition,Component,Map)} * to create components. * * @param reader the reader to retrieve the raw content. * @param extension the default extension if the content doesn't specify * an language. In other words, if * the content doesn't specify an language, {@link LanguageDefinition#getByExtension} * is called. * If extension is null and the content doesn't specify a language, * the language called "xul/html" is assumed. * @param parent the parent component, or null if you want it to be * a root component. If parent is null, the page is assumed to be * the current page, which is determined by the execution context. * In other words, the new component will be the root component * of the current page if parent is null. * @param arg a map of parameters that is accessible by the arg variable * in EL, or by {@link Execution#getArg}. * Ignored if null. * @return the first component being created. * @see #createComponents(PageDefinition, Component, Map) * @see #createComponents(String, Component, Map) * @see #createComponentsDirectly(Document, String, Component, Map) * @see #createComponentsDirectly(String, String, Component, Map) */ public static Component createComponentsDirectly(Reader reader, String extension, Component parent, Map arg) throws IOException { return getCurrent().createComponentsDirectly(reader, extension, parent, arg); } /** Creates components that don't belong to any page * from the specified page definition. * * <p>Unlike {@link #createComponents(PageDefinition,Component,Map)}, * this method can be inovked without the current execution, such as * a working thread. In this case, the wapp argument must be specified. * * @param wapp the Web application. It is optional and used only if * no current execution (e.g., in a working thread). * The instance of {@link WebApp} can be retrieved by use of {@link org.zkoss.zk.ui.http.WebManager#getWebApp}, * while the instance of {@link org.zkoss.zk.ui.http.WebManager} can be retrieved * by {@link org.zkoss.zk.ui.http.WebManager#getWebManager} * @param pagedef the page definition to use. It cannot be null. * @param arg a map of parameters that is accessible by the arg variable * in EL, or by {@link Execution#getArg}. * Ignored if null. * @return all top-level components being created. * @see #createComponents(WebApp, String, Map) * @since 3.6.2 */ public static Component[] createComponents(WebApp wapp, PageDefinition pagedef, Map arg) { final CCInfo cci = beforeCC(wapp); try { return cci.exec.createComponents(pagedef, arg); } finally { afterCC(cci); } } /** Creates components that don't belong to any page * from a page file specified by an URI. * * <p>It loads the page definition from the specified URI (by * use {@link #getPageDefinition} ), and then * invokes {@link #createComponents(WebApp,PageDefinition,Map)} * to create components. * * <p>Unlike {@link #createComponents(String,Component,Map)}, * this method can be inovked without the current execution, such as * a working thread. In this case, the wapp argument must be specified. * * @param wapp the Web application. It is optional and used only if * no current execution (e.g., in a working thread). * The instance of {@link WebApp} can be retrieved by use of {@link org.zkoss.zk.ui.http.WebManager#getWebApp}, * while the instance of {@link org.zkoss.zk.ui.http.WebManager} can be retrieved * by {@link org.zkoss.zk.ui.http.WebManager#getWebManager} * @param arg a map of parameters that is accessible by the arg variable * in EL, or by {@link Execution#getArg}. * Ignored if null. * @return all top-level components being created. * @see #createComponents(WebApp, PageDefinition, Map) * @see #createComponentsDirectly(WebApp, String, String, Map) * @see #createComponentsDirectly(WebApp, Document, String, Map) * @see #createComponentsDirectly(WebApp, Reader, String, Map) * @since 3.6.2 */ public static Component[] createComponents(WebApp wapp, String uri, Map arg) { final CCInfo cci = beforeCC(wapp); try { return cci.exec.createComponents(uri, arg); } finally { afterCC(cci); } } /** Creates components that don't belong to any page * from the raw content specified by a string. * * <p>The raw content is parsed to a page defintion by use of * {@link #getPageDefinitionDirectly(WebApp,String,String)}, and then * invokes {@link #createComponents(WebApp,PageDefinition,Map)} * to create components. * * <p>Unlike {@link #createComponentsDirectly(String,String,Component,Map)}, * this method can be inovked without the current execution, such as * a working thread. In this case, the wapp argument must be specified. * * @param wapp the Web application. It is optional and used only if * no current execution (e.g., in a working thread). * The instance of {@link WebApp} can be retrieved by use of {@link org.zkoss.zk.ui.http.WebManager#getWebApp}, * while the instance of {@link org.zkoss.zk.ui.http.WebManager} can be retrieved * by {@link org.zkoss.zk.ui.http.WebManager#getWebManager} * @param content the raw content of the page. It must be in ZUML. * @param extension the default extension if the content doesn't specify * an language. In other words, if * the content doesn't specify an language, {@link LanguageDefinition#getByExtension} * is called. * If extension is null and the content doesn't specify a language, * the language called "xul/html" is assumed. * @param arg a map of parameters that is accessible by the arg variable * in EL, or by {@link Execution#getArg}. * Ignored if null. * @return all top-level components being created. * @see #createComponents(WebApp, PageDefinition, Map) * @see #createComponents(WebApp, String, Map) * @see #createComponentsDirectly(WebApp, Document, String, Map) * @see #createComponentsDirectly(WebApp, Reader, String, Map) * @since 3.6.2 */ public static Component[] createComponentsDirectly(WebApp wapp, String content, String extension, Map arg) { final CCInfo cci = beforeCC(wapp); try { return cci.exec.createComponentsDirectly(content, extension, arg); } finally { afterCC(cci); } } /** Creates components that don't belong to any page * from the raw content specified by a DOM tree. * * <p>The raw content is parsed to a page defintion by use of * {@link #getPageDefinitionDirectly(WebApp,Document, String)}, and then * invokes {@link #createComponents(WebApp,PageDefinition,Map)} * to create components. * * <p>Unlike {@link #createComponentsDirectly(Document,String,Component,Map)}, * this method can be inovked without the current execution, such as * a working thread. In this case, the wapp argument must be specified. * * @param wapp the Web application. It is optional and used only if * no current execution (e.g., in a working thread). * The instance of {@link WebApp} can be retrieved by use of {@link org.zkoss.zk.ui.http.WebManager#getWebApp}, * while the instance of {@link org.zkoss.zk.ui.http.WebManager} can be retrieved * by {@link org.zkoss.zk.ui.http.WebManager#getWebManager} * @param content the raw content in DOM. * @param extension the default extension if the content doesn't specify * an language. In other words, if * the content doesn't specify an language, {@link LanguageDefinition#getByExtension} * is called. * If extension is null and the content doesn't specify a language, * the language called "xul/html" is assumed. * @param arg a map of parameters that is accessible by the arg variable * in EL, or by {@link Execution#getArg}. * Ignored if null. * @return all top-level components being created. * @see #createComponents(WebApp, PageDefinition, Map) * @see #createComponents(WebApp, String, Map) * @see #createComponentsDirectly(WebApp, Document, String, Map) * @see #createComponentsDirectly(WebApp, Reader, String, Map) * @since 3.6.2 */ public static Component[] createComponentsDirectly(WebApp wapp, Document content, String extension, Map arg) { final CCInfo cci = beforeCC(wapp); try { return cci.exec.createComponentsDirectly(content, extension, arg); } finally { afterCC(cci); } } /** Creates components that don't belong to any page * from the raw content read from the specified reader. * * <p>Unl * * <p>The raw content is loaded and parsed to a page defintion by use of * {@link #getPageDefinitionDirectly(WebApp,Reader,String)}, and then * invokes {@link #createComponents(WebApp,PageDefinition,Map)} * to create components. * * <p>Unlike {@link #createComponentsDirectly(Reader,String,Component,Map)}, * this method can be inovked without the current execution, such as * a working thread. In this case, the wapp argument must be specified. * * @param wapp the Web application. It is optional and used only if * no current execution (e.g., in a working thread). * The instance of {@link WebApp} can be retrieved by use of {@link org.zkoss.zk.ui.http.WebManager#getWebApp}, * while the instance of {@link org.zkoss.zk.ui.http.WebManager} can be retrieved * by {@link org.zkoss.zk.ui.http.WebManager#getWebManager} * @param reader the reader to retrieve the raw content in ZUML. * @param extension the default extension if the content doesn't specify * an language. In other words, if * the content doesn't specify an language, {@link LanguageDefinition#getByExtension} * is called. * If extension is null and the content doesn't specify a language, * the language called "xul/html" is assumed. * @param arg a map of parameters that is accessible by the arg variable * in EL, or by {@link Execution#getArg}. * Ignored if null. * @return all top-level components being created. * @see #createComponents(WebApp, PageDefinition, Map) * @see #createComponents(WebApp, String, Map) * @see #createComponentsDirectly(WebApp, Document, String, Map) * @see #createComponentsDirectly(WebApp, String, String, Map) * @since 3.6.2 */ public static Component[] createComponentsDirectly(WebApp wapp, Reader reader, String extension, Map arg) throws IOException { final CCInfo cci = beforeCC(wapp); try { return cci.exec.createComponentsDirectly(reader, extension, arg); } finally { afterCC(cci); } } /** Returns the page definition from the page file specified by an URI. * * <p>Like {@link #createComponents(WebApp,PageDefinition,Map)}, * this method can be inovked without the current execution, such as * a working thread. In this case, the wapp argument must be specified. * * @param wapp the Web application. It is optional and used only if * no current execution (e.g., in a working thread). * The instance of {@link WebApp} can be retrieved by use of {@link org.zkoss.zk.ui.http.WebManager#getWebApp}, * while the instance of {@link org.zkoss.zk.ui.http.WebManager} can be retrieved * by {@link org.zkoss.zk.ui.http.WebManager#getWebManager} * @param uri the URI of the page file. * * @see #getPageDefinitionDirectly(WebApp, String, String) * @see #getPageDefinitionDirectly(WebApp, Document, String) * @see #getPageDefinitionDirectly(WebApp, Reader, String) * @since 3.6.2 */ public static PageDefinition getPageDefinition(WebApp wapp, String uri) { final CCInfo cci = beforeCC(wapp); try { return cci.exec.getPageDefinition(uri); } finally { afterCC(cci); } } /** Converts the specified page content to a page definition. * * <p>Like {@link #createComponents(WebApp,PageDefinition,Map)}, * this method can be inovked without the current execution, such as * a working thread. In this case, the wapp argument must be specified. * * @param wapp the Web application. It is optional and used only if * no current execution (e.g., in a working thread). * The instance of {@link WebApp} can be retrieved by use of {@link org.zkoss.zk.ui.http.WebManager#getWebApp}, * while the instance of {@link org.zkoss.zk.ui.http.WebManager} can be retrieved * by {@link org.zkoss.zk.ui.http.WebManager#getWebManager} * @param content the raw content of the page. It must be in ZUML. * @param extension the default extension if the content doesn't specify * an language. In other words, if * the content doesn't specify an language, {@link LanguageDefinition#getByExtension} * is called. * If extension is null and the content doesn't specify a language, * the language called "xul/html" is assumed. * @see #getPageDefinitionDirectly(WebApp, Document, String) * @see #getPageDefinitionDirectly(WebApp, Reader, String) * @see #getPageDefinition * @since 3.6.2 */ public PageDefinition getPageDefinitionDirectly(WebApp wapp, String content, String extension) { final CCInfo cci = beforeCC(wapp); try { return cci.exec.getPageDefinitionDirectly(content, extension); } finally { afterCC(cci); } } /** Converts the specified page content, in DOM, to a page definition. * * <p>Like {@link #createComponentsDirectly(WebApp,Document,String,Map)}, * this method can be inovked without the current execution, such as * a working thread. In this case, the wapp argument must be specified. * * @param wapp the Web application. It is optional and used only if * no current execution (e.g., in a working thread). * The instance of {@link WebApp} can be retrieved by use of {@link org.zkoss.zk.ui.http.WebManager#getWebApp}, * while the instance of {@link org.zkoss.zk.ui.http.WebManager} can be retrieved * by {@link org.zkoss.zk.ui.http.WebManager#getWebManager} * @param content the raw content of the page in DOM. * @param extension the default extension if the content doesn't specify * an language. In other words, if * the content doesn't specify an language, {@link LanguageDefinition#getByExtension} * is called. * If extension is null and the content doesn't specify a language, * the language called "xul/html" is assumed. * @see #getPageDefinitionDirectly(WebApp, String, String) * @see #getPageDefinitionDirectly(WebApp, Reader, String) * @see #getPageDefinition * @since 3.6.2 */ public PageDefinition getPageDefinitionDirectly(WebApp wapp, Document content, String extension) { final CCInfo cci = beforeCC(wapp); try { return cci.exec.getPageDefinitionDirectly(content, extension); } finally { afterCC(cci); } } /** Reads the raw content from a reader and converts it into * a page definition. * * <p>Like {@link #createComponentsDirectly(WebApp,Reader,String,Map)}, * this method can be inovked without the current execution, such as * a working thread. In this case, the wapp argument must be specified. * * @param wapp the Web application. It is optional and used only if * no current execution (e.g., in a working thread). * The instance of {@link WebApp} can be retrieved by use of {@link org.zkoss.zk.ui.http.WebManager#getWebApp}, * while the instance of {@link org.zkoss.zk.ui.http.WebManager} can be retrieved * by {@link org.zkoss.zk.ui.http.WebManager#getWebManager} * @param reader used to input the raw content of the page. It must be in ZUML. * @param extension the default extension if the content doesn't specify * an language. In other words, if * the content doesn't specify an language, {@link LanguageDefinition#getByExtension} * is called. * If extension is null and the content doesn't specify a language, * the language called "xul/html" is assumed. * @see #getPageDefinitionDirectly(WebApp, String, String) * @see #getPageDefinitionDirectly(WebApp, Document, String) * @see #getPageDefinition * @since 3.6.2 */ public PageDefinition getPageDefinitionDirectly(WebApp wapp, Reader reader, String extension) throws IOException { final CCInfo cci = beforeCC(wapp); try { return cci.exec.getPageDefinitionDirectly(reader, extension); } finally { afterCC(cci); } } private static final CCInfo beforeCC(WebApp wapp) { Execution exec = Executions.getCurrent(); if (exec != null) return new CCInfo(exec, false); ((WebAppCtrl)wapp).getUiEngine() .activate(exec = CCExecution.newInstance(wapp)); return new CCInfo(exec, true); } private static final void afterCC(CCInfo cci) { if (cci.created) { try { ((WebAppCtrl)cci.exec.getDesktop().getWebApp()) .getUiEngine().deactivate(cci.exec); } catch (Throwable ex) { } } } private static class CCInfo { private final Execution exec; private final boolean created; private CCInfo(Execution exec, boolean created) { this.exec = exec; this.created = created; } } /** Sends a temporary redirect response to the client using the specified * redirect location URL by use of the current execution, * {@link #getCurrent}. * * <p>After calling this method, the caller shall end the processing * immediately (by returning). All pending requests and events will * be dropped. * * @param uri the URI to redirect to, or null to reload the same page * @see Execution#sendRedirect */ public static void sendRedirect(String uri) { getCurrent().sendRedirect(uri); } /** A shortcut of Executions.getCurrent().include(page). * * @see Execution#include(Writer,String,Map,int) * @see Execution#include(String) */ public static void include(String page) throws IOException { getCurrent().include(page); } /** A shortcut of Executions.getCurrent().forward(page). * * @see Execution#forward(Writer,String,Map,int) * @see Execution#forward(String) */ public static void forward(String page) throws IOException { getCurrent().forward(page); } //-- wait/notify --// /** Suspends the current processing of an event and wait until the * other thread invokes {@link #notify(Object)}, {@link #notifyAll(Object)}, * {@link #notify(Desktop, Object)} or {@link #notifyAll(Desktop, Object)} * for the specified object. * * <p>It can only be called when the current thread is processing an event. * And, when called, the current processing is suspended and ZK continues * to process the next event and finally render the result. * * <p>It is typical use to implement a modal dialog where it won't return * until the modal dialog ends. * * @param mutex any non-null object to identify what to notify. * It must be same object passed to {@link #notify(Desktop, Object)}. * If there is racing issue, you have to enclose it with * <code>synchronized</code> (though it is optional). * @exception UiException if it is called not during event processing. * @exception SuspendNotAllowedException if there are too many suspended * exceptions. * Deployers can control the maximal allowed number of suspended exceptions * by specifying <code>max-suspended-thread</code> in <code>zk.xml</code>, * or invoking {@link org.zkoss.zk.ui.util.Configuration#setMaxSuspendedThreads}. */ public static final void wait(Object mutex) throws InterruptedException, SuspendNotAllowedException { getUiEngine().wait(mutex); } /** Wakes up a single event processing thread that is waiting on the * specified object. * * <p>Unlike {@link #notify(Desktop, Object)}, this method can be invoked only * in the event listener that processing the same desktop. * In addition, this method can be called under the event listener. * * <p>Use {@link #notify(Desktop, Object)} if you want to notify in other * thread, such as a working thread. * * @param mutex any non-null object to identify what to notify. * It must be same object passed to {@link #wait}. * If there is racing issue, you have to enclose it with * <code>synchronized</code> (though it is optional). * @see #notify(Desktop, Object) * @see #notifyAll(Object) * @exception UiException if it is called not during event processing. */ public static final void notify(Object mutex) { getUiEngine().notify(mutex); } /** Wakes up all event processing thread that are waiting on the * specified object. * * <p>Unlike {@link #notify(Desktop, Object)}, this method can be invoked only * in the event listener that processing the same desktop. * In addition, this method can be called under the event listener. * * <p>Use {@link #notifyAll(Desktop, Object)} if you want to notify in other * thread, such as a working thread. * * @param mutex any non-null object to identify what to notify. * It must be same object passed to {@link #wait}. * If there is racing issue, you have to enclose it with * <code>synchronized</code> (though it is optional). * @see #notify(Desktop, Object) * @see #notifyAll(Object) * @exception UiException if it is called not during event processing. */ public static final void notifyAll(Object mutex) { getUiEngine().notifyAll(mutex); } /** Wakes up a single event processing thread for the specified desktop * that is waiting on the specified object. * * <p>Unlike {@link #notify(Object)}, this method can be called any time. * It is designed to let working threads resume an event processing * thread. * * <p>Notice: if this method is NOT called in an event processing thread, * the resumed thread won't execute until the next request is received. * To enforce it happen, you might use the timer component (found in ZUL). * * <p>Notice: to resolve racing issue, you usually need to follow * this pattern. * <pre><code> //Event Handling Thread synchronized (mutex) { final WorkingThread worker = new WorkingThread(desktop); synchronized (mutex) { worker.start(); Executions.wait(mutex); } .... } //Working Thread public void run() { .... synchronized (mutex) { Executions.notify(desktop, mutex); } } </code></pre> * * @param desktop the desktop which the suspended thread is processing. * It must be the same desktop of the suspended thread. * @param mutex any non-null object to identify what to notify. * It must be same object passed to {@link #wait}. * If there is racing issue, you have to enclose it with * <code>synchronized</code> (though it is optional). * @see #notify(Object) * @see #notifyAll(Desktop, Object) */ public static final void notify(Desktop desktop, Object mutex) { getUiEngine(desktop).notify(desktop, mutex); } /** Wakes up all event processing theads for the specified desktop * that are waiting on the specified object. * * <p>Unlike {@link #notifyAll(Object)}, this method can be called any time. * It is designed to let working threads resume an event processing * thread. * * <p>Notice: if this method is NOT called in an event processing thread, * the resumed thread won't execute until the next request is received. * To enforce it happen, you might use the timer component (found in ZUL). * * <p>Notice: to resolve racing issue, you usually need to follow * this pattern. * <pre><code> //Event Handling Thread synchronized (mutex) { final WorkingThread worker = new WorkingThread(desktop); synchronized (mutex) { worker.start(); Executions.wait(mutex); } .... } //Working Thread public void run() { .... synchronized (mutex) { Executions.notifyAll(desktop, mutex); } } </code></pre> * * @param desktop the desktop which the suspended thread is processing. * It must be the same desktop of the suspended thread. * @param mutex any non-null object to identify what to notify. * It must be same object passed to {@link #wait}. * If there is racing issue, you have to enclose it with * <code>synchronized</code> (though it is optional). * @see #notify(Object) * @see #notifyAll(Desktop, Object) */ public static final void notifyAll(Desktop desktop, Object mutex) { getUiEngine(desktop).notifyAll(desktop, mutex); } /** Schedules a task to run under the server push of the given desktop asynchronously. * The caller can be any thread, not * limited to the event listener of the given desktop. * * <p>The task is executed when the server push of the given desktop * is granted. The task is executed asynchronously. That is, this method * return without waiting for the task to be executed. * * <p>The task is executed in the thread serving the server-push request, * so no additional thread will be created. It is safe to use in a clustering * environment. * * <p>The task is represented by an event listener. When the server push * is ready to serve the given task, {@link EventListener#onEvent} is called * with the given event. * * <p>Like {@link #activate}, this method can be called anywhere, not limited * to the event listener of the given desktop. It can be called even * if there is no current execution. * * <p>Alternative to {@link #schedule}, you could use {@link #activate}/{@link #deactivate} * if you prefer something to be done synchrnously. * * <p>The server-push is disabled by default. To use it, you have to enable * it first with {@link Desktop#enableServerPush} for the given desktop. * Once enabled, you can use as many as sevrer-push threads you like * (for the desktop with the server-push feature enabled). * * @param task the task to execute * @param event the event to be passed to the task (i.e., the event listener). * It could null or any instance as long as the task recognizes it. * @exception IllegalStateException if the server push is not enabled. * @exception DesktopUnavailableException if the desktop is removed * (when activating). * @since 5.0.6 */ public static void schedule(Desktop desktop, EventListener task, Event event) { ((DesktopCtrl)desktop).scheduleServerPush(task, event); } /** Activates a thread to allow it access the given desktop synchronously. * It causes the current thread to wait until the desktop is available * to access, the desktop no longer exists, * or some other thread interrupts this thread. * * <p>Alternative to {@link #activate}/{@link #deactivate}, you could use * {@link #schedule} to execute a task under server push. {@link #schedule} is * asynchronous, while {@link #activate}/{@link #deactivate} is synchronous * * <p>Like {@link #schedule}, this method can be called anywhere, not limited * to the event listener of the given desktop. It can be called even * if there is no current execution. * * <p>The server-push is disabled by default. To use it, you have to enable * it first with {@link Desktop#enableServerPush} for the given desktop. * Once enabled, you can use as many as sevrer-push threads you like * (for the desktop with the server-push feature enabled). * * <p>Before a thread, not running in the event listener of the given desktop, * can access the desktop, you have to activate it first by {@link #activate}. * Once this method returns, the thread is activated and it, like * an event listener of the given desktop, can manipulate the desktop directly. * * <p>A typical use pattern: * * <pre><code>class MyWorkingThread extends Thread { * public void run() { * while (anything_to_publish) { * //prepare something to publish * //you can create new components and manipulate them before * //activation, as long as they are not attached to the desktop * * Executions.activate(desktop); * try { * try { * //activated * //manipulate the components that are attached the desktop * } finally { * Executions.deactivate(desktop) * } * } catch (DesktopUnavailableException ex) { * //clean up (since desktop is dead) * } * } * } *}</code></pre> * * <p>Note: the access of components is sequentialized. That is, * at most one thread is activated. All others, including * the event listeners, have to wait util it is deactivated * (i.e., until {@link #deactivate} is called). * Thus, it is better to minimize the time remaining activated. * A typical practice is to create new components and manipulate them * before activated. Then, you have to only attach them after activated. * * <pre><code> Tree tree = new Tree(); * new Treechildren().setParent(tree); //initialize the tree * Exections.activate(desktop); * try { * tree.setPage(page); //assume page is a page of desktop *</code></pre> * * <p>Note: you don't need to invoke this method in the event listener * since it is already activated when an event listen starts execution. * * @exception InterruptedException if it is interrupted by other thread * @exception IllegalStateException if the server push is not enabled. * @exception DesktopUnavailableException if the desktop is removed * (when activating). * @since 3.0.0 */ public static final void activate(Desktop desktop) throws InterruptedException, DesktopUnavailableException { activate(desktop, 0); } /** Activates a thread to allow it access the given desktop synchronously, * or until a certain amount of time has elapsed. * It causes the current thread to wait until the desktop is available * to access, the desktop no longer exists, * some other thread interrupts this thread, * or a certain amount of real time has elapsed. * * @param timeout the maximum time to wait in milliseconds. * Ingored (i.e., never timeout) if non-positive. * @return whether it is activated or it is timeout. * The only reason it returns false is timeout. * @exception InterruptedException if it is interrupted by other thread * @exception DesktopUnavailableException if the desktop is removed * (when activating). * @exception IllegalStateException if the server push is not * enabled for this desktop yet ({@link Desktop#enableServerPush}). * @since 3.0.0 * @see #activate(Desktop) * @see #deactivate */ public static final boolean activate(Desktop desktop, long timeout) throws InterruptedException, DesktopUnavailableException { return ((DesktopCtrl)desktop).activateServerPush(timeout); } /** Deactivates a thread that has invoked {@link #activate} successfully. * @since 3.0.0 * @see #activate(Desktop) * @see #activate(Desktop, long) */ public static final void deactivate(Desktop desktop) { ((DesktopCtrl)desktop).deactivateServerPush(); } private static final UiEngine getUiEngine(Desktop desktop) { if (desktop == null) throw new IllegalArgumentException("desktop cannot be null"); return ((WebAppCtrl)desktop.getWebApp()).getUiEngine(); } private static final UiEngine getUiEngine() { final Execution exec = getCurrent(); if (exec == null) throw new IllegalStateException("This method can be called only under an event listener"); return ((WebAppCtrl)exec.getDesktop().getWebApp()).getUiEngine(); } }
true
89af903a41fecc96bd430741739a7c95fa2bdcee
Java
uk-gov-dft/bluebadge-payment-service
/src/main/java/uk/gov/dft/bluebadge/service/payment/service/GovPayProfile.java
UTF-8
363
1.578125
2
[ "MIT" ]
permissive
package uk.gov.dft.bluebadge.service.payment.service; import javax.validation.constraints.NotBlank; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; @Builder @Getter @NoArgsConstructor @AllArgsConstructor @ToString class GovPayProfile { @NotBlank private String apiKey; }
true
56aaee3f5a9947c331289c855f1ab19ea8bcb0b6
Java
bronwen-cassidy/talent-evolution
/talent-studio-views/src/test/java/com/zynap/talentstudio/web/security/area/TestAreaValidator.java
UTF-8
1,061
1.953125
2
[]
no_license
package com.zynap.talentstudio.web.security.area; /** * User: amark * Date: 20-Mar-2005 * Time: 11:38:32 */ import com.zynap.talentstudio.security.areas.Area; import com.zynap.talentstudio.security.areas.AreaElement; import junit.framework.TestCase; import org.springframework.validation.BindException; import java.util.HashSet; public class TestAreaValidator extends TestCase { protected void setUp() throws Exception { areaValidator = new AreaValidator(); } public void testSupports() throws Exception { assertTrue(areaValidator.supports(AreaWrapperBean.class)); } public void testValidateCoreValues() throws Exception { AreaWrapperBean areaWrapperBean = new AreaWrapperBean(new Area(), new HashSet<AreaElement>()); final BindException errors = new BindException(areaWrapperBean, "command"); areaValidator.validateCoreValues(areaWrapperBean, errors); assertTrue(errors.hasErrors()); assertTrue(errors.hasFieldErrors("label")); } AreaValidator areaValidator; }
true
97a9d1db46bc8ffb8e5c106b0a0f7ca6a45285a3
Java
akaravi/Ntk.Android.CustomerClub
/app/src/main/java/ntk/android/customerclub/activity/Class1.java
UTF-8
3,712
2.03125
2
[]
no_license
package ntk.android.customerclub.activity; import android.os.Bundle; import android.widget.AutoCompleteTextView; import android.widget.TextView; import androidx.annotation.Nullable; import com.google.android.material.textfield.TextInputEditText; import es.dmoral.toasty.Toasty; import io.reactivex.annotations.NonNull; import ntk.android.base.activity.BaseActivity; import ntk.android.base.config.NtkObserver; import ntk.android.base.config.ServiceExecute; import ntk.android.base.entitymodel.base.ErrorException; import ntk.android.base.entitymodel.base.FilterModel; import ntk.android.customerclub.R; import ntk.android.customerclub.adapter.AccountSelectAdapter; import ntk.android.customerclub.server.model.PayModel; import ntk.android.customerclub.server.service.PayService; public class Class1 extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.class1); ((TextView) findViewById(R.id.txtToolbar)).setText(getString(R.string.mainCard1)); findViewById(R.id.btn_cancel).setOnClickListener(view -> finish()); findViewById(R.id.back_button).setOnClickListener(view -> finish()); getAccounts(); findViewById(R.id.btnOk).setOnClickListener(view -> checkData()); } private void checkData() { AutoCompleteTextView accountId = findViewById(R.id.etAccountId); TextInputEditText amount = findViewById(R.id.etAmount); if (accountId.getText().toString().equalsIgnoreCase("")) Toasty.error(this, "لطفا حساب سپرده ی خود را انتخاب کنید").show(); else if (amount.getText().toString().equalsIgnoreCase("")) Toasty.error(this, "مبلغ واریزی را مشخص نمایید").show(); else { long price = 0; try { price = Long.parseLong(amount.getText().toString()); } catch (Exception e) { Toasty.error(this, "مبلغ واریزی نا معتبر است").show(); return; } if (price < 100) { Toasty.error(this, "حداقل مبلغ واریزی 100 ریال می باشد").show(); } else callApi(); } } private void callApi() { } private void getAccounts() { switcher.showProgressView(); ServiceExecute.execute(new PayService(this).getAll(new FilterModel())).subscribe(new NtkObserver<ErrorException<PayModel>>() { @Override public void onNext(@NonNull ErrorException<PayModel> accountModelErrorException) { switcher.showContentView(); AutoCompleteTextView paymentType = (AutoCompleteTextView) findViewById(R.id.etAccountId); TextInputEditText Name = findViewById(R.id.etName); paymentType.setAdapter(new AccountSelectAdapter(Class1.this, accountModelErrorException.ListItems)); paymentType.setOnItemClickListener((adapterView, view12, i, l) -> { if (i >= 0) { paymentType.setText(((PayModel) adapterView.getItemAtPosition(i)).AccountId); Name.setText(((PayModel) adapterView.getItemAtPosition(i)).Name); } else { paymentType.setText(""); Name.setText(""); } }); } @Override public void onError(@NonNull Throwable e) { switcher.showErrorView(e.getMessage(), Class1.this::getAccounts); } }); } }
true
65de535338ec87c35259c736b3fa882285e661e0
Java
Dinox869/betika_ui
/app/src/main/java/com/example/betika_ui/adapter/Bets.java
UTF-8
1,864
2.4375
2
[]
no_license
package com.example.betika_ui.adapter; public class Bets { private String one,two,title,title2,title3,button1,button2,button3,button4; public String getButton1() { return button1; } public void setButton1(String button1) { this.button1 = button1; } public String getOne() { return one; } public void setOne(String one) { this.one = one; } public String getTwo() { return two; } public void setTwo(String two) { this.two = two; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitle2() { return title2; } public void setTitle2(String title2) { this.title2 = title2; } public String getTitle3() { return title3; } public void setTitle3(String title3) { this.title3 = title3; } public String getButton2() { return button2; } public void setButton2(String button2) { this.button2 = button2; } public String getButton3() { return button3; } public void setButton3(String button3) { this.button3 = button3; } public String getButton4() { return button4; } public void setButton4(String button4) { this.button4 = button4; } public Bets(String button1, String one, String two, String title, String title2, String title3, String button2, String button3, String button4) { this.button1 = button1; this.button2 = button2; this.button3 = button3; this.button4 = button4; this.one = one; this.two = two; this.title = title; this.title2 = title2; this.title3 = title3; } }
true
561ebf2ea9ae61700ff8996ce923f3b9cce0f74c
Java
ehabibov/jagger
/webclient/src/main/java/com/griddynamics/jagger/webclient/client/trends/TrendsPlace.java
UTF-8
3,340
2.296875
2
[ "Apache-2.0" ]
permissive
package com.griddynamics.jagger.webclient.client.trends; import com.griddynamics.jagger.webclient.client.mvp.AbstractPlaceHistoryMapper; import com.griddynamics.jagger.webclient.client.mvp.PlaceWithParameters; import java.util.*; /** * @author "Artem Kirillov" (akirillov@griddynamics.com) * @since 6/20/12 */ public class TrendsPlace extends PlaceWithParameters { private static final String FRAGMENT = "fragment"; private String token; private String url; private List<LinkFragment> linkFragments = Collections.EMPTY_LIST; public TrendsPlace(String token){ this.token = token; } public Set<String> getSessionTrends() { if (linkFragments.size() == 1) return linkFragments.iterator().next().getSessionTrends(); return Collections.EMPTY_SET; } public Set<String> getSelectedSessionIds() { // get all sessionIds Set<String> sessionIds = new HashSet<String>(); for (LinkFragment fragment : linkFragments) { sessionIds.addAll(fragment.getSelectedSessionIds()); } return sessionIds; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public void setLinkFragments(List<LinkFragment> linkFragments) { this.linkFragments = linkFragments; } public List<LinkFragment> getLinkFragments() { return linkFragments; } @Override public Map<String, Set<String>> getParameters() { Map<String, Set<String>> parameters = new LinkedHashMap<String, Set<String>>(); if (linkFragments.isEmpty()) { return Collections.EMPTY_MAP; } else if (linkFragments.size() == 1) { return linkFragments.iterator().next().getParameters(); } int index = 1; for (LinkFragment linkFragment : linkFragments) { Set<String> set = new HashSet<String>(1); set.add('(' + linkFragment.getParametersAsString() + ')'); parameters.put(FRAGMENT + index++, set); } return parameters; } @Override public void setParameters(Map<String, Set<String>> parameters) { if (parameters != null && !parameters.isEmpty()) { if (parameters.keySet().iterator().next().contains(FRAGMENT)) { linkFragments = new ArrayList<LinkFragment>(parameters.size()); for (Map.Entry<String, Set<String>> entry : parameters.entrySet()) { LinkFragment linkFragment = new LinkFragment(); String value = entry.getValue().iterator().next(); value = value.substring(1, value.length() - 1); Map<String, Set<String>> params = AbstractPlaceHistoryMapper.getParameters(value); linkFragment.setParameters(params); linkFragments.add(linkFragment); } } else { linkFragments = new ArrayList<LinkFragment>(1); LinkFragment linkFragment = new LinkFragment(); linkFragment.setParameters(parameters); linkFragments.add(linkFragment); } } } public void setUrl(String url) { this.url = url; } public String getUrl() { return url; } }
true
0fa3e49b7ece979780fa557c9427772c26df25a5
Java
timjansen/actorsguild
/src/org/actorsguildframework/internal/Controller.java
UTF-8
3,300
2.5625
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2008 Tim Jansen * * 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 org.actorsguildframework.internal; import java.util.concurrent.locks.ReentrantLock; import org.actorsguildframework.Agent; /** * Controller interface. This is the central interface for the library code. */ public interface Controller { /** * Returns the next Actor to process from the queue and puts it at the end of the queue. * Thus the thread that takes it does not own it and it stays in the queue until the * thread actually empties the queue or locks the actor. * You must lock actorLock before calling this! * @return the actor. Null if the actor queue is empty. * @throws InterruptedException if the thread is interrupted */ public ActorState getNextFromQueueUnsynchronized() throws InterruptedException; /** * Makes sure that the given actor is either in the queue or not, depending on the second * argument. * You must lock actorLock before calling this! * @param actorState the actor to check and possibly to add/remove * @param oldNumberOfOpenParallelTasks the number of open tasks that has been registered before for the Actor * @param newNumberOfOpenParallelTasks the number of tasks needed for the Actor */ public void updateActorStateQueueUnsynchronized(ActorState actorState, int oldNumberOfOpenParallelTasks, int newNumberOfOpenParallelTasks); /** * Changes the state of a thread from the old to the given new state. * @param oldState the thread's old state * @param newState the thread's new state */ public void changeWorkerThreadState(WorkerState oldState, WorkerState newState); /** * Removes the state of a thread from the statistics. * @param oldState the thread's old state */ public void removeWorkerThreadState(WorkerState oldState); /** * Returns the agent of the controller. * @return the agent */ public Agent getAgent(); /** * Returns a KeepRunningInterface for a worker that will tell the worker when to stop. * @return the interface */ public KeepRunningInterface createKeepRunningInterface(); /** * Returns true if action like message will be logged. * @return true for logging, false otherwise */ public boolean isLoggingActions(); /** * Returns the actor lock for accessing an ActorState of this Controller or and the * mActorsWithWork list. * @return the actor lock */ public ReentrantLock getActorLock(); /** * Tries to shut down the controller with all its threads as soon as possible. Messages * that have not been processed yet may not be processed. There is no guarantee * that this operation succeeds. */ public void shutdown(); }
true
d2edcda2cbc5dc5c74005bb1694f4de45caa9292
Java
chaluja7/fixitapp
/src/main/java/cz/cvut/jee/service/InvalidIncidentReferenceService.java
UTF-8
1,095
2.21875
2
[]
no_license
package cz.cvut.jee.service; import cz.cvut.jee.dao.wrappers.InvalidIncidentStatisticItem; import cz.cvut.jee.entity.InvalidIncidentReference; import javax.ejb.Local; import java.util.List; /** * Service for Invalid incident reference. * * @author jakubchalupa * @since 29.01.14 */ @Local public interface InvalidIncidentReferenceService { /** * @param invalidIncidentReference invalidIncidentReference to persist */ public void createInvalidIncidentReference(InvalidIncidentReference invalidIncidentReference); /** * @param id id of invalidIncidentReference to delete */ public void deleteInvalidIncidentReference(long id); /** * @return all records */ public List<InvalidIncidentReference> findAll(); /** * @param incidentId id of incident * @return InvalidIncidentReference for given incidentId or null */ public InvalidIncidentReference findByIncidentId(long incidentId); /** * @return statistics of invalid incidents */ public List<InvalidIncidentStatisticItem> getStatistics(); }
true
138a1b7b997e6901982775eb2865cffcec8cb57c
Java
xeon-ye/spring-boot
/mybatis/src/main/java/com/example/mybatis/MyApplicationRunner.java
UTF-8
1,149
2.109375
2
[]
no_license
package com.example.mybatis; import org.apache.ibatis.io.Resources; import org.apache.ibatis.jdbc.ScriptRunner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.stereotype.Component; import javax.sql.DataSource; import java.io.File; /** * @author zhengsl26931 */ @Component public class MyApplicationRunner implements ApplicationRunner { @Autowired private DataSource dataSource; @Override public void run(ApplicationArguments args) throws Exception { ScriptRunner scriptRunner = new ScriptRunner(dataSource.getConnection()); scriptRunner.setStopOnError(true); String path = "mysql"; Resource[] resources = new PathMatchingResourcePatternResolver() .getResources("classpath:" + path + "/*.sql"); scriptRunner.runScript(Resources.getResourceAsReader(path + "/" + resources[0].getFilename())); } }
true
525e76f4f711d0b9f05d76aa46cafaf5ec3c1f29
Java
alancnet/artifactory
/web/application/src/main/java/org/artifactory/webapp/wicket/application/ArtifactoryWebSession.java
UTF-8
10,706
1.539063
2
[ "Apache-2.0" ]
permissive
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Artifactory. If not, see <http://www.gnu.org/licenses/>. */ package org.artifactory.webapp.wicket.application; import org.apache.commons.lang.StringUtils; import org.apache.wicket.Session; import org.apache.wicket.authroles.authentication.AuthenticatedWebSession; import org.apache.wicket.authroles.authorization.strategies.role.Roles; import org.apache.wicket.proxy.IProxyTargetLocator; import org.apache.wicket.proxy.LazyInitProxyFactory; import org.apache.wicket.request.Request; import org.artifactory.UiAuthenticationDetails; import org.artifactory.api.context.ArtifactoryContext; import org.artifactory.api.context.ContextHelper; import org.artifactory.api.search.SavedSearchResults; import org.artifactory.api.security.AuthorizationService; import org.artifactory.api.security.SecurityService; import org.artifactory.common.wicket.util.WicketUtils; import org.artifactory.security.AccessLogger; import org.artifactory.security.ArtifactoryPermission; import org.artifactory.security.HttpAuthenticationDetails; import org.artifactory.security.UserInfo; import org.artifactory.util.SerializablePair; import org.artifactory.webapp.servlet.RequestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetails; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @author Yoav Landman */ public class ArtifactoryWebSession extends AuthenticatedWebSession { private static final Logger log = LoggerFactory.getLogger(ArtifactoryWebSession.class); private AuthenticationManager authenticationManager; private Authentication authentication; private Roles roles; private Map<String, SavedSearchResults> results; private SerializablePair<String, Long> lastLoginInfo; public static ArtifactoryWebSession get() { return (ArtifactoryWebSession) Session.get(); } public ArtifactoryWebSession(Request request) { super(request); authenticationManager = (AuthenticationManager) LazyInitProxyFactory.createProxy( AuthenticationManager.class, new SecurityServiceLocator()); } @Override public boolean authenticate(final String username, final String password) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); HttpServletRequest servletRequest = WicketUtils.getHttpServletRequest(); HttpServletResponse servletResponse = WicketUtils.getHttpServletResponse(); replaceSession(); // protect against session fixation WebAuthenticationDetails details = new UiAuthenticationDetails(servletRequest, servletResponse); authenticationToken.setDetails(details); boolean authenticated; try { Authentication authentication = authenticationManager.authenticate(authenticationToken); authenticated = authentication.isAuthenticated(); if (authenticated) { setAuthentication(authentication); if (StringUtils.isNotBlank(username) && (!username.equals(UserInfo.ANONYMOUS))) { //Save the user's last login info in the web session so we can display it in the welcome page ArtifactoryContext context = ContextHelper.get(); SecurityService securityService = context.beanForType(SecurityService.class); SerializablePair<String, Long> lastLoginInfo = securityService.getUserLastLoginInfo(username); ArtifactoryWebSession.get().setLastLoginInfo(lastLoginInfo); //Update the user's current login info in the database String remoteAddress = new HttpAuthenticationDetails(servletRequest).getRemoteAddress(); securityService.updateUserLastLogin(username, remoteAddress, System.currentTimeMillis()); } } } catch (AuthenticationException e) { authenticated = false; AccessLogger.loginDenied(authenticationToken); if (log.isDebugEnabled()) { log.debug("Failed to authenticate " + username, e); } } return authenticated; } private void setWicketRoles(Authentication authentication) { Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); String[] authorityRoles = new String[authorities.size()]; int i = 0; for (GrantedAuthority authority : authorities) { String role = authority.getAuthority(); authorityRoles[i] = role; i++; } roles = new Roles(authorityRoles); } public void signOutArtifactory() { signOut(); // Remove the authentication attribute early RequestUtils.removeAuthentication(WicketUtils.getHttpServletRequest()); // Clear authentication and authorization data saved in this session // (this WICKET session will still be used in the logout page) roles = null; authentication = null; results = null; SecurityContextHolder.clearContext(); invalidate(); } void setAuthentication(Authentication authentication) { this.authentication = authentication; if (authentication.isAuthenticated()) { setWicketRoles(authentication); //Log authentication if not anonymous if (!isAnonymous()) { AccessLogger.loggedIn(authentication); } //Set a http session token so that we can reuse the login in direct repo browsing HttpServletRequest httpServletRequest = WicketUtils.getHttpServletRequest(); RequestUtils.setAuthentication(httpServletRequest, authentication, true); //Update the spring security context bindAuthentication(); } dirty(); } void initAnonymousAuthentication() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.isAuthenticated()) { if (!isSignedIn() || (isAnonymous() && !UserInfo.ANONYMOUS.equals("" + authentication.getPrincipal()))) { // session is not logged in yet, but was already authenticated (probably by a filter) so set the // authentication and call signIn with empty params which will mark the session as authenticated setAuthentication(authentication); markSignedIn(); } } } /** * @return True is anonymous user is logged in to this session. */ boolean isAnonymous() { return authentication != null && UserInfo.ANONYMOUS.equals(authentication.getPrincipal().toString()); } @Override public Roles getRoles() { return roles; } public boolean hasRole(String role) { return roles != null && roles.hasRole(role); } public void setResults(SavedSearchResults savedSearchResults) { AuthorizationService authService = ContextHelper.get().getAuthorizationService(); if (authService.hasPermission(ArtifactoryPermission.DEPLOY)) { getResults().put(savedSearchResults.getName(), savedSearchResults); } } public SavedSearchResults getResults(String resultsName) { if (results != null) { return getResults().get(resultsName); } else { return null; } } public void removeResult(String resultsName) { if (results != null) { getResults().remove(resultsName); } } public Set<String> getResultNames() { if (results == null) { return Collections.emptySet(); } return getResults().keySet(); } public boolean hasResults() { return results != null && !results.isEmpty(); } public SerializablePair<String, Long> getLastLoginInfo() { return lastLoginInfo; } public void setLastLoginInfo(SerializablePair<String, Long> lastLoginInfo) { this.lastLoginInfo = lastLoginInfo; } private Map<String, SavedSearchResults> getResults() { if (results == null) { results = new HashMap<>(); } return results; } @Override public void detach() { SecurityContextHolder.clearContext(); super.detach(); } void bindAuthentication() { //Add the authentication to the request thread SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(authentication); } /** * Call this method when external authentication is performed (eg, cookie, token). */ public void markSignedIn() { super.signIn(true); } private static class SecurityServiceLocator implements IProxyTargetLocator { @Override public Object locateProxyTarget() { ArtifactoryContext context = ContextHelper.get(); // get the "ui" authentication manager (no password encryption stuff) AuthenticationManager security = (AuthenticationManager) context.getBean("authenticationManager"); return security; } } }
true
9756ec066f666958206276b3a35fe666ccfad461
Java
nguyenducbinh96/tkclock
/alarmclock/src/com/tkclock/voice/user_interaction/TkVoiceRecognizerCtrl.java
UTF-8
2,988
2.265625
2
[]
no_license
package com.tkclock.voice.user_interaction; import android.content.Context; import android.content.Intent; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; import android.util.Log; import android.widget.Toast; import com.tkclock.models.TkTextToSpeech; import static com.tkclock.models.TkTextToSpeech.TASK_PRIORITY_HIGH; import static com.tkclock.voice.notify_manager.TkVoiceCmd.COMMAND_OK_STR; import static com.tkclock.voice.notify_manager.TkVoiceCmd.COMMAND_UNSUPPORTED_STR; public class TkVoiceRecognizerCtrl implements TkVoiceListener.OnListenerResult { private static int MAX_RECOG_RESULT = 5; private static String TAG = "TkVoiceRecognizerCtrl"; TkTextToSpeech m_speaker; private SpeechRecognizer m_speech_recog; private String m_wait_confirm_cmd; private OnCommandProcessing m_controller; public interface OnCommandProcessing { public String OnProcess(String command); } private static final String supported_commands[] = {"pause", "stop", "dismiss", "turn off", "off", "repeat", "back", "next", "facebook", "gmail", "email", "weather", "news", "yes", "no"}; public TkVoiceRecognizerCtrl(OnCommandProcessing controller, TkTextToSpeech speaker) { m_speaker = speaker; m_wait_confirm_cmd = ""; m_controller = (OnCommandProcessing) controller; m_speech_recog = SpeechRecognizer.createSpeechRecognizer((Context)m_controller); m_speech_recog.setRecognitionListener(new TkVoiceListener(this, supported_commands)); } @Override public void OnCommandDetected(String command) { if (m_controller == null) { return; } else if(command.length() == 0) { Log.d(TAG, "Restart service"); m_controller.OnProcess(command); return; } Toast.makeText((Context)m_controller, command, Toast.LENGTH_LONG).show(); String result = m_controller.OnProcess(command); if (result.equals(COMMAND_OK_STR)) { Log.d(TAG, "Command is supported: " + command); } else if (result.equals(COMMAND_UNSUPPORTED_STR)) { Log.d(TAG, "Command is not supported: " + command); // TODO: speak the info to user m_speaker.acquire(TASK_PRIORITY_HIGH); m_speaker.speak("Command " + command + " is not supported"); m_speaker.release(TASK_PRIORITY_HIGH); } else { Log.d(TAG, "Suggest another command: " + command + " --> " + result); m_speaker.acquire(TASK_PRIORITY_HIGH); m_wait_confirm_cmd = result; m_speaker.speak("Do you want to " + result); m_speaker.release(TASK_PRIORITY_HIGH); } } public void start() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "voice.recognition.test"); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, MAX_RECOG_RESULT); m_speech_recog.startListening(intent); } public void stop() { m_speech_recog.stopListening(); m_speech_recog.destroy(); } }
true
f2b1a4eccb6fcfbe223aa45eac7254f24f573b4e
Java
tomdev2008/zxzshop-parent
/WMb2b-bizshop/src/main/java/com/wangmeng/common/web/filter/AuthorityFilter.java
UTF-8
2,682
2.203125
2
[]
no_license
package com.wangmeng.common.web.filter; import com.wangmeng.common.utils.LoginUtil; import com.wangmeng.service.api.UserInfoService; import com.wangmeng.service.bean.User; import com.wangmeng.spring.ApplicationContextHolderSingleton; import org.apache.log4j.Logger; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * <p> 权限校验过滤器 </p> * * @author changming.Y <changming.yaung.ah@gmail.com> * @since 2016-10-20 13:56 */ public class AuthorityFilter implements Filter { private final Logger logger = Logger.getLogger(LoginFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; String requestURL = request.getRequestURI().toString(); Long userId = LoginUtil.getCurrentUserId(request); int userType = 0; HttpServletResponse response = (HttpServletResponse)servletResponse; try { UserInfoService userInfoService = ApplicationContextHolderSingleton.getInstance().getBean("userInfoService"); User user = userInfoService.queryUserInfo(null, userId, null); if (user == null) { logger.warn("don't have the user"); response.sendRedirect(request.getContextPath() + "/pages/redirect-login.html"); return; } userType = user.getUserType(); } catch (Exception e) { logger.warn("get userInfo error", e); response.sendRedirect(request.getContextPath() + "/pages/redirect-login.html"); return; } if (requestURL.contains("buyer")) {//买家 if (userType != 1) { response.sendRedirect(request.getContextPath() + "/pages/redirect-login.html"); return; } } else if (requestURL.contains("seller")) {//卖家 if (userType != 2) { response.sendRedirect(request.getContextPath() + "/pages/redirect-login.html"); return; } } else if (requestURL.contains("third")) {//第三方 if (userType != 3) { response.sendRedirect(request.getContextPath() + "/pages/redirect-login.html"); return; } } filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
true
1540c7ba9b6e6b57ca3b885ee7ac6e416faf7a0f
Java
runnerdave/oca-8-prac
/chapter3/StringPrac.java
UTF-8
1,738
3.765625
4
[]
no_license
import java.util.*; public class StringPrac{ public static void main(String[] args){ String myString = "unoSeLaCala"; String myString2 = "\t\n y dos "; String myString3 = myString2.trim().concat(myString); System.out.println(myString); System.out.println("largo de myString:" + myString.length()); char c = myString.charAt(3); System.out.println("el caracter 3 en unoSeLaCala es:" + c); System.out.println("el caracter 3 (en int) en unoSeLaCala es:" + (int)c); System.out.println("===Practice trim==="); System.out.println(myString2 + "|"); System.out.println(myString3 + "|"); System.out.println(myString2.trim() + "|"); myString2 = myString2.trim(); System.out.println(myString2 + "|"); System.out.println("trim this ".trim() + "|"); System.out.println("===Practice substring==="); System.out.println("myString:" + myString); System.out.println("sub 0,1:" + myString.substring(0,1)); System.out.println("sub 1,1:" + myString.substring(1,1)); System.out.println("sub 3,4:" + myString.substring(3,4)); System.out.println("sub 3,3:" + myString.substring(3,3)); try { System.out.println("sub 3,2:" + myString.substring(3,2)); } catch(StringIndexOutOfBoundsException e) { System.out.println("sub 3,2 throws exception:" + e.getMessage()); } System.out.println("===Practice concat==="); System.out.println("myString:".concat("concat")); System.out.println("===Practice indexOf==="); System.out.println(myString); System.out.println(myString.indexOf("Se")); System.out.println("===Practice array of String==="); //String[] grades; grades = {"1","2"};//does not compile String[] grades = new String[] {"1","2"}; System.out.println(Arrays.asList(grades)); } }
true
5ca513f73302b2a8b5d18264b79f0b026d490aa5
Java
wintermute766/code_practice
/src/main/java/test/my/Main.java
UTF-8
4,118
3.3125
3
[]
no_license
package test.my; import java.util.*; import java.util.stream.Collectors; class Main { static String findNumberOfReplacements(String input) { String[] arr = input.split("\n"); int birthdays = Integer.parseInt(arr[0]); String[] result = new String[birthdays]; for (int i = 1; i < birthdays + 1; i++) { int num = numberOfReplacements(arr[i].toCharArray()); result[i - 1] = String.format("Case #%d: %s", i, num); } return String.join("\n", result); } static int numberOfReplacements(char[] arr) { Set<Character> vowels = "AEIOU".chars() .mapToObj(chr -> (char) chr) .collect(Collectors.toSet()); Set<Character> consonants = "BCDFGHJKLMNPQRSTVWXZ".chars() .mapToObj(chr -> (char) chr) .collect(Collectors.toSet()); Map<Character, Integer> cmap = new HashMap<>(); Map<Character, Integer> vmap = new HashMap<>(); int cnumber = 0; int vnumber = 0; for (char key : arr) { if (vowels.contains(key) && vmap.containsKey(key)) { int freq = vmap.get(key); freq++; vmap.put(key, freq); vnumber++; } else if (vowels.contains(key)) { vmap.put(key, 1); vnumber++; } else if (consonants.contains(key) && cmap.containsKey(key)) { int freq = cmap.get(key); freq++; cmap.put(key, freq); cnumber++; } else { cmap.put(key, 1); cnumber++; } } int max_count_v = 0; for (Map.Entry<Character, Integer> val : vmap.entrySet()) { if (max_count_v < val.getValue()) { max_count_v = val.getValue(); } } int max_count_c = 0; for (Map.Entry<Character, Integer> val : cmap.entrySet()) { if (max_count_c < val.getValue()) { max_count_c = val.getValue(); } } int i1 = vnumber + 2 * (cnumber - max_count_c); int i2 = cnumber + 2 * (vnumber - max_count_v); if (i1 < 0) { return i2; } if (i2 < 0) { return i1; } return Math.min(i1, i2); } static int numberOfReplacements1(char[] arr) { return 0; } public static void main(String[] args) { String s = "7\n" + "ABC\n" + "2\n" + "BA\n" + "CA\n" + "ABC\n" + "2\n" + "AB\n" + "AC\n" + "F\n" + "0\n" + "BANANA\n" + "4\n" + "AB\n" + "AN\n" + "BA\n" + "NA\n" + "FBHC\n" + "4\n" + "FB\n" + "BF\n" + "HC\n" + "CH\n" + "FOXEN\n" + "8\n" + "NI\n" + "OE\n" + "NX\n" + "EW\n" + "OI\n" + "FE\n" + "FN\n" + "XW\n" + "CONSISTENCY\n" + "26\n" + "AB\n" + "BC\n" + "CD\n" + "DE\n" + "EF\n" + "FG\n" + "GH\n" + "HI\n" + "IJ\n" + "JK\n" + "KL\n" + "LM\n" + "MN\n" + "NO\n" + "OP\n" + "PQ\n" + "QR\n" + "RS\n" + "ST\n" + "TU\n" + "UV\n" + "VW\n" + "WX\n" + "XY\n" + "YZ\n" + "ZA"; System.out.println(findNumberOfReplacements(s)); } }
true
a7cb7768aa2ce6b2530b1e036e9b6262a1ca0739
Java
CostelloLab/GSEARerank
/.metadata/.plugins/org.eclipse.core.resources/.history/6a/c03fdfe1466e001714e6eab34308208c.java
UTF-8
1,255
1.882813
2
[]
no_license
/******************************************************************************* * Copyright (c) 2003-2016 Broad Institute, Inc., Massachusetts Institute of Technology, and Regents of the University of California. All rights reserved. *******************************************************************************/ package xtools.api.param; import edu.mit.broad.genome.objects.Dataset; import xtools.api.AbstractTool; import java.awt.event.ActionListener; /** * @author Aravind Subramanian * @version %I%, %G% */ public class DatasetReqdParam extends PobParam implements ActionListener { /** * Class constructor */ public DatasetReqdParam() { this(RES, RES_ENGLISH, RES_DESC); } public DatasetReqdParam(final String name, final String nameEnglish, final String desc) { super(name, nameEnglish, Dataset.class, desc, new Dataset[]{}, true); } // Override this parameter for custom dataset impls public Dataset getDataset() throws Exception { return (Dataset) getPob(); } public Dataset getDataset(final ChipOptParam chipParam) throws Exception { Dataset ds = getDataset(); AbstractTool.setChip(ds, chipParam); return ds; } } // End class DatasetReqdParam
true
620e9c716b7d62915402f0630d0838497cacc271
Java
jetoze/gunga
/src/main/java/jetoze/gunga/selection/SelectionAction.java
UTF-8
1,178
2.640625
3
[]
no_license
package jetoze.gunga.selection; import static java.util.Objects.*; import java.awt.event.ActionEvent; import java.util.function.Consumer; import javax.annotation.Nullable; import javax.swing.Action; import jetoze.gunga.UiThread; public interface SelectionAction<T> extends Action { void setSelectionSource(SelectionSource<T> source); public static <T> SelectionAction<T> forSingleItem(String name, Consumer<? super T> handler) { requireNonNull(handler); return new AbstractSelectionAction<T>(name) { @Nullable private T selectedItem; @Override public void actionPerformed(ActionEvent e) { T item = selectedItem; if (item != null) { UiThread.acceptLater(handler, item); } } @Override protected void handleSelection(Selection<T> selection) { selectedItem = (selection.getItems().size() == 1) ? selection.getItems().get(0) : null; setEnabled(selectedItem != null); } }; } }
true
84c0ac1211cb652d19bfa9608c4bde390517476b
Java
ZhouYangGaoGao/MT
/maTao/src/main/java/com/matao/adapter/XttzAdapter.java
UTF-8
1,848
2.046875
2
[]
no_license
package com.matao.adapter; import java.util.List; import android.content.Context; import android.view.View; import android.view.View.OnClickListener; import com.matao.activity.HomeActivity; import com.matao.bean.HeadAdList; import com.matao.matao.R; import com.matao.utils.Logger; import com.matao.utils.ViewHolder; /** * @author: YeClazy * @E-mail: 18701120043@163.com * @version: 创建时间:2015-7-13 上午11:02:48 * @Description:系统通知列表适配器 */ public class XttzAdapter extends CommonAdapter<HeadAdList> { private HomeActivity home; private int msgnum; /** * @param context * @param mDatas * @param itemLayoutId */ public XttzAdapter(Context context, List<HeadAdList> mDatas, int itemLayoutId, int num) { super(context, mDatas, itemLayoutId); home = HomeActivity.getHomeAvtivity(); msgnum = num; } @Override public void convert(final ViewHolder helper, final HeadAdList item, int position) { helper.setImageByUrl(R.id.xttz_icon, item.getHeadImage()); helper.setText(R.id.xttz_name, item.getNickName()); helper.setText(R.id.xttz_content, item.getNoticeContent()); if (msgnum > position) { helper.getView(R.id.xttz_layout).setBackgroundResource( R.color.item_msg); } else { helper.getView(R.id.xttz_layout).setBackgroundResource( android.R.color.white); } Logger.e("msgnum----------------", msgnum); Logger.e("position----------------", position); if (msgnum > position) { helper.getView(R.id.xttz_layout).setBackgroundResource(R.color.msg); } else { helper.getView(R.id.xttz_layout).setBackgroundResource(R.color.set); } helper.getConvertView().setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { helper.getView(R.id.xttz_layout).setBackgroundResource( R.color.set); home.linkTo(item); } }); } }
true
ee0cae894b7e6daede61f3358875bbd8f4f2ed1a
Java
mstane/cloud-app-watch
/cloudappwatch/src/main/java/io/github/ms/cloudappwatch/repository/AppRepository.java
UTF-8
390
1.773438
2
[ "MIT" ]
permissive
package io.github.ms.cloudappwatch.repository; import io.github.ms.cloudappwatch.domain.App; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data repository for the App entity. */ @SuppressWarnings("unused") @Repository public interface AppRepository extends JpaRepository<App, Long>, JpaSpecificationExecutor<App> { }
true
8d939c9955ec0c54973a58b5d0f077e9a7892aa1
Java
congphuong1703/order-banquet
/src/main/java/com/btl/dattiec/SecurityConfig.java
UTF-8
1,012
2.125
2
[]
no_license
package com.btl.dattiec; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest() .permitAll(); } @Override public void configure(WebSecurity web) throws Exception { web .ignoring() .antMatchers("/resources/**", "/static/**", "/webfonts/**", "/css/**", "/js/**", "/images/**") .and().ignoring(); } }
true
390abddcd56ee15390994817c87674f39750a5a9
Java
cometman/Scheduler
/Scheduler/src/test/java/com/imedical/data/TestLogger.java
UTF-8
392
1.921875
2
[]
no_license
package com.imedical.data; import static org.junit.Assert.*; import java.io.IOException; import java.util.logging.Level; import org.junit.Test; import com.imedical.common.LogUtil; public class TestLogger { @Test public void LogTester() { LogUtil.writeMessage("Here is a test"); LogUtil.writeMessage("Here is a testsdfsdfsdf"); LogUtil.closeWriter(); } }
true
f9c45d39b1881a918779c890f9e7062cff1d96e8
Java
WAPProject/CyclingEvent
/Ride/src/main/java/com/cs/servlet/LoginFilter.java
UTF-8
3,182
2.53125
3
[]
no_license
package com.cs.servlet; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * Created by tao on 2017/4/6 0006. */ @WebFilter(filterName="LoginFilter",urlPatterns="/*") public class LoginFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)resp; String currentURL = request.getRequestURI(); System.out.println("currentURL:"+currentURL); String ctxPath = request.getContextPath(); System.out.println("ctxPath:"+ctxPath); //除掉项目名称时访问页面当前路径 String targetURL = currentURL.substring(ctxPath.length()); System.out.println("targetURL:"+targetURL); //登录页面 String loginPage = "/login.jsp"; //注册页面 String registerPage = "/register.jsp"; //登录的Servlet对应的url String loginServlet = "/user?action=login"; HttpSession session = request.getSession(false); //对当前页面进行判断,如果当前页面不为登录页面 if(loginPage.equals(targetURL) || "/user".equalsIgnoreCase(targetURL)){ //这里表示如果当前页面是登陆页面,跳转到登陆页面 chain.doFilter(request, response); }else if(registerPage.equals(targetURL)){ //这里表示如果当前页面是注册页面,跳转到注册页面 chain.doFilter(request, response); }else if(targetURL.endsWith(".txt")|| targetURL.endsWith(".js")|| targetURL.endsWith(".css")|| targetURL.endsWith(".png")|| targetURL.endsWith(".jpg")|| targetURL.endsWith(".jpeg")|| targetURL.endsWith(".bmp") ){ //这里表示如果是静态资源,可以访问 chain.doFilter(request, response); return; } else{ if(loginServlet.equals(targetURL)){ //Servlet验证 chain.doFilter(request, response); return; }else{ //在不为登陆页面时,再进行判断,如果不是登陆页面也没有session则跳转到登录页面, if(session == null || session.getAttribute(UserServlet.USERSESSION) == null ){ response.sendRedirect(ctxPath+loginPage); System.out.println("redirect:"+ctxPath+loginPage); }else{ //这里表示正确,会去寻找下一个链,如果不存在,则进行正常的页面跳转 chain.doFilter(request, response); return; } } } } public void init(FilterConfig config) throws ServletException { } }
true
011e510dd3a5e753a203b3980a6faf7352fce931
Java
732275239/nfc
/app/src/main/java/com/chuyu/nfc/bean/UserBean.java
UTF-8
308
2.046875
2
[]
no_license
package com.chuyu.nfc.bean; /** * 名称:登录获取用户信息 */ public class UserBean { /** * token : 28051dcad9802db9ad53a245611e4695 */ private String token; public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
true
e16ca7b558a5f42dcc29e9c2b2e4b04407db80b4
Java
MeenakshiSundaram-93/nmsrepo
/src/test/java/testcases/HomePageTestCases.java
UTF-8
1,000
2.265625
2
[]
no_license
package testcases; import org.testng.annotations.Test; import basetest.BaseTest; import pages.HomePage; import pages.SearchPage; public class HomePageTestCases extends BaseTest { @Test(priority = 1) public void validateEnteringWrongValuesInMandateFields() { test = extent.createTest("Validate the Homepage by entering wrong name in the field", "Enter the wrong value to validate error msg"); HomePage homePage = new HomePage(driver, test); homePage.validateHomePage(); homePage.enterWrongMandatoryFields(); homePage.validateErrorMsg(); } @Test(priority = 2) public void validateEnteringValuesInMandateFields() { test = extent.createTest("Validate the Homepage by entering Correct values in the field", "Enter the right value to validate error msgs"); HomePage homePage = new HomePage(driver, test); SearchPage searchPage = new SearchPage(driver, test); homePage.validateHomePage(); homePage.enterMandatoryFields(); searchPage.validateSearchPage(); } }
true
1eaa8578529097763a07891f852c24337cc546fc
Java
washhy/trony
/src/main/java/com/hunantv/bigdata/troy/statistics/StatisticsUtils.java
UTF-8
3,622
2.359375
2
[]
no_license
package com.hunantv.bigdata.troy.statistics; import com.google.common.base.Strings; import com.google.common.collect.Maps; import com.hunantv.bigdata.troy.Lifecycle; import com.hunantv.bigdata.troy.configure.AbstractConfigManager; import com.hunantv.bigdata.troy.configure.LogConfig; import com.hunantv.bigdata.troy.entity.Message; import com.hunantv.bigdata.troy.entity.MessageStatus; import com.hunantv.bigdata.troy.entity.Statistics; import com.hunantv.bigdata.troy.tools.Constants; import com.hunantv.bigdata.troy.tools.JsonUtils; import com.hunantv.bigdata.troy.tools.Utils; import java.util.Map; /** * 日志统计类 * Copyright (c) 2014, hunantv.com All Rights Reserved. * <p/> * User: jeffreywu MailTo:jeffreywu@sohu-inc.com * Date: 15/1/20 * Time: PM7:16 */ public class StatisticsUtils implements Lifecycle { public static Map<String, Statistics> configedStats; public static Map<String, Statistics> nonConfigedStats; public static Statistics totalStat; public StatisticsUtils(AbstractConfigManager configManager){ Map<Integer, LogConfig> logConfigs = configManager.getConfigMap(); configedStats = Maps.newHashMap(); nonConfigedStats = Maps.newHashMap(); Statistics stat; String time = Utils.getCurrentTime(); long timestamp = Utils.getUnixTimeStamp(); for(LogConfig config: logConfigs.values()){ for(StatStatus status : StatStatus.values()){ stat = new Statistics(); stat.setBid(config.getBid()); stat.setStartTime(time); stat.setStartTimeStamp(timestamp); stat.setLastTime(time); stat.setLastTimeStamp(timestamp); stat.setTotalCounter(0); configedStats.put(config.getBid() + "_" + status, stat); stat = new Statistics(); stat.setBid(Constants.INVALID_BID); stat.setStartTime(time); stat.setStartTimeStamp(timestamp); stat.setLastTime(time); stat.setLastTimeStamp(timestamp); stat.setTotalCounter(0); nonConfigedStats.put(Constants.INVALID_BID + "_" + status, stat); } } totalStat = new Statistics(); totalStat.setBid(Constants.TOTAL_BID); totalStat.setStartTime(time); totalStat.setStartTimeStamp(timestamp); totalStat.setLastTime(time); totalStat.setLastTimeStamp(timestamp); totalStat.setTotalCounter(0); } public static Message stat(Message message) { stat(message.getBid(), message.getStatus()); return message; } public static void stat(String bid, MessageStatus status) { Statistics stat; if(!Strings.isNullOrEmpty(bid) && configedStats.get(bid + "_" + status) != null){ stat = configedStats.get(bid + "_" + status); } else { stat = nonConfigedStats.get(Constants.INVALID_BID + "_" + status); } stat.increment(); } public static void statTotal(){ totalStat.increment(); } public static String getStats(){ Map<String, Statistics> stats = Maps.newHashMap(); stats.put(Constants.TOTAL_BID, totalStat); stats.putAll(configedStats); stats.putAll(nonConfigedStats); return JsonUtils.simpleJson(stats); } private static enum StatStatus { BUILD_ERROR, PARSE_ERROR, VALID_SUCC, VALID_ERROR, IS_DEBUG, } @Override public void doStart() { } @Override public void destory() { } }
true
fda989851f481b407ef564ebcf1155bbf7125df7
Java
petercsengodi/games
/AMediaEditorCollection/src/main/java/hu/csega/editors/common/lens/EditorLensPipeline.java
UTF-8
2,181
2.609375
3
[]
no_license
package hu.csega.editors.common.lens; public class EditorLensPipeline { private EditorLensTranslateImpl translate = new EditorLensTranslateImpl(); private EditorLensScaleImpl scale = new EditorLensScaleImpl(); public void setScale(double scaling) { EditorPoint current = scale.getScaling(); current.setX(scaling); current.setY(scaling); current.setZ(scaling); current.setW(1.0); } public void setScale(EditorPoint scaling) { EditorPoint current = scale.getScaling(); current.setX(scaling.getX()); current.setY(scaling.getY()); current.setZ(scaling.getZ()); current.setW(1.0); } public void setTranslation(EditorPoint translation) { EditorPoint current = translate.getTranslation(); current.setX(translation.getX()); current.setY(translation.getY()); current.setZ(translation.getZ()); current.setW(0.0); } public void addTranslation(double x, double y, double z) { EditorPoint ep = new EditorPoint(x, y, z, 0.0); scale.fromScreenToModel(ep); EditorPoint current = translate.getTranslation(); current.addValuesFrom(ep); current.setW(0.0); } public void addTranslation(EditorPoint translation) { EditorPoint ep = new EditorPoint(translation); scale.fromScreenToModel(ep); EditorPoint current = translate.getTranslation(); current.addValuesFrom(ep); current.setW(0.0); } public EditorPoint fromModelToScreen(double x, double y, double z) { EditorPoint result = new EditorPoint(x, y, z, 1.0); translate.fromModelToScreen(result); scale.fromModelToScreen(result); return result; } public EditorPoint fromModelToScreen(EditorPoint original) { EditorPoint result = new EditorPoint(original); translate.fromModelToScreen(result); scale.fromModelToScreen(result); return result; } public EditorPoint fromScreenToModel(EditorPoint original) { EditorPoint result = new EditorPoint(original); scale.fromScreenToModel(result); translate.fromScreenToModel(result); return result; } public EditorPoint fromScreenToModel(double x, double y) { EditorPoint result = new EditorPoint(x, y, 0, 1); scale.fromScreenToModel(result); translate.fromScreenToModel(result); return result; } }
true
440fd03966f9691d4171ae7c18d6fac3268b08ed
Java
liangshanhero/energyDeviceManage
/cmi/cn/edu/scau/cmi/service/WhstrategyService.java
UTF-8
1,037
1.929688
2
[]
no_license
package cn.edu.scau.cmi.service; import java.util.List; import java.util.Set; import cn.edu.scau.cmi.domain.*; public interface WhstrategyService { public void saveWhstrategy(Whstrategy whstrategy); public Whstrategy saveWhstrategyWhdevice(Integer id, Whdevice related_whdevice); public Whstrategy saveWhstrategyWhstrategydetails(Integer id, Whstrategydetail related_whstrategydetails); public Set<Whstrategy> loadWhstrategys(); public Set<Whstrategy> loadWhstrategys(int index, int size); public void deleteWhstrategy(Whstrategy whstrategy); public Whstrategy deleteWhstrategyWhdevice(Integer id, Integer related_whdevice_id); public Whstrategy deleteWhstrategyWhstrategydetails(Integer id, Integer related_whstrategydetails_id); public List<Whstrategy> findAllWhstrategys(Integer startResult, Integer maxRows); public Whstrategy findWhstrategyByPrimaryKey(Integer id); public Integer countwhstrategys(); public Integer countRelativeWhdeviceWhstrategys(Integer whdevice); }
true
3116a3e1c748dc66c2109cbbb604d2eefa182486
Java
r-asano/java_experience
/src/java_experience/Cf7_4.java
UTF-8
1,293
3.328125
3
[]
no_license
package java_experience; // XML形式のデータを読み込む import java.io.FileInputStream; import java.io.InputStream; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class Cf7_4 { public static void main(String[] args) throws Exception { InputStream iStream = new FileInputStream("C:\\rpgsave.xml"); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(iStream); Element hero = document.getDocumentElement(); Element weapon = findChildByTag(hero, "weapon"); Element power = findChildByTag(weapon, "power"); String value = power.getTextContent(); } // 指定された名前を持つタグの最初の子タグを返す private static Element findChildByTag(Element self, String name) { // すべての子を取得 NodeList children = self.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { if(children.item(i) instanceof Element) { Element element = (Element) children.item(i); // タグ名を照会 if(element.getTagName().equals(name)) { // selfが持つ要素の中で、タグ名がnameである要素をシーケンシャルに探す return element; } } } return null; } }
true
b423c658219a0ef2ad67f24b29cbee961071811b
Java
lukerowley101/farmer2market
/src/main/java/com/mastek/farmertomarket/dao/itemJPADAO.java
UTF-8
219
1.585938
2
[]
no_license
package com.mastek.farmertomarket.dao; import org.springframework.data.repository.CrudRepository; import com.mastek.farmertomarket.entities.item; public interface itemJPADAO extends CrudRepository<item, Integer>{ }
true
13e8abceb7bbc205d1a64cc1202489b3811529d6
Java
NickOwhadi/java-practice
/src/day27_main/CopyArrayWholeOrSome.java
UTF-8
680
3.171875
3
[]
no_license
package day27_main; import java.util.*; public class CopyArrayWholeOrSome { public static void main(String[] args) { // TODO Auto-generated method stub double[] d1 = { 2.3, 4.5, 12.4 }; double[] d2 = d1; System.out.println(Arrays.toString(d1)); System.out.println(Arrays.toString(d2)); d1[0] = 1000.2; System.out.println(Arrays.toString(d1)); System.out.println(Arrays.toString(d2)); d2[1] = 4000.5; System.out.println(Arrays.toString(d1)); System.out.println(Arrays.toString(d2)); double []d3 = Arrays.copyOf(d2, d2.length); d1[2]=34.76; System.out.println(Arrays.toString(d1)); System.out.println("d3: "+Arrays.toString(d3)); } }
true
386b87459548b90b7e28a33afd1d07efc6484540
Java
MathiasMonstrey/fosil_decompiled
/com/portfolio/platform/data/source/remote/NotificationRemoteDataSource.java
UTF-8
3,489
1.5625
2
[]
no_license
package com.portfolio.platform.data.source.remote; import android.util.SparseArray; import com.fossil.wearables.fsl.appfilter.AppFilter; import com.fossil.wearables.fsl.contact.Contact; import com.fossil.wearables.fsl.contact.ContactGroup; import com.fossil.wearables.fsl.contact.EmailAddress; import com.fossil.wearables.fsl.contact.PhoneNumber; import com.fossil.wearables.fsl.shared.BaseFeatureModel; import com.portfolio.platform.data.source.NotificationsDataSource; import com.portfolio.platform.model.PhoneFavoritesContact; import java.util.List; public class NotificationRemoteDataSource implements NotificationsDataSource { public List<ContactGroup> getAllContactGroups(int i) { return null; } public void saveContactGroup(ContactGroup contactGroup) { } public void removeContactGroup(ContactGroup contactGroup) { } public void saveContactGroupList(List<ContactGroup> list) { } public void removeContactGroupList(List<ContactGroup> list) { } public void saveContact(Contact contact) { } public void removeContact(Contact contact) { } public void saveListContact(List<Contact> list) { } public void removeListContact(List<Contact> list) { } public void savePhoneNumber(PhoneNumber phoneNumber) { } public void saveListPhoneNumber(List<PhoneNumber> list) { } public void saveEmailAddress(EmailAddress emailAddress) { } public List<ContactGroup> getContactGroupsMatchingSms(String str, int i) { return null; } public List<ContactGroup> getContactGroupsMatchingIncomingCall(String str, int i) { return null; } public List<ContactGroup> getContactGroupsMatchingEmail(String str, int i) { return null; } public void saveAppFilter(AppFilter appFilter) { } public void removeAllAppFilters() { } public void removeAppFilter(AppFilter appFilter) { } public void removeListAppFilter(List<AppFilter> list) { } public void saveListAppFilters(List<AppFilter> list) { } public List<AppFilter> getAllAppFilters(int i) { return null; } public AppFilter getAppFilterByType(String str, int i) { return null; } public List<AppFilter> getAllAppFilterByHour(int i, int i2) { return null; } public List<AppFilter> getAllAppFilterByVibration(int i) { return null; } public SparseArray<List<BaseFeatureModel>> getAllNotificationsByHour(String str) { return null; } public void clearAllNotificationSetting() { } public void removeRedundantContact() { } public List<Integer> getLocalContactId() { return null; } public List<Integer> getContactGroupId(List<Integer> list) { return null; } public void removeLocalRedundantContact(List<Integer> list) { } public void removeLocalRedundantContactGroup(List<Integer> list) { } public void removePhoneNumber(List<Integer> list) { } public Contact getContactById(int i) { return null; } public void removePhoneNumberByContactGroupId(int i) { } public void clearAllPhoneFavoritesContacts() { } public void removePhoneFavoritesContact(PhoneFavoritesContact phoneFavoritesContact) { } public void removePhoneFavoritesContact(String str) { } public void savePhoneFavoritesContact(PhoneFavoritesContact phoneFavoritesContact) { } }
true
f5850529c0642f37b8e9f36eab721e6eed788335
Java
raghavmysari/egen-be-challenge
/src/main/java/Company.java
UTF-8
337
2.59375
3
[]
no_license
import lombok.Data; @Data public class Company implements IsValid{ String name, website; public Company(String name, String website) { this.name = name; this.website = website; } public boolean valid() { return name != null && website !=null && !name.equals("") && website.equals(""); } }
true
e3598b96684a6d879396d36501f98bf45b8cbb92
Java
zendawg/org.w3c.atom
/src/main/java/org/hl7/fhir/impl/ConformanceImplementationImpl.java
UTF-8
3,501
1.984375
2
[]
no_license
/* * XML Type: Conformance.Implementation * Namespace: http://hl7.org/fhir * Java type: org.hl7.fhir.ConformanceImplementation * * Automatically generated - do not modify. */ package org.hl7.fhir.impl; /** * An XML Conformance.Implementation(@http://hl7.org/fhir). * * This is a complex type. */ public class ConformanceImplementationImpl extends org.hl7.fhir.impl.BackboneElementImpl implements org.hl7.fhir.ConformanceImplementation { private static final long serialVersionUID = 1L; public ConformanceImplementationImpl(org.apache.xmlbeans.SchemaType sType) { super(sType); } private static final javax.xml.namespace.QName DESCRIPTION$0 = new javax.xml.namespace.QName("http://hl7.org/fhir", "description"); private static final javax.xml.namespace.QName URL$2 = new javax.xml.namespace.QName("http://hl7.org/fhir", "url"); /** * Gets the "description" element */ public org.hl7.fhir.String getDescription() { synchronized (monitor()) { check_orphaned(); org.hl7.fhir.String target = null; target = (org.hl7.fhir.String)get_store().find_element_user(DESCRIPTION$0, 0); if (target == null) { return null; } return target; } } /** * Sets the "description" element */ public void setDescription(org.hl7.fhir.String description) { generatedSetterHelperImpl(description, DESCRIPTION$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON); } /** * Appends and returns a new empty "description" element */ public org.hl7.fhir.String addNewDescription() { synchronized (monitor()) { check_orphaned(); org.hl7.fhir.String target = null; target = (org.hl7.fhir.String)get_store().add_element_user(DESCRIPTION$0); return target; } } /** * Gets the "url" element */ public org.hl7.fhir.Uri getUrl() { synchronized (monitor()) { check_orphaned(); org.hl7.fhir.Uri target = null; target = (org.hl7.fhir.Uri)get_store().find_element_user(URL$2, 0); if (target == null) { return null; } return target; } } /** * True if has "url" element */ public boolean isSetUrl() { synchronized (monitor()) { check_orphaned(); return get_store().count_elements(URL$2) != 0; } } /** * Sets the "url" element */ public void setUrl(org.hl7.fhir.Uri url) { generatedSetterHelperImpl(url, URL$2, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON); } /** * Appends and returns a new empty "url" element */ public org.hl7.fhir.Uri addNewUrl() { synchronized (monitor()) { check_orphaned(); org.hl7.fhir.Uri target = null; target = (org.hl7.fhir.Uri)get_store().add_element_user(URL$2); return target; } } /** * Unsets the "url" element */ public void unsetUrl() { synchronized (monitor()) { check_orphaned(); get_store().remove_element(URL$2, 0); } } }
true
8be621828bd4732f9e393d9d38064e97b8805159
Java
Lawrence982/NC_2grp_2016
/eav/src/main/java/web/ChatController.java
UTF-8
3,137
2.21875
2
[]
no_license
package web; /** * Created by Hroniko on 11.05.2017. */ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import service.chat.ChatManager; import service.chat.ChatRequest; import service.chat.ChatResponse; import java.lang.reflect.InvocationTargetException; import java.sql.SQLException; import java.text.ParseException; import java.util.ArrayList; import java.util.concurrent.ExecutionException; // Класс-контроллер для работы с чатом встречи @Controller public class ChatController { // 2017-05-11 К запросу на получение ВСЕХ сообщений данной встречи @RequestMapping(value = "/getAllMessagesChat", method = RequestMethod.POST, headers = {"Content-type=application/json"}) @ResponseBody public ArrayList<ChatResponse> getAllMessagesChat(@RequestBody ChatRequest chatRequest) throws SQLException, InvocationTargetException, NoSuchMethodException, ParseException, IllegalAccessException, ExecutionException { return new ChatManager().getAll(chatRequest); } // 2017-05-11 К запросу на получение некоторых (начиная с определенного айди) сообщений данной встречи @RequestMapping(value = "/getMessagesChatAfterId", method = RequestMethod.POST, headers = {"Content-type=application/json"}) @ResponseBody public ArrayList<ChatResponse> getMessagesChatAfterId(@RequestBody ChatRequest chatRequest) throws SQLException, InvocationTargetException, NoSuchMethodException, ParseException, IllegalAccessException, ExecutionException { return new ChatManager().getMessagesAfterId(chatRequest); } // 2017-05-11 К запросу на отправку сообщения со страницы и последующее получение некоторых (начиная с определенного айди) сообщений данной встречи @RequestMapping(value = "/sendMessageChat", method = RequestMethod.POST, headers = {"Content-type=application/json"}) @ResponseBody public ArrayList<ChatResponse> sendMessageChat(@RequestBody ChatRequest chatRequest) throws SQLException, InvocationTargetException, NoSuchMethodException, ParseException, IllegalAccessException, ExecutionException { new ChatManager().sendMessage(chatRequest); // Крепим к сейверу новое сообщение return new ChatManager().getMessagesAfterId(chatRequest); // и подгружаем все новые сообщения } /* // 2017-05-12 Тестовое public ArrayList<ChatResponse> getAllMessagesChat1(ChatRequest chatRequest) throws NoSuchMethodException, ExecutionException, ParseException, SQLException, IllegalAccessException, InvocationTargetException { ArrayList<ChatResponse> res = new ArrayList<>(); res.add(new ChatResponse(-1, "00", "Проверка", 11, "Vasya", "pic")); return res; } */ }
true
181b034a5626c615f43a8fcdf1499629ecc67ba6
Java
exsolvi/maven-eclipse-configurator-plugin
/src/main/java/se/exsolvi/maven/plugin/eclipseconfigurator/mojo/MojoParameter.java
UTF-8
1,662
2.515625
3
[]
no_license
package se.exsolvi.maven.plugin.eclipseconfigurator.mojo; public class MojoParameter { private final String name; private final String value; private boolean mandatory = false; private Class<? extends MojoParameterValidator> validator; public MojoParameter(String name, String value, boolean mandatory) { this.name = name; this.value = value; this.mandatory = mandatory; } public MojoParameter(String name, String value, boolean mandatory, Class<? extends MojoParameterValidator> validator) { this(name, value, mandatory); this.validator = validator; } public String getName() { return name; } public String getValue() { return value; } public boolean isMandatory() { return mandatory; } public Class<? extends MojoParameterValidator> getValidatorClass() { return validator; } public MojoParameterValidator getValidator() { MojoParameterValidator validatorInstance = null; if (validator != null) { try { validatorInstance = validator.newInstance(); validatorInstance.setMojoParameter(this); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } return validatorInstance; } }
true
39d5755d8692821af44194e84487bc4e2a6d797b
Java
goxr3plus/JTouchBar
/src/test/java/com/thizzer/jtouchbar/swt/JTouchBarSWTTest.java
UTF-8
1,208
2.328125
2
[ "MIT" ]
permissive
/** * JTouchBar * * Copyright (c) 2018 thizzer.com * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * @author M. ten Veldhuis */ package com.thizzer.jtouchbar.swt; import static org.junit.Assert.assertNotNull; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import com.thizzer.jtouchbar.JTouchBar; import com.thizzer.jtouchbar.JTouchBarTestUtils; @Ignore public class JTouchBarSWTTest { @Before public void setup() { Display.getDefault(); } @Test public void test() { JTouchBar jTouchBar = JTouchBarTestUtils.constructTouchBar(); assertNotNull(jTouchBar); Display display = Display.getCurrent(); Shell shell = new Shell(display); shell.setLayout(new FillLayout()); shell.open(); jTouchBar.show( shell ); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); break; } } display.dispose(); } }
true
548cf2ae7477ee7b1e3a99f0fbcaf7db693c8929
Java
Fitria01/BouquetApp
/app/src/main/java/com/example/project/PemesananActivity.java
UTF-8
8,712
1.960938
2
[]
no_license
package com.example.project; import androidx.appcompat.app.AppCompatActivity; import android.app.DatePickerDialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.Calendar; public class PemesananActivity extends AppCompatActivity { TextView tv_tanggal, hrg; EditText et_nama, et_wa, et_alamat, et_total, et_card, et_tanggal; RadioGroup rgpilih; RadioButton rose, peony, wisuda; Spinner pilihan; Button simpan, plus, min; Integer valuejumlah = 0; int harga [] = { 30000, 35000, 40000}; TextView tv_angka; DatePickerDialog.OnDateSetListener setListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pemesanan); hrg = findViewById(R.id.hrg); tv_tanggal = findViewById(R.id.tv_tanggal); et_nama = findViewById(R.id.et_nama); et_wa = findViewById(R.id.et_wa); et_alamat = findViewById(R.id.et_alamat); et_card = findViewById(R.id.et_card); et_total = findViewById(R.id.et_total); rgpilih = findViewById(R.id.rgpilih); rose = findViewById(R.id.rose); peony = findViewById(R.id.peony); wisuda = findViewById(R.id.wisuda); pilihan = findViewById(R.id.pilihan); simpan = findViewById(R.id.simpan); plus = findViewById(R.id.plus); min = findViewById(R.id.min); et_tanggal = findViewById(R.id.et_tanggal); if (savedInstanceState != null) { String nilaiSaved = savedInstanceState.getString("nilai"); tv_angka.setText(nilaiSaved); } Calendar calendar = Calendar.getInstance(); final int year = calendar.get(Calendar.YEAR); final int month = calendar.get(Calendar.MONTH); final int day = calendar.get(Calendar.DAY_OF_MONTH); tv_tanggal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DatePickerDialog datePickerDialog = new DatePickerDialog( PemesananActivity.this,R.style.Theme_AppCompat_DayNight_Dialog_MinWidth, setListener, year, month, day); datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); datePickerDialog.show(); } }); setListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { month = month + 1; String date = day + "/" + month + "/" + year; tv_tanggal.setText(date); } }; et_tanggal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DatePickerDialog datePickerDialog = new DatePickerDialog( PemesananActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int day) { month = month + 1; String date = day + "/" + month + "/" + year; et_tanggal.setText(date); } }, year, month, day); datePickerDialog.show(); } }); plus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { valuejumlah += 1; tv_angka.setText(valuejumlah.toString()); int tot =Integer.parseInt(tv_angka.getText().toString()); int hrd = Integer.parseInt(hrg.getText().toString()); int total = tot*hrd; et_total.setText(String.valueOf(total)); } }); min.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (valuejumlah > 1){ valuejumlah -= 1; tv_angka.setText(valuejumlah.toString()); int tot =Integer.parseInt(tv_angka.getText().toString()); int hrd = Integer.parseInt(hrg.getText().toString()); int total = tot*hrd; et_total.setText(String.valueOf(total)); } } }); simpan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String vNama = et_nama.getText().toString(); String vNohp = et_wa.getText().toString(); String vAlamat = et_alamat.getText().toString(); String Spbox = String.valueOf(pilihan.getSelectedItem()); String vTanggal = et_tanggal.getText().toString(); String vCard = et_card.getText().toString(); String pilpkt = " "; if (rose.isChecked()){ pilpkt+= "Rose Style"; } if (peony.isChecked()){ pilpkt+= "Peony Style"; } if (wisuda.isChecked()){ pilpkt+= "Wisuda Style"; } String vStyle = tv_angka.getText().toString(); String vTotal = et_total.getText().toString(); if (vNama.isEmpty()) { et_nama.setError("Nama tidak boleh kosong"); et_nama.requestFocus(); return; } if (vNama.length() < 3) { et_nama.setError("Nama harus lebih dari 2 karakter"); return; } if (vNohp.isEmpty()) { et_wa.setError("Nomor telpon tidak boleh kosong"); et_wa.requestFocus(); return; } if (vNohp.length() < 12) { et_wa.setError("Masukan nomor telepon yang valid"); return; } if (vAlamat.isEmpty()) { et_alamat.setError("Alamat tidak boleh kosong"); et_alamat.requestFocus(); return; } Intent box = new Intent(PemesananActivity.this, ValuePesanActivity.class); box.putExtra("extraNama", vNama); box.putExtra("extraNohp", vNohp); box.putExtra("extraAlamat", vAlamat); box.putExtra("extraSpbox", Spbox); box.putExtra("extraTanggal", vTanggal); box.putExtra("extraCard", vCard); box.putExtra("extraStyle", vStyle); box.putExtra("extraTotal", vTotal); startActivity(box); } }); } public void onRadioButtonClicked(View view) { // Is the button now checked? boolean checked = ((RadioButton) view).isChecked(); // Check which radio button was clicked. switch (view.getId()) { case R.id.rose: if (checked) // Same day service et_total.setText(String.valueOf(harga[0])); hrg.setText(String.valueOf(harga[0])); displayToast(getString(R.string.rose)); break; case R.id.peony: if (checked) // Next day delivery et_total.setText(String.valueOf(harga[2])); hrg.setText(String.valueOf(harga[2])); displayToast(getString(R.string.peony)); break; case R.id.wisuda: if (checked) // Next day delivery et_total.setText(String.valueOf(harga[1])); hrg.setText(String.valueOf(harga[1])); displayToast(getString(R.string.wisuda)); break; default: // Do nothing. break; } } private void displayToast(String message) { Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); } }
true
e094a8ef7f9e10838d20f0013e0a345b38de1b27
Java
clfbai/heoll
/user-center/src/main/java/com/boyu/erp/platform/usercenter/service/system/SpecService.java
UTF-8
1,548
1.929688
2
[]
no_license
package com.boyu.erp.platform.usercenter.service.system; import com.boyu.erp.platform.usercenter.entity.Spec; import com.boyu.erp.platform.usercenter.exception.ServiceException; import com.boyu.erp.platform.usercenter.vo.goods.ProductVo; import com.github.pagehelper.PageInfo; import java.util.List; import java.util.Set; /** * 规格 */ public interface SpecService { public PageInfo<Spec> selectAll(Integer pageNum, Integer pageSize, Spec spec) throws ServiceException; /** * 根据规格组ID获取规格列表 * * @param specGrpId * @return * @throws ServiceException */ public List<Spec> getListSpecBySpecGrpId(String specGrpId) throws ServiceException; /** * 获取下拉框选择规格 * * @param spec * @return * @throws ServiceException */ public List<Spec> getOptionsList(Spec spec) throws ServiceException; public Spec getSpecById(Spec spec) throws ServiceException; public int insertSpec(Spec spec) throws ServiceException; public int updateSpec(Spec spec) throws ServiceException; public int deleteSpec(Spec spec) throws ServiceException; List<Spec> getAll(); /** * 功能描述: 批量查询规格 * * @param: * @return: * @auther: CLF * @date: 2019/8/15 20:19 */ List<Spec> getSpecList(List<ProductVo> list); /** * 根据规格Id集合查询规格集合 * @author HHe * @date 2019/10/7 17:21 */ List<Spec> querySpecListByIds(Set<Long> specIds); }
true
65934abbcc9b7228177be81ba0071a1c79d07cfc
Java
MatthieuDJ/api_training
/src/main/java/fr/esiea/ex4A/FakeTinder/Sexes.java
UTF-8
77
1.875
2
[]
no_license
package fr.esiea.ex4A.FakeTinder; public enum Sexes { M, F, O }
true
b4d819e65d843d8e1be7ae127eeefe303a8c5a80
Java
lehmansarahm/PrivacyManager
/EnvironmentalAccessControl/eac/src/main/java/edu/temple/eac/utils/DialogManager.java
UTF-8
1,477
2.453125
2
[]
no_license
package edu.temple.eac.utils; import android.app.Activity; import android.app.ProgressDialog; /** * */ public class DialogManager { private static ProgressDialog dialog; /** * * @param title * @param message */ public static void show(final Activity currentActivity, final String title, final String message) { currentActivity.runOnUiThread(new Runnable() { @Override public void run() { dialog = new ProgressDialog(currentActivity); dialog.setTitle(title); dialog.setMessage(message); dialog.setCancelable(false); // disable dismiss by tapping outside of the dialog dialog.show(); } }); } /** * * @param currentActivity */ public static void hide(final Activity currentActivity) { currentActivity.runOnUiThread(new Runnable() { @Override public void run() { dialog.hide(); } }); } /** * * @param currentActivity * @param message */ public static void hide(final Activity currentActivity, final String message) { currentActivity.runOnUiThread(new Runnable() { @Override public void run() { if (dialog != null) dialog.hide(); ToastManager.showShortToast(currentActivity, message); } }); } }
true
e0ae4911dfccf2a301c67e4db9b575c5bc87efcc
Java
blue-for-dragon/LearningProject
/spring-boot-learn/src/main/java/com/lyl/service/EmployeeService.java
UTF-8
2,584
3.109375
3
[]
no_license
package com.lyl.service; import com.lyl.Bean.Employee; import com.lyl.mapper.EmployeeMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.*; import org.springframework.stereotype.Service; //可以再类上指定cache的全局规则 @CacheConfig(cacheNames = "emp") @Service public class EmployeeService { @Autowired EmployeeMapper employeeMapper; /** * 开启缓存 * * CacheManager管理多个Cache组件 对缓存的真正CRUD操作在Cache组件中 每一个缓存组件有自己唯一一个名字 * 属性: * cacheName/value:指定缓存组件的名字 * key:缓存数据使用的key;默认使用方法参数的值 * keyGenerator 二选一 * CacheManager指定缓存管理器 * cacheRosovler二选一 * condition指定条件 * unless否定 本来缓存 除非满足条件就不满足了 可以用结果作为条件 unless="#result==null" * sync 异步 * @param id * @return */ @Cacheable(cacheNames = {"emp"},key="#id",condition = "#id>0") public Employee get(Integer id) { System.out.println("查询"+id+"号员工"); Employee emp=employeeMapper.gettt(id); return emp; } /** * @CachePut 既调用方法,又更新缓存数据 * 修改了数据 同时更新缓存 * * 因为上面的key是1 下面不写key默认是employee对象 所以更新后查询对象仍然是更新前的缓存 * 也可以result.id but Cacheable不能用 */ @CachePut(value = "emp",key = "#employee.id") public Employee updateEmp(Employee employee){ employeeMapper.update(employee); return employee; } /** * @CacheEvict 缓存清除 * allEntries=true 删除emp里的所有key value * beforeInvocation=false 缓存的清除是否在方法执行之前执行 * 默认是在方法执行之后进行的 */ @CacheEvict(value = "emp",key = "#id") public void delete(Integer id){ System.out.println("delete员工"); employeeMapper.delete(id); } /** * @Caching 定义复杂规则 * */ @Caching( cacheable = { @Cacheable(value = "emp",key = "#lastName") }, put = { @CachePut(value = "emp",key = "#result.id"), @CachePut(value = "emo",key = "#result.email") } ) public Employee get(String lastName){ return new Employee(); } }
true
425669b6187fe4fe399caf3765b8b21d4b98fcb6
Java
fill24/ERP
/test/java/tests/silktoselenium/SchedulerCalendarRecurrenceTest3883.java
UTF-8
4,559
2.03125
2
[]
no_license
package tests.silktoselenium; import data.InputControls; import data.JobStatus; import framework.data.PropertiesReader; import framework.reporter.TestLog; import helpers.FindIn; import helpers.LoginAndNavigationHelper; import helpers.scheduler.RecurrenceCalendarModel; import helpers.scheduler.ScheduledJobCreator; import helpers.scheduler.StartJobModel; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import tests.BaseTests; import ui.dialogs.propertiesdialogs.JobPropertiesDialog; import ui.elements.contentitems.jobs.CompletedJobItem; import ui.objects.manageusers.UserPropertiesObject; import ui.objects.manageusers.UsersListObject; import ui.pages.MainNavigationPage; import utils.WaitUtils; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static utils.WaitUtils.sleep; /** * Created by p524380 on 2/2/2015. */ public class SchedulerCalendarRecurrenceTest3883 extends BaseTests{ private final String FUND = "TEMOFF"; private final String REPORT_ID = "GHOX0001"; private final String REPORT_PATH = "Reporting -> Reports -> Holdings"; private final String JOB_NAME = "RPTDE3883_SchedulerCalendarRecurrence"; private final String GROUP_NAME = "OPEN JOBS"; private final String USER_NAME = "IMSdeschedul"; @BeforeClass public void setUp(){ new LoginAndNavigationHelper().loginAs(PropertiesReader.getInstance().getAdminUser()); new MainNavigationPage().getNavigationMenu().clickManageButton().clickUsers(); WaitUtils.waitForLoadingDisappear(); UsersListObject usersListObject = new UsersListObject();//.getUserConfiguration(USER_NAME).click(); usersListObject.filter(USER_NAME); usersListObject.getUserConfiguration(USER_NAME).click(); WaitUtils.waitForLoadingDisappear(); new UserPropertiesObject().clickLoginAsUserButton(); WaitUtils.waitForLoadingDisappear(); } @AfterClass public void tearDown(){ List<CompletedJobItem> jobItems = new FindIn.CompletedJobs(). jobNameContains(JOB_NAME). waitFor(). getList(); for(CompletedJobItem jobItem: jobItems){ jobItem.getContextMenu().clickDelete().accept(); } } @Test public void testSchedulerCalendarRecurrence(){ TestLog.fullTestName("Verify that IMSdeschedul can add job to the scheduler with calendar recurrence"); TestLog.preconditions("IMSdeschedul user is logged in."); TestLog.expectedResult("The job should be processed at defined date and time"); new MainNavigationPage().clickViewRepositoryButton(); final LinkedHashMap<String, String> fundTab = new LinkedHashMap<>(); fundTab.put(InputControls.STAR_FUND, FUND); DateTime startDateTime = new DateTime().plusMinutes(20); new ScheduledJobCreator.Builder( REPORT_PATH, REPORT_ID, JOB_NAME). startJobModel(new StartJobModel.Builder().setImmediately().build()). recurrenceCalendarModel(new RecurrenceCalendarModel.Builder(). setHours(startDateTime.hourOfDay().getAsText()). setMinutes(startDateTime.minuteOfHour().getAsText()). setRecurUntil(startDateTime.toString("MM/dd/yyyy hh:mm:ss")). build()). jobGroup(GROUP_NAME). parameters(new LinkedHashMap<String, LinkedHashMap<String, String>>() {{ put(InputControls.REPORT_PARAMETERS_FUND_TAB, fundTab); }}).build().schedule(true); while (new DateTime().isBefore(startDateTime)) { sleep(10); } JobPropertiesDialog jobPropertiesDialog=new FindIn.CompletedJobs(). jobNameContains(JOB_NAME). statusEquals(JobStatus.SUCCESS). waitFor(). get().getContextMenu().clickProperties(); Map<String, Map<String, String>> values = jobPropertiesDialog.getSummaryTabValues(); jobPropertiesDialog.clickOkButton(); Assert.assertTrue(values.get("Job").get("Quartz Instance Id").matches("svanyc\\w+_GroupScheduler_TG_OPEN"), "Invalid Quartz Instance Id"); Assert.assertEquals(new FindIn.ScheduledJobs().jobNameContains(JOB_NAME).getList().size(), 0, "Calendar Recurrence job still in scheduled jobs after completed"); } }
true
6523b4f92a26ae26b8283f6c5314f0a59a88a478
Java
rafadelnero/alura
/alura/design-patterns/design-patterns-ii/src/memento/Programa.java
UTF-8
610
2.640625
3
[]
no_license
package memento; import java.util.Date; public class Programa { public static void main(String[] args) { HistoricoContrato historicoContrato = new HistoricoContrato(); Contrato contrato = new Contrato(new Date(), "Josefo", Tipo.NOVO); historicoContrato.adiciona(contrato.salvaEstado()); contrato.avanca(); historicoContrato.adiciona(contrato.salvaEstado()); contrato.avanca(); historicoContrato.adiciona(contrato.salvaEstado()); contrato.avanca(); historicoContrato.adiciona(contrato.salvaEstado()); System.out.println(historicoContrato.pega(3).getContrato()); } }
true
bbb5fdab7d0476a0d719b4c4b15fac799d1d2507
Java
baiymfkese/jedis
/src/main/java/com/dawning/gridview/app/gridview/webapp/jedis/cxf/client/WebServiceClient.java
UTF-8
1,598
2.296875
2
[]
no_license
package com.dawning.gridview.app.gridview.webapp.jedis.cxf.client; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.frontend.ClientProxyFactoryBean; import org.apache.cxf.transport.http.HTTPConduit; import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; /** * web service客户端 * @author ming * */ public class WebServiceClient { /** * * @param webServiceurl "http://10.0.31.78:9091/teacherManage" * @param clazz * @return */ public static <T> T getWebService(String webServiceurl,Class<T> clazz){ T t=null; try { ClientProxyFactoryBean proxyFactory=new ClientProxyFactoryBean(); proxyFactory.setServiceClass(clazz); proxyFactory.setAddress(webServiceurl); // proxyFactory.getServiceFactory().setDataBinding(new AegisDatabinding());// 对数据进行绑定 Object service=proxyFactory.create(); Client client=ClientProxy.getClient(service); HTTPConduit conduit=(HTTPConduit)client.getConduit(); HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); long strReceiveTimeout = 40*60*1000; long strConnTimeout = 20*60*1000; httpClientPolicy.setReceiveTimeout(strReceiveTimeout);// 等待服务器响应时间40分钟 httpClientPolicy.setAllowChunking(false); httpClientPolicy.setConnectionTimeout(strConnTimeout);// 连接服务器超时时间20分钟 conduit.setClient(httpClientPolicy); if(null != service){ t=clazz.cast(service); } } catch (Exception e) { e.printStackTrace(); } return t; } }
true
ad7dc507b98de4c2093352bee4103380220a237d
Java
MicaVsr/taller-web
/src/main/java/ar/edu/unlam/tallerweb1/modelo/Puntaje.java
UTF-8
1,592
2.328125
2
[]
no_license
package ar.edu.unlam.tallerweb1.modelo; import javax.persistence.*; import java.util.Date; @Entity public class Puntaje { public Puntaje(){} public Puntaje(Publicacion publicacion, Integer valor, String comentario, Usuario usuario){ this.setFecha(new Date()); this.setPublicacion(publicacion); this.setValor(valor); this.setComentario(comentario); this.setUsuario(usuario); } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne() private Publicacion publicacion; @ManyToOne() private Usuario usuario; private Integer valor; private Date fecha; public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public String getComentario() { return comentario; } public void setComentario(String comentario) { this.comentario = comentario; } private String comentario; public Long getId() { return id; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public void setId(Long id) { this.id = id; } public Publicacion getPublicacion() { return publicacion; } public void setPublicacion(Publicacion publicacion) { this.publicacion = publicacion; } public Integer getValor() { return valor; } public void setValor(Integer puntaje) { this.valor = puntaje; } }
true
368ddc33c0864047e3edfbd33017d8b1986ec250
Java
luwang951753/Spring
/spring01_IOC&&DI/src/test/java/com/feng/spring/IOCTest4.java
UTF-8
924
2.578125
3
[]
no_license
package com.feng.spring; import com.feng.spring2.Service.BookService; import com.feng.spring2.Servlet.BookServlet; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class IOCTest4 { private ApplicationContext ioc = new ClassPathXmlApplicationContext("ioc5.xml"); @Test public void test2(){ // BookServlet bookServlet = ioc.getBean(BookServlet.class); // bookServlet.doGet(); } /** * 使用注解加入到容器中的组件,和使用配置加入到容器中的组件行为都是默认一样的: * 1、id默认为类名首字母小写 * 2、组件默认为单例 */ @Test public void test(){ Object bookDao = ioc.getBean("bookDao"); Object bookDao2 = ioc.getBean("bookDao"); System.out.println(bookDao==bookDao2); } }
true
0194ea5b2d511f7146c88de553279367ca177c2c
Java
gibalo/fuenflix-api
/src/main/java/es/cesfuencarral/fuenflixapi/persistence/entity/Content.java
UTF-8
3,330
2.390625
2
[]
no_license
package es.cesfuencarral.fuenflixapi.persistence.entity; import javax.persistence.*; import es.cesfuencarral.fuenflixapi.controller.request.ContentRequest; import java.io.Serializable; import java.util.Set; @Entity @Table(name = "content") @NamedQueries({ @NamedQuery(name = "Content.findByFilter", query = "SELECT c FROM Content c WHERE c.contentType = :contentType") //,@NamedQuery(name = "Content.findByUserContent", query = "SELECT c FROM Content c JOIN User u ON c.user.id = :user WHERE c.id IN (SELECT u.contents FROM User u WHERE u.user = :user)") ,@NamedQuery(name = "Content.findByContentType",query = "SELECT c FROM Content c WHERE c.contentType.id = :contentType") ,@NamedQuery(name = "Content.findByIdList",query = "SELECT c FROM Content c WHERE c.id IN :idList") }) public class Content implements Serializable { /* Fields */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; private String description; private double price; private String path; @Column(name = "image_path") private String imagePath; @JoinColumn(name = "content_type", referencedColumnName = "id") @ManyToOne private ContentType contentType; @ManyToMany(mappedBy = "contents") private Set<User> users; /* Constructors */ public Content() { } /* Getters & setters */ public Content(ContentType contentType, ContentRequest request) { this.contentType = contentType; this.name = request.getName(); this.description = request.getDescription(); //this.price = request.getPrice(); this.path = request.getPath(); this.imagePath = request.getImagePath(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public ContentType getContentType() { return contentType; } public void setContentType(ContentType contentType) { this.contentType = contentType; } public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } /* others */ @Override public boolean equals(Object object) { return (object instanceof Content) && this.id == ((Content) object).getId(); } @Override public String toString() { return " id=" + id + " ]"; } public void update(ContentType contentType, ContentRequest request) { this.contentType = contentType; this.name = request.getName(); this.description = request.getDescription(); //this.price = request.getPrice(); this.path = request.getPath(); this.imagePath = request.getImagePath(); } }
true
437bb623756013f0e899de8b3451b90585c31bf1
Java
lxqxsyu/SheJiMoShi
/src/观察者模式/ObserverClass1.java
GB18030
238
3.125
3
[]
no_license
package ۲ģʽ; public class ObserverClass1 implements SuperObsever{ @Override public void update(Object data) { String str = (String) data; System.out.println("ǹ۲1֪ͨҵ: " + str); } }
true
255b7663e3c232e41997670aadd37287f636f0d1
Java
JungDayoon/DBproject_team6
/resourcesharing/src/main/java/com/dbteam6/resourcesharing/controller/MainController.java
UTF-8
723
1.875
2
[]
no_license
package com.dbteam6.resourcesharing.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MainController { @GetMapping("/") public String Index() { return "index"; } @GetMapping("/main_page") public String mainPage() { return "main_page"; } @GetMapping("/signup") public String signup(){ return "signup"; } @GetMapping("/mypage") public String mypage() { return "mypage"; } @GetMapping("/modify_page") public String modify_page() { return "modify_page"; } }
true
b8a0f78f6d2c27f499d7e9a11ca664991ea4c9b8
Java
AndrewBaliushin/Learning-Java
/src/eckel/interfaces/FactoryMethodExercise.java
UTF-8
1,472
3.921875
4
[]
no_license
/* * /interfaces/exercise 13 * from Eckel. * * Create a framework using Factory Methods that performs both coin tossing and dice tossing. * * 19.10.14 * * By Andrew Baliushin */ import java.util.Random; interface Tosser { String getTossResult(); } interface TosserFactory { Tosser getTosser(); } class Coin implements Tosser { @Override public String getTossResult() { return (Math.random() <= 0.5d) ? "Heads" : "Tails"; } } class Dice implements Tosser { @Override public String getTossResult() { Random rand = new Random(); return "Dice showed " + (rand.nextInt(6) + 1); //note: nextInt(n) -- n exclusive. } } class CoinFactory implements TosserFactory { @Override public Tosser getTosser() { return new Coin(); } } class DiceFactory implements TosserFactory { @Override public Tosser getTosser() { return new Dice(); } } public class FactoryMethodExercise { public static void main(String[] args) { Random rand = new Random(); TosserFactory[] tosserFactoriesArray = {new CoinFactory(), new DiceFactory()}; for (int i=1; i<20; i++) { TosserFactory randTosserFactory = tosserFactoriesArray[rand.nextInt(2)]; Tosser randTosser = randTosserFactory.getTosser(); System.out.println(randTosser.getTossResult()); } } } /* Output example: Heads Dice showed 1 Tails Dice showed 4 Dice showed 6 */
true
aed3e859e8a4ab45e1be317e69c182af45a0a7a7
Java
avertocle/mediacenter
/src/main/java/mc/gui/library/TableCollection.java
UTF-8
1,511
2.4375
2
[]
no_license
package mc.gui.library; import java.awt.Component; import java.awt.Dimension; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.TableCellRenderer; import mc.gui.ColorConsts; public class TableCollection extends JTable { private static final long serialVersionUID = 1L; TableModelCollection tmodel; public TableCollection(TableModelCollection tmodel) { super(tmodel); this.tmodel = tmodel; setTableProperties(); } private void setTableProperties() { this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); this.setRowSelectionAllowed(true); this.setFillsViewportHeight(true); this.setShowGrid(false); this.setRowHeight(40); this.setIntercellSpacing(new Dimension(5, 10)); this.setBackground(ColorConsts.Table_Collections.clrBg); this.setForeground(ColorConsts.Table_Collections.clrFg); this.setFont(ColorConsts.Table_Collections.font); fixColumnWidth(TableModelCollection.colNumCollection, 330); fixColumnWidth(TableModelCollection.colNumUse, 35); } private void fixColumnWidth(int colNo, int width) { this.getColumnModel().getColumn(colNo).setMaxWidth(width); this.getColumnModel().getColumn(colNo).setPreferredWidth(width); } public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); c.setForeground(ColorConsts.Table_Collections.clrCellFg); c.setBackground(ColorConsts.Table_Collections.clrCellBg); return c; } }
true
6f667b31fbff9ea6cdfbd493ffb347b4dbbde147
Java
fajarnugraha37/aem-demo-machine
/java/core/src/main/java/com/adobe/aem/demomachine/gui/AemDemoConstants.java
UTF-8
4,320
1.84375
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2016 Adobe Systems Incorporated. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.adobe.aem.demomachine.gui; public class AemDemoConstants { public static final String OPTIONS_STORES = "demo.store.options"; public static final String OPTIONS_SRPS = "demo.srp.options"; public static final String OPTIONS_TOPOLOGIES = "demo.type.options"; public static final String OPTIONS_STORES_DEFAULT = "demo.store"; public static final String OPTIONS_SRPS_DEFAULT = "demo.srp"; public static final String OPTIONS_TOPOLOGIES_DEFAULT = "demo.type"; public static final String OPTIONS_JAR_DEFAULT = "demo.jar"; public static final String OPTIONS_BUILD_DEFAULT = "demo.build"; public static final String OPTIONS_DOWNLOAD = "demo.download"; public static final String OPTIONS_WEBDOWNLOAD = "demo.download.demomachine.all"; public static final String OPTIONS_DEMODOWNLOAD = "demo.download.demomachine"; public static final String OPTIONS_DOCUMENTATION = "demo.documentation"; public static final String OPTIONS_SCRIPTS = "demo.scripts"; public static final String[] INSTANCE_ACTIONS = new String[] {"start","restore","backup","uninstall", "details"}; public static final String[] CLEANUP_ACTIONS = new String[] {"uninstall"}; public static final String[] STOP_ACTIONS = new String[] {"uninstall","stop"}; public static final String[] BUILD_ACTIONS = new String[] {"demo", "create"}; public static final String BUILD_ACTION = "create"; public static final String ADOBEDEMOSERVER = "aem-communities-demo.corp.adobe.com"; public static final String ADOBEVPN = "adobevpn"; public static final String PASSWORD = "******"; public static final String HR = "-------------------------------"; public static final String Credits = "Welcome to the AEM Demo Machine! Everyone knows there isn't any good demo without a bouncing scrolltext... The AEM Demo Machine is an OpenSource project. You are welcome to contribute as did the people listed later. Don't forget to \"git pull\" the latest changes often. Also make sure to check the latest updates to the Wiki documentation at https://github.com/Adobe-Marketing-Cloud/aem-demo-machine/wiki . Many thanks to the following people for contributing, one way or the other, to the AEM Demo Machine: Gerd Handke, Cedric Huesler, Greg Klebus, Gabriel Walt, Mathias Siegel, Martin Buergi, Scott Date, Randah McKinnie, Don Walling, Abhinav Chakravarty, Nikhil Vasudeva, Chris Gatihi, Michael Marth, Mark Szulc, Kyle Chau, Marcel Boucher, Michael Point, Brandon Tan, Raul Ugarte, Christophe Loffler, Samuel Blin, Sethu Iyer, Mark Frazer. Designed and built with all the love in the world by @bdecoatpont. Copyright - well, there's actually no copyright. Let's wrap and happy AEM demoing!"; public static final String[][] demoPaths = new String[][]{ { "0", "", "AEM Demo Machine", "false", "packages"}, { "1", "dist/apps", "AEM Apps Demo Add-ons", "true", "apps" }, { "2", "dist/apps-packages", "AEM Apps Packages", "true", "apps" }, { "3", "dist/assets", "AEM Assets Demo Add-ons", "true", "assets" }, { "4", "dist/assets-packages", "AEM Assets Packages", "true", "assets" }, { "5", "dist/community/featurepacks", "AEM Communities Packages", "true", "communities" }, { "6", "dist/sites", "AEM Sites Demo Add-ons", "true", "sites" }, { "7", "dist/sites-packages", "AEM Sites Packages", "true", "sites" }, { "8", "dist/forms", "AEM Forms Demo Add-ons", "true", "forms" }, { "9", "dist/forms-packages", "AEM Forms Packages", "true", "forms" }, { "10", "dist/hotfixes", "AEM Hotfixes", "true", "hotfixes" }, { "11", "dist/we-retail", "AEM We-Retail", "true", "weretail" }, { "12", "dist/livefyre", "AEM Livefyre", "true", "livefyre" }, { "13", "dist/commerce", "AEM Commerce", "false", "commerce" }, }; }
true