blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
e4200d933599764884647691adf663c80cde4df7
32ca45d52da1680b29c24b109a58751a538716a1
/src/test/java/com/gaggle/step_definitions/DockerImageStep.java
58b997d5967f37881bd777cd1f1552088297df39
[]
no_license
ybark/DockerRestAPI
414b08f9bdaab3342c30d4238996acab783e4dbb
ff28d0a400e6a2f382beb621faa1efcc2e8d38e2
refs/heads/main
2023-03-28T06:09:55.453963
2021-04-01T03:39:38
2021-04-01T03:39:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,725
java
package com.gaggle.step_definitions; import com.gaggle.base.BaseDockerImage; import com.gaggle.utillities.ConfigurationReader; import io.cucumber.java.BeforeStep; import io.cucumber.java.en.And; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.restassured.RestAssured; import io.restassured.builder.RequestSpecBuilder; import io.restassured.filter.log.LogDetail; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import org.junit.Assert; import org.junit.Test; import org.junit.jupiter.api.BeforeAll; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.is; public class DockerImageStep { private Response response; private JsonPath jsonPath; public static RequestSpecification requestSpec; @BeforeStep public static void init() { RestAssured.baseURI = ConfigurationReader.getProperty("dockerBaseURI"); RestAssured.basePath = ConfigurationReader.getProperty("dockerBasePath"); } @Given("Users Performs Get operation") public void users_performs_get_operation() { requestSpec = new RequestSpecBuilder().log(LogDetail.ALL).build(); response = given(). spec(requestSpec).log().all(). when().get("").prettyPeek(); } @Then("User should see the success status as {int}") public void userShouldSeeTheSuccessStatusAs(int statusCode) { Assert.assertEquals(response.statusCode(),statusCode); } @And("Payload has {string}") public void payload_has(String value) { Assert.assertTrue(response.body().prettyPrint().contains(value)); } }
ece24a8d0fc5304c05e31be87e9b12d32a727cad
8fb2778fbbc0e58e80d886fff7bd9fd6ff48c8d5
/medium/17.letter-combinations-of-a-phone-number.java
14031115b90148155f0178e56c724d57bf984c65
[]
no_license
SidTheEngineer/LeetCode
f9aae4be8abd3e8b338550d1565f7e29cbd8999c
a9064dbccad192be31b977070cd1fe7776717f36
refs/heads/master
2021-01-16T00:46:18.663247
2017-10-22T23:11:46
2017-10-22T23:11:46
99,978,194
0
0
null
null
null
null
UTF-8
Java
false
false
1,333
java
public class Solution { public List<String> letterCombinations(String digits) { if (digits.length() == 0) return new ArrayList<String>(); LinkedList<String> solution = new LinkedList<>(); // Start off with an empty string in our solutions so we have something to remove // and add to. solution.add(""); // Here's the trick. The indeces of mapping correspond to the digits on the phone, their // values being the corresponding letters that can come from the digit. String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; for (int i = 0; i < digits.length(); i++) { int convertedInt = Character.getNumericValue(digits.charAt(i)); // Go through the whole queue, adding every possible char for the next digit (i). // When the new head is longer than i, we know we're done with the previous combinations. // The length of the combination will be at most the length of the digit. while (solution.peek().length() == i) { String previousCombo = solution.remove(); for (char c : mapping[convertedInt].toCharArray()) solution.add(previousCombo + c); } } return solution; } }
6fbfb2e9513f5ff4a7900f61733bb58d2b04d505
9fd2044c6fb9036a70a4f10aa0de96d113ecdb2d
/FunfTestApp/src/edu/mit/media/funf/testapp/MyActivity.java
d54e55ed1463a0602899165a584fe66a363d387a
[]
no_license
apps8os/Funf
8ea9dd8ff709626e21a1cd1d7b96e2fb759e389d
8764e27e6245dfdf2a6a310646fe2d512a899f50
refs/heads/master
2020-12-14T07:20:15.902484
2015-03-25T07:53:47
2015-03-25T07:53:47
18,488,581
0
0
null
2015-03-19T14:58:26
2014-04-06T11:55:35
Java
UTF-8
Java
false
false
361
java
package edu.mit.media.funf.testapp; import android.app.Activity; import android.os.Bundle; public class MyActivity extends Activity { /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
227592b43edd34869f8f38f9a117a26bff2cb8c4
5913904e7b345287faeafaa60f51ea6cf6819721
/AspectjProj-9-DistributedTxMgmt/src/main/java/com/pg/service/AccountService.java
2d503618b3beaffbf8e5a692a5e0e1874fa53c96
[]
no_license
preetamgagan/Assignments
890618934ddad9e15b98c5d3b1eb6521b84f6b39
5821998360ebb33649dbc4ffb4df223851036329
refs/heads/master
2020-04-23T20:46:30.070476
2019-03-07T16:58:12
2019-03-07T16:58:12
171,450,826
0
1
null
null
null
null
UTF-8
Java
false
false
689
java
package com.pg.service; import com.pg.dao.DepositeDAO; import com.pg.dao.WithdrawDAO; public class AccountService { private WithdrawDAO withdrawDAO; private DepositeDAO depositeDAO; public void setWithdrawDAO(WithdrawDAO withdrawDAO) { this.withdrawDAO = withdrawDAO; } public void setDepositeDAO(DepositeDAO depositeDAO) { this.depositeDAO = depositeDAO; } public boolean TransferMoney(int srcAcc,int destAcc,int amt) { int result1=withdrawDAO.withdraw(srcAcc, amt); int result2=depositeDAO.deposite(destAcc, amt); if(result1==0 || result2==0) { throw new RuntimeException("Transaction Failed(Tx Rollback"); } return true; } }
1905f3bff6281f3a1c1a4ae453d163b4649acd3c
0e7dfad16f857bfc65e9d107095a90845d5572ad
/Sem 4/Computer Graphics and Gaming/Ass6/_Ass6.java
da5f7d86d210c485f8501e58d964e93c23d66649
[]
no_license
shrirangmhalgi/College-Codes
c11648b0f60e6f79ea4432ce74c9ea8b6c9ccf8a
07f9f8237030d1643dd83ba84feff7632f5d95c3
refs/heads/master
2021-07-16T18:46:03.307819
2020-06-04T05:22:09
2020-06-04T05:22:09
218,691,387
0
0
null
2020-10-13T17:07:23
2019-10-31T05:32:47
C++
UTF-8
Java
false
false
5,929
java
package cgg; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; import javax.swing.JFrame; public class Assignment6Scanline extends JFrame implements MouseListener { static boolean intial=true; static boolean choice=false; int noOfVertices,count; ArrayList<Edge> edgeTable; // to store edges ArrayList<Edge> activeEdges; ArrayList<Integer> xcord=new ArrayList<Integer>(); int previousX,previousY,startX,startY; public Assignment6Scanline() { this.noOfVertices=0; this.count=0; this.previousX=0; this.previousY=0; this.startX=0; this.startY=0; edgeTable=new ArrayList<Edge>(); activeEdges=new ArrayList<Edge>(); } public static void main(String args[]) { Assignment6Scanline sc=new Assignment6Scanline(); sc.setSize(1500,1500); sc.setVisible(true); sc.setDefaultCloseOperation(EXIT_ON_CLOSE); sc.getEdges(); //sc.draw(); } public void printEdgeTable() { for(Edge edge:edgeTable) { System.out.println(" Edge No: "+edge.edgeNo); System.out.println(" X1: "+edge.x1); System.out.println(" Y1: "+edge.y1); System.out.println(" X2: "+edge.x2); System.out.println(" Y2: "+edge.y2); System.out.println(" Slope: "+edge.slope); } } public int[] minNMax() { int arr[]= {edgeTable.get(0).y1,edgeTable.get(0).y1,edgeTable.get(0).x1,edgeTable.get(0).x1}; // ymin,ymax,xmix,xmax for(Edge temp:edgeTable) { if(arr[0]>temp.y1)//y min arr[0]=temp.y1; if(arr[1]<temp.y1)//y max arr[1]=temp.y1; if(arr[2]>temp.x1)//x min arr[2]=temp.x1; if(arr[3]<temp.x1)//y max arr[3]=temp.x1; } return arr; } public boolean checkEdgeActivity(Edge temp,int curY) // check if current value of y lies on the edge { boolean flag=false; if ((temp.y1<curY && curY<=temp.y2 )||(temp.y1>=curY && curY>temp.y2)) flag=true; return flag; } public void getActiveEdges(int curY) // needs bit of changes { for(Edge edge : edgeTable) { if(checkEdgeActivity(edge, curY) && !activeEdges.contains(edge))// add edge if not present and is active activeEdges.add(edge); else if(activeEdges.contains(edge)) activeEdges.remove(edge); } } public void scanline() { Graphics g=getGraphics(); printEdgeTable(); int minMax[]=minNMax(); int yMin=minMax[0],yMax=minMax[1],tempX=0; System.out.println("Y min :"+yMin+" yMAx: "+yMax); for(int i=yMin;i<=yMax;i++) { g.setColor(Color.GREEN); if(i%3==0) g.setColor(Color.blue); else if(i%2==0) g.setColor(Color.red); activeEdges.clear(); getActiveEdges(i);// check active edges for current y xcord.clear();// find xcords and store in list for(Edge edge : activeEdges) { tempX=(((i-edge.y1)*(edge.dx))/edge.dy)+edge.x1; // Finding intersection . Now add to list of xcordinates xcord.add(tempX); } xcord.sort(new Comparator<Integer>() { public int compare(Integer x1,Integer x2) { int a=0; if(x1>x2) a=1; else if(x1==x2) a=0; else a=-1; return a; } }); // now after sorting the points draw line for(int j=0;j<xcord.size();j+=2) { int x1 = xcord.get(j); if (j+1>=xcord.size()) break; int x2 =xcord.get(j+1); try { Thread.sleep(50); g.drawLine(x1, i, x2, i); } catch (Exception e) { System.out.println(e.toString()); } } } } public void draw() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); try { System.out.println("Enter True to scan line fill"); Assignment6Scanline.choice=Boolean.parseBoolean(br.readLine()); } catch (Exception e) { System.out.println(e.toString()); } Assignment6Scanline.intial=false; } // for mouse events @Override public void mouseReleased(MouseEvent m) {} @Override public void mousePressed(MouseEvent m) {} @Override public void mouseExited(MouseEvent m) {} @Override public void mouseEntered(MouseEvent m) {} @Override public void mouseClicked(MouseEvent m) { // add edges to edges table Graphics g=getGraphics(); g.setColor(Color.BLUE); int x,y; x=m.getXOnScreen(); y=m.getYOnScreen(); System.out.println("count "+count); if(count==0) { previousX=x; previousY=y; startX=x; startY=y; count++; } else { if(count<noOfVertices) { Edge temp=new Edge(count,previousX,previousY,x,y); // x1,y1,x2,y2 edgeTable.add(temp); g.drawLine(temp.x1, temp.y1, temp.x2, temp.y2); previousX=x; previousY=y; } if(count==(noOfVertices-1)) { System.out.println("For last edge"); Edge temp=new Edge(count+1,x,y,startX,startY); // x1,y1,x2,y2 edgeTable.add(temp); g.drawLine(temp.x1, temp.y1, temp.x2, temp.y2); removeList(); } count++; } } private void addList() { addMouseListener(this); } private void removeList() { removeMouseListener(this); Assignment6Scanline.intial=false; System.out.println(Assignment6Scanline.intial); scanline(); } public void getEdges() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); try { System.out.println("Enter No of vertices"); this.noOfVertices=Integer.parseInt(br.readLine()); System.out.println("Drawing edges "+noOfVertices); addList(); } catch (Exception e) { System.out.println(e.toString()); } } } class Edge { int x1,x2,y1,y2,dx,dy; int edgeNo; // yC y coordinate and ind :Index double slope; Edge(int edgeNo,int x1,int y1,int x2,int y2) { this.x1=x1; this.y1=y1; this.x2=x2; this.y2=y2; this.edgeNo=edgeNo; this.dx=x2-x1; this.dy=y2-y1; this.slope=(double)(dy)/(double)(dx); } }
3383591d45feee98a102500b2f8a3f408e726fb9
d07de20e38e394f4fb3cf0bb20b274adbbc8b84b
/src/main/java/com/reddoor/framework/service/boot/PostConstructService.java
82143fbec48b3259b1f12f7e37f2a65c4056da48
[ "MIT" ]
permissive
JefferyTien/TradeSystem
8b9303be61178299fd28ae275d57519fe56d7124
602e0e4221870547b572de760a09474dc7656614
refs/heads/master
2022-12-24T23:14:53.624893
2020-03-19T10:57:27
2020-03-19T10:57:27
226,647,897
0
0
MIT
2022-12-16T07:47:10
2019-12-08T10:09:39
Java
UTF-8
Java
false
false
1,529
java
package com.reddoor.framework.service.boot; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.reddoor.framework.domain.Configuration; import com.reddoor.framework.service.ConfigurationService; import com.reddoor.framework.utils.PropertiesUtils; import com.reddoor.framework.utils.SysCache; @Service("postConstructService") public class PostConstructService { @Autowired ConfigurationService configurationService; @PostConstruct public void init() throws Exception{ // 加载数据库中sys_configuration表的所有系统配置, 并放入syscache缓存 List<Configuration> sysConfigList = configurationService.findAll(); Map<String, Configuration> sysConfigMap = new HashMap<String, Configuration>(); if(null != sysConfigList){ for(Configuration eachConfig:sysConfigList){ sysConfigMap.put(eachConfig.getCode(), eachConfig); } } SysCache.sysConfigMap = sysConfigMap; // 加载classes根路径下的application.properties文件 String path = this.getClass().getResource("/").getPath(); String sysPropsPath = path + "/application.properties"; File sysPropsFile = new File(sysPropsPath); if(sysPropsFile.exists() && sysPropsFile.isFile()){ Properties sysProps = PropertiesUtils.getProperties(sysPropsPath); SysCache.sysProps = sysProps; } } }
e217a7dbfb6b4d26c41e58240b8c12540f924b3f
51fa3cc281eee60058563920c3c9059e8a142e66
/Java/src/testcases/CWE89_SQL_Injection/s01/CWE89_SQL_Injection__database_execute_04.java
a278f9fdce69ecffddbe228d6db5884e52631e49
[]
no_license
CU-0xff/CWE-Juliet-TestSuite-Java
0b4846d6b283d91214fed2ab96dd78e0b68c945c
f616822e8cb65e4e5a321529aa28b79451702d30
refs/heads/master
2020-09-14T10:41:33.545462
2019-11-21T07:34:54
2019-11-21T07:34:54
223,105,798
1
4
null
null
null
null
UTF-8
Java
false
false
20,290
java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE89_SQL_Injection__database_execute_04.java Label Definition File: CWE89_SQL_Injection.label.xml Template File: sources-sinks-04.tmpl.java */ /* * @description * CWE: 89 SQL Injection * BadSource: database Read data from a database * GoodSource: A hardcoded string * Sinks: execute * GoodSink: Use prepared statement and execute (properly) * BadSink : data concatenated into SQL statement used in execute(), which could result in SQL Injection * Flow Variant: 04 Control flow: if(PRIVATE_STATIC_FINAL_TRUE) and if(PRIVATE_STATIC_FINAL_FALSE) * * */ package testcases.CWE89_SQL_Injection.s01; import testcasesupport.*; import javax.servlet.http.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.sql.*; public class CWE89_SQL_Injection__database_execute_04 extends AbstractTestCase { /* The two variables below are declared "final", so a tool should * be able to identify that reads of these will always return their * initialized values. */ private static final boolean PRIVATE_STATIC_FINAL_TRUE = true; private static final boolean PRIVATE_STATIC_FINAL_FALSE = false; public void bad() throws Throwable { String data; if (PRIVATE_STATIC_FINAL_TRUE) { data = ""; /* Initialize data */ /* Read data from a database */ { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { /* setup the connection */ connection = IO.getDBConnection(); /* prepare and execute a (hardcoded) query */ preparedStatement = connection.prepareStatement("select name from users where id=0"); resultSet = preparedStatement.executeQuery(); /* POTENTIAL FLAW: Read data from a database query resultset */ data = resultSet.getString(1); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error with SQL statement", exceptSql); } finally { /* Close database objects */ try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (connection != null) { connection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (PRIVATE_STATIC_FINAL_TRUE) { Connection dbConnection = null; Statement sqlStatement = null; try { dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.createStatement(); /* POTENTIAL FLAW: data concatenated into SQL statement used in execute(), which could result in SQL Injection */ Boolean result = sqlStatement.execute("insert into users (status) values ('updated') where name='"+data+"'"); if(result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: " + data); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } /* goodG2B1() - use goodsource and badsink by changing first PRIVATE_STATIC_FINAL_TRUE to PRIVATE_STATIC_FINAL_FALSE */ private void goodG2B1() throws Throwable { String data; if (PRIVATE_STATIC_FINAL_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } else { /* FIX: Use a hardcoded string */ data = "foo"; } if (PRIVATE_STATIC_FINAL_TRUE) { Connection dbConnection = null; Statement sqlStatement = null; try { dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.createStatement(); /* POTENTIAL FLAW: data concatenated into SQL statement used in execute(), which could result in SQL Injection */ Boolean result = sqlStatement.execute("insert into users (status) values ('updated') where name='"+data+"'"); if(result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: " + data); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } /* goodG2B2() - use goodsource and badsink by reversing statements in first if */ private void goodG2B2() throws Throwable { String data; if (PRIVATE_STATIC_FINAL_TRUE) { /* FIX: Use a hardcoded string */ data = "foo"; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (PRIVATE_STATIC_FINAL_TRUE) { Connection dbConnection = null; Statement sqlStatement = null; try { dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.createStatement(); /* POTENTIAL FLAW: data concatenated into SQL statement used in execute(), which could result in SQL Injection */ Boolean result = sqlStatement.execute("insert into users (status) values ('updated') where name='"+data+"'"); if(result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: " + data); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } /* goodB2G1() - use badsource and goodsink by changing second PRIVATE_STATIC_FINAL_TRUE to PRIVATE_STATIC_FINAL_FALSE */ private void goodB2G1() throws Throwable { String data; if (PRIVATE_STATIC_FINAL_TRUE) { data = ""; /* Initialize data */ /* Read data from a database */ { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { /* setup the connection */ connection = IO.getDBConnection(); /* prepare and execute a (hardcoded) query */ preparedStatement = connection.prepareStatement("select name from users where id=0"); resultSet = preparedStatement.executeQuery(); /* POTENTIAL FLAW: Read data from a database query resultset */ data = resultSet.getString(1); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error with SQL statement", exceptSql); } finally { /* Close database objects */ try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (connection != null) { connection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (PRIVATE_STATIC_FINAL_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and execute (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("insert into users (status) values ('updated') where name=?"); sqlStatement.setString(1, data); Boolean result = sqlStatement.execute(); if (result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: " + data); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } /* goodB2G2() - use badsource and goodsink by reversing statements in second if */ private void goodB2G2() throws Throwable { String data; if (PRIVATE_STATIC_FINAL_TRUE) { data = ""; /* Initialize data */ /* Read data from a database */ { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { /* setup the connection */ connection = IO.getDBConnection(); /* prepare and execute a (hardcoded) query */ preparedStatement = connection.prepareStatement("select name from users where id=0"); resultSet = preparedStatement.executeQuery(); /* POTENTIAL FLAW: Read data from a database query resultset */ data = resultSet.getString(1); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error with SQL statement", exceptSql); } finally { /* Close database objects */ try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (connection != null) { connection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (PRIVATE_STATIC_FINAL_TRUE) { Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and execute (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("insert into users (status) values ('updated') where name=?"); sqlStatement.setString(1, data); Boolean result = sqlStatement.execute(); if (result) { IO.writeLine("Name, " + data + ", updated successfully"); } else { IO.writeLine("Unable to update records for user: " + data); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } public void good() throws Throwable { goodG2B1(); goodG2B2(); goodB2G1(); goodB2G2(); } /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
31c9b339b1d7accc8583cca509edab5eb6a572f3
5b320ab3401ce3fe968ec57929dd8013474f5c09
/02_Mobile Developer/02_Java (Intermediate)/055_ Closing Down the Client Stuff/Client.java
57afa36e83c510fc2b3414ba5d41ed52a2d47003
[]
no_license
abdibogor/Thenewboston
a7d701db4f233073b3bf0a422698e6accee885ff
743ad015601fa308d74cca46bfc2159a01ad9821
refs/heads/master
2020-08-05T14:39:37.866343
2020-02-13T08:37:12
2020-02-13T08:37:12
212,581,907
0
0
null
2020-01-02T13:55:18
2019-10-03T13:03:56
HTML
UTF-8
Java
false
false
2,819
java
import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Client extends JFrame{ private JTextField userText; private JTextArea chatWindow; private ObjectOutputStream output; private ObjectInputStream input; private String message = ""; private String serverIP; private Socket connection; //constructor public Client(String host){ super("Client"); serverIP = host; userText = new JTextField(); userText.setEditable(false); userText.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent event){ sendMessage(event.getActionCommand()); userText.setText(""); } } ); add(userText, BorderLayout.NORTH); chatWindow = new JTextArea(); add(new JScrollPane(chatWindow)); setSize(300, 150); //Sets the window size setVisible(true); } //connect to server public void startRunning(){ try{ connectToServer(); setupStreams(); whileChatting(); }catch(EOFException eofException){ showMessage("\n Client terminated the connection"); }catch(IOException ioException){ ioException.printStackTrace(); }finally{ closeConnection(); } } //connect to server private void connectToServer() throws IOException{ showMessage("Attempting connection... \n"); connection = new Socket(InetAddress.getByName(serverIP), 6789); showMessage("Connection Established! Connected to: " + connection.getInetAddress().getHostName()); } //53_ Setting Up the Client Streams //set up streams private void setupStreams() throws IOException{ output = new ObjectOutputStream(connection.getOutputStream()); output.flush(); input = new ObjectInputStream(connection.getInputStream()); showMessage("\n The streams are now set up! \n"); } //053_Setting Up the client Streams //Set up streams to send and receive messages private void setupStreams() throws IOException{ output = new ObjectOutputStream(connection.getOutputStream()); output.flush(); input = new ObjectInputStream(connection.getInputStream()); showMessage("\n Dude your streams are now good to go! \n"); } //054_WhileChatting Client //while chatting with server private void whileChatting() throws IOException{ ableToType(true); do{ try{ message = (String) input.readObject(); showMessage("\n" + message); }catch(ClassNotFoundException classNotfoundException){ showMessage("\n I dont know that object type"); } }while(!message.equals("SERVER - END")); } //close the streams and sockets private void closeConnection(){ showMessage("\n Closing the connection!"); ableToType(false); try{ output.close(); input.close(); connection.close(); }catch(IOException ioException){ ioException.printStackTrace(); } } }
2d9067a5a723d14934f5601a42005d2b978a9c0c
af94343dc60811321d976899de851c1c1e673c1c
/app/src/androidTest/java/com/example/fininfo/ExampleInstrumentedTest.java
338fb4edb1065518e1e16515ad23dd8aa0fbc8a9
[]
no_license
ZakharovP/Fininfo
a216c6621201de0d11ed2e46404bc6819da4cd33
5d7a2f44c8f172d9096a39fcdb151110c31d1f0b
refs/heads/master
2021-03-09T19:51:53.133405
2020-12-29T16:03:43
2020-12-29T16:03:43
246,374,332
0
1
null
null
null
null
UTF-8
Java
false
false
754
java
package com.example.fininfo; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.example.fininfo", appContext.getPackageName()); } }
380a3822b6d7d215159a77643cb80b4c5f64e944
b868a1cce5820782ba696981211d93e5caa8f623
/org.summer.xaml.core/src-gen/org/summer/xaml/core/xAML/util/XAMLSwitch.java
f1750b236d1adb8e1d1d7054cb54e72461f4ec51
[]
no_license
zwgirl/summer
220693d71294f8ccffe1b58e8bc1dea44536c47c
1da11dfb5c323d805422c9870382fb0a81d5a8f1
refs/heads/master
2021-01-22T22:57:46.801255
2014-04-29T22:00:21
2014-04-29T22:00:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,459
java
/** */ package org.summer.xaml.core.xAML.util; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; import org.summer.dsl.model.xbase.XExpression; import org.summer.xaml.core.xAML.*; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see org.summer.xaml.core.xAML.XAMLPackage * @generated */ public class XAMLSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static XAMLPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public XAMLSwitch() { if (modelPackage == null) { modelPackage = XAMLPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @parameter ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case XAMLPackage.DOCUMENT: { Document document = (Document)theEObject; T result = caseDocument(document); if (result == null) result = defaultCase(theEObject); return result; } case XAMLPackage.ELEMENT_CONTENT: { ElementContent elementContent = (ElementContent)theEObject; T result = caseElementContent(elementContent); if (result == null) result = defaultCase(theEObject); return result; } case XAMLPackage.OBJECT_ELEMENT: { ObjectElement objectElement = (ObjectElement)theEObject; T result = caseObjectElement(objectElement); if (result == null) result = caseElementContent(objectElement); if (result == null) result = defaultCase(theEObject); return result; } case XAMLPackage.ATTRIBUTE_ELEMENT: { AttributeElement attributeElement = (AttributeElement)theEObject; T result = caseAttributeElement(attributeElement); if (result == null) result = caseElementContent(attributeElement); if (result == null) result = defaultCase(theEObject); return result; } case XAMLPackage.ABSTRACT_PROPERTY: { AbstractProperty abstractProperty = (AbstractProperty)theEObject; T result = caseAbstractProperty(abstractProperty); if (result == null) result = defaultCase(theEObject); return result; } case XAMLPackage.PROPERTY: { Property property = (Property)theEObject; T result = caseProperty(property); if (result == null) result = caseAbstractProperty(property); if (result == null) result = defaultCase(theEObject); return result; } case XAMLPackage.MARKUP_EXTENSON: { MarkupExtenson markupExtenson = (MarkupExtenson)theEObject; T result = caseMarkupExtenson(markupExtenson); if (result == null) result = caseXExpression(markupExtenson); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Document</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Document</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDocument(Document object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Element Content</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Element Content</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseElementContent(ElementContent object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Object Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Object Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseObjectElement(ObjectElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Attribute Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Attribute Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseAttributeElement(AttributeElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Abstract Property</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Abstract Property</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseAbstractProperty(AbstractProperty object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Property</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Property</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseProperty(Property object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Markup Extenson</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Markup Extenson</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMarkupExtenson(MarkupExtenson object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>XExpression</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>XExpression</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseXExpression(XExpression object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //XAMLSwitch
f6011408de0de1ce79c835765d33e82e3c2730c0
18ae90e19a93488ef8fe96019d0bc98605e6b4c1
/servletstrail/src/com/servlets/LoginServlet.java
1141a42e8e14ea6bd93075764cdbf9a05783c03e
[]
no_license
srinivas7/code
1188dfb8daef5c4c282d202e9efa1a164d43f378
09f4e46830d587e620e418ad5fe7cd645b248dc1
refs/heads/master
2020-05-17T02:15:05.360852
2014-08-18T06:22:12
2014-08-18T06:22:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
812
java
package com.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet{ private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("username"); String p=request.getParameter("userpass"); out.print("name :"+n); out.print("pwd:"+p); } }
9ef5a9e3dcb5749eb071c89bd5b2404f592c8faa
00fd80e05fdb71505cad90ef560edbd8725189d5
/src/main/java/com/webapp/common/interceptor/PageInterceptor.java
275f8077b7a8543821ab0a4578fbc174dec3a99c
[]
no_license
masterasia/webapp
6c1895150e833b3a751c4cf4baa96865069c4b6a
7042e3e734e9b825840f347fa7a362a390639d78
refs/heads/master
2021-09-09T15:58:45.829737
2018-03-17T16:25:27
2018-03-17T16:25:52
125,622,968
1
0
null
null
null
null
UTF-8
Java
false
false
14,562
java
package com.webapp.common.interceptor; import com.webapp.common.utils.PageUtils; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.parameter.ParameterHandler; import org.apache.ibatis.executor.statement.RoutingStatementHandler; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.*; import org.apache.ibatis.plugin.*; import org.apache.ibatis.scripting.defaults.DefaultParameterHandler; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import java.lang.reflect.Field; import java.sql.*; import java.util.*; /** * @author Robert.XU * @email <[email protected]> * @date 2017/12/11 0011 下午 02:10 * @description 插件分页 */ @Intercepts({@Signature(method = "prepare", type = StatementHandler.class, args = {Connection.class}), @Signature(method = "query", type = Executor.class, args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})}) public class PageInterceptor implements Interceptor { private static final Logger log = LoggerFactory.getLogger(PageInterceptor.class); public static final String ORACLE = "oracle"; /** * 数据库类型,不同的数据库有不同的分页方法 */ protected String databaseType; protected ThreadLocal<PageUtils> pageThreadLocal = new ThreadLocal<PageUtils>(); public String getDatabaseType() { return databaseType; } public void setDatabaseType(String databaseType) { if (!databaseType.equalsIgnoreCase(ORACLE)) { throw new PageNotSupportException("Page not support for the type of database, database type [" + databaseType + "]"); } this.databaseType = databaseType; } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { String databaseType = properties.getProperty("databaseType"); if (databaseType != null) { setDatabaseType(databaseType); } } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public Object intercept(Invocation invocation) throws Throwable { // 控制SQL和查询总数的地方 if (invocation.getTarget() instanceof StatementHandler) { PageUtils page = pageThreadLocal.get(); //不是分页查询 if (page == null) { return invocation.proceed(); } RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget(); StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate"); BoundSql boundSql = delegate.getBoundSql(); Connection connection = (Connection) invocation.getArgs()[0]; // 准备数据库类型 prepareAndCheckDatabaseType(connection); if (page.getTotalPage() > -1) { if (log.isTraceEnabled()) { log.trace("已经设置了总页数, 不需要再查询总数."); } } else { Object parameterObj = boundSql.getParameterObject(); MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement"); queryTotalRecord(page, parameterObj, mappedStatement, connection); } String sql = boundSql.getSql(); String pageSql = buildPageSql(page, sql); if (log.isDebugEnabled()) { log.debug("分页时, 生成分页pageSql: " + pageSql); } ReflectUtil.setFieldValue(boundSql, "sql", pageSql); return invocation.proceed(); } else { // 查询结果的地方 // 获取是否有分页Page对象 PageUtils<?> page = findPageObject(invocation.getArgs()[1]); if (page == null) { if (log.isTraceEnabled()) { log.trace("没有Page对象作为参数, 不是分页查询."); } return invocation.proceed(); } else { if (log.isTraceEnabled()) { log.trace("检测到分页Page对象, 使用分页查询."); } } //设置真正的parameterObj invocation.getArgs()[1] = extractRealParameterObject(invocation.getArgs()[1]); pageThreadLocal.set(page); try { // Executor.query(..) Object resultObj = invocation.proceed(); if (resultObj instanceof List) { /* @SuppressWarnings({ "unchecked", "rawtypes" }) */ page.setList((List) resultObj); } return resultObj; } finally { pageThreadLocal.remove(); } } } protected PageUtils<?> findPageObject(Object parameterObj) { if (parameterObj instanceof PageUtils<?>) { return (PageUtils<?>) parameterObj; } else if (parameterObj instanceof Map) { for (Object val : ((Map<?, ?>) parameterObj).values()) { if (val instanceof PageUtils<?>) { return (PageUtils<?>) val; } } } return null; } /** * <pre> * 把真正的参数对象解析出来 * Spring会自动封装对个参数对象为Map<String, Object>对象 * 对于通过@Param指定key值参数我们不做处理,因为XML文件需要该KEY值 * 而对于没有@Param指定时,Spring会使用0,1作为主键 * 对于没有@Param指定名称的参数,一般XML文件会直接对真正的参数对象解析, * 此时解析出真正的参数作为根对象 * </pre> * * @param parameterObj * @return * @author jundong.xu_C */ protected Object extractRealParameterObject(Object parameterObj) { if (parameterObj instanceof Map<?, ?>) { Map<?, ?> parameterMap = (Map<?, ?>) parameterObj; int pageParamLength = 2; if (parameterMap.size() == pageParamLength) { boolean springMapWithNoParamName = true; for (Object key : parameterMap.keySet()) { if (!(key instanceof String)) { springMapWithNoParamName = false; break; } String keyStr = (String) key; if (!"0".equals(keyStr) && !"1".equals(keyStr)) { springMapWithNoParamName = false; break; } } if (springMapWithNoParamName) { for (Object value : parameterMap.values()) { if (!(value instanceof Page<?>)) { return value; } } } } } return parameterObj; } protected void prepareAndCheckDatabaseType(Connection connection) throws SQLException { if (databaseType == null) { String productName = connection.getMetaData().getDatabaseProductName(); if (log.isTraceEnabled()) { log.trace("Database productName: " + productName); } productName = productName.toLowerCase(); if (productName.indexOf(ORACLE) != -1) { databaseType = ORACLE; } else { throw new PageNotSupportException("Page not support for the type of database, database product name [" + productName + "]"); } if (log.isInfoEnabled()) { log.info("自动检测到的数据库类型为: " + databaseType); } } } /** * <pre> * 生成分页SQL * </pre> * * @param page * @param sql * @return * @author jundong.xu_C */ protected String buildPageSql(PageUtils<?> page, String sql) { if (ORACLE.equalsIgnoreCase(databaseType)) { return buildOraclePageSql(page, sql); } return sql; } /** * <pre> * 生成Oracle分页查询SQL * </pre> * * @param page * @param sql * @return * @author jundong.xu_C */ protected String buildOraclePageSql(PageUtils<?> page, String sql) { // 计算第一条记录的位置,Oracle分页是通过rownum进行的,而rownum是从1开始的 int offset = (page.getCurrPage() - 1) * page.getPageSize() + 1; StringBuilder sb = new StringBuilder(sql); sb.insert(0, "select u.*, rownum r from (").append(") u where rownum < ").append(offset + page.getPageSize()); sb.insert(0, "select * from (").append(") where r >= ").append(offset); return sb.toString(); } /** * <pre> * 查询总数 * </pre> * * @param page * @param parameterObject * @param mappedStatement * @param connection * @throws SQLException * @author jundong.xu_C */ protected void queryTotalRecord(PageUtils<?> page, Object parameterObject, MappedStatement mappedStatement, Connection connection) throws SQLException { BoundSql boundSql = mappedStatement.getBoundSql(page); String sql = boundSql.getSql(); String countSql = this.buildCountSql(sql); if (log.isDebugEnabled()) { log.debug("分页时, 生成countSql: " + countSql); } List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); BoundSql countBoundSql = new BoundSql(mappedStatement.getConfiguration(), countSql, parameterMappings, parameterObject); ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, countBoundSql); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = connection.prepareStatement(countSql); parameterHandler.setParameters(pstmt); rs = pstmt.executeQuery(); if (rs.next()) { Long totalRecord = rs.getLong(1); page.setTotalCount(totalRecord.intValue()); } } finally { if (rs != null) { try { rs.close(); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("关闭ResultSet时异常.", e); } } } if (pstmt != null) { try { pstmt.close(); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("关闭PreparedStatement时异常.", e); } } } } } /** * 根据原Sql语句获取对应的查询总记录数的Sql语句 * * @param sql * @return */ protected String buildCountSql(String sql) { int index = sql.indexOf("from"); return "select count(*) " + sql.substring(index); } /** * 利用反射进行操作的一个工具类 */ private static class ReflectUtil { /** * 利用反射获取指定对象的指定属性 * * @param obj 目标对象 * @param fieldName 目标属性 * @return 目标属性的值 */ public static Object getFieldValue(Object obj, String fieldName) { Object result = null; Field field = ReflectUtil.getField(obj, fieldName); if (field != null) { field.setAccessible(true); try { result = field.get(obj); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } /** * 利用反射获取指定对象里面的指定属性 * * @param obj 目标对象 * @param fieldName 目标属性 * @return 目标字段 */ private static Field getField(Object obj, String fieldName) { Field field = null; for (Class<?> clazz = obj.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) { try { field = clazz.getDeclaredField(fieldName); break; } catch (NoSuchFieldException e) { // 杩欓噷涓嶇敤鍋氬鐞嗭紝瀛愮被娌℃湁璇ュ瓧娈靛彲鑳藉搴旂殑鐖剁被鏈夛紝閮芥病鏈夊氨杩斿洖null銆� } } return field; } /** * 利用反射设置指定对象的指定属性为指定的值 * * @param obj 目标对象 * @param fieldName 目标属性 * @param fieldValue 目标值 */ public static void setFieldValue(Object obj, String fieldName, String fieldValue) { Field field = ReflectUtil.getField(obj, fieldName); if (field != null) { try { field.setAccessible(true); field.set(obj, fieldValue); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static class PageNotSupportException extends RuntimeException { public PageNotSupportException() { super(); } public PageNotSupportException(String message, Throwable cause) { super(message, cause); } public PageNotSupportException(String message) { super(message); } public PageNotSupportException(Throwable cause) { super(cause); } } }
6387e58f604834a53118162ce23740a0c008e601
0200d246c97e64e194aa770bb5991192b3df4f98
/SecondLabs/app/src/main/java/com/lumi/secondlabs/model/Cat.java
f35a025da68b820b6ecf1d4f84a777916c0e5bc6
[]
no_license
okorochek1/lab
244dab6a13dd33a50099fca96e6c29b6c4962d7d
d580f67c3b9af1de6ca358460cce5f7169b10cf4
refs/heads/main
2023-03-06T07:38:49.468275
2021-02-18T12:44:00
2021-02-18T12:44:00
339,014,266
0
0
null
null
null
null
UTF-8
Java
false
false
715
java
package com.lumi.secondlabs.model; import java.io.Serializable; public class Cat implements Serializable { private int mId; private int mUrlImgRes; private String mName; private String description; public Cat(int mId, int mUrlImgRes, String mName, String description) { this.mId = mId; this.mUrlImgRes = mUrlImgRes; this.mName = mName; this.description = description; } public int getId() { return mId; } public int getUrlImgRes() { return mUrlImgRes; } public String getName() { return mName; } public String getDescription() { return description; } }
670cd671c386aeeae2919ea96f49e71cc2451120
d772a1d658f1efa7018763e12310e8b4a01c84fc
/src/music/objects/Guitar.java
3f9a3790138613bdda13a7bf8e7335f29bbb76f7
[]
no_license
YaremenkoIgor/module9
c832f74a40a446a06952fdd3c356287069193648
595330a701583743acdaba53f1021508ac73785a
refs/heads/master
2021-01-10T14:39:26.932502
2016-01-30T13:33:23
2016-01-30T13:33:23
50,726,041
0
0
null
null
null
null
UTF-8
Java
false
false
350
java
package music.objects; import music.abstract_level.MusicalInstruments; public class Guitar extends MusicalInstruments { public Guitar(String name, Integer prise) { super(name, prise); } @Override public String toString() { return Guitar.class.getSimpleName()+ "\t\t " + getName() + "\t\t " + getPrise(); } }
af39acbc6b5254236327c32854a9ca1dc3c38344
521f9a81ff171c8a68cf78a794eab3355017e438
/src/main/java/Levenshtein.java
bf49a5e9c0ae8e1f4bf60978ff984087130e1e3d
[]
no_license
Radutiu-Horatiu/java-playtime
976757e906e348130c85e1cdfe7aef812645f5be
1d6d8c75c739ed16a9c7876bebb13e6f877a663f
refs/heads/main
2023-01-24T13:48:33.923099
2020-11-17T16:40:19
2020-11-17T16:40:19
313,680,424
0
0
null
null
null
null
UTF-8
Java
false
false
1,082
java
import java.util.Arrays; // The Levenshtein distance is a measure of dissimilarity between two Strings. // Mathematically, given two Strings x and y, the distance // measures the minimum number of character edits required to transform x into y. public class Levenshtein implements Distance { @Override public double compute(String s1, String s2) { if (s1.isEmpty()) { return s2.length(); } if (s2.isEmpty()) { return s1.length(); } int substitution = (int) (compute(s1.substring(1), s2.substring(1)) + costOfSubstitution(s1.charAt(0), s2.charAt(0))); int insertion = (int) (compute(s1, s2.substring(1)) + 1); int deletion = (int) (compute(s1.substring(1), s2) + 1); return min(substitution, insertion, deletion); } public static int costOfSubstitution(char a, char b) { return a == b ? 0 : 1; } public static int min(int... numbers) { return Arrays.stream(numbers) .min().orElse(Integer.MAX_VALUE); } }
d69fb2101cd165e47306aac60085cba6e3c1ce57
611a518fc1c33fa0e981be1303e1335b2bb6349a
/Proyecto_DDB_completo/src/java/db/dao/AdministradorDAO.java
95965688e873a0ba1427685cfe9f43d913086463
[]
no_license
jonciverka/Proyecto_BDD_Completo
dd4dfd2ba8c633cb85ea55aae0b57bec3a2913fe
7cb52e8f6f9911b8e34f1186ff408ccdb467367b
refs/heads/master
2020-03-11T17:19:14.882228
2018-05-02T16:14:50
2018-05-02T16:14:50
130,143,796
0
0
null
null
null
null
UTF-8
Java
false
false
4,587
java
package db.dao; import db.entity.Administrador; import db.connection.Conexion; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class AdministradorDAO { public AdministradorDAO(){} public void agregarAdministrador(Administrador a) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{ Conexion conector = new Conexion(); String query = "insert into Administrador values(?,?,?)"; PreparedStatement pS; conector.setBd("proyecto_DDB"); conector.abrirConexion(); pS = conector.getConect().prepareStatement(query); conector.getConect().setAutoCommit(false); pS.setInt(1, a.getIdAdministrador()); pS.setString(2, a.getCodigo()); pS.setInt(3, a.getIdUsuario()); pS.execute(); conector.getConect().commit(); conector.cerrarConexion(); } public Administrador buscarAdministrador(int id) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{ Conexion conector = new Conexion(); String query = "select * from Administrador where idAdministrador = ?"; PreparedStatement pS; ResultSet rS; conector.setBd("proyecto_DDB"); conector.abrirConexion(); pS = conector.getConect().prepareStatement(query); conector.getConect().setAutoCommit(false); pS.setInt(1, id); rS = pS.executeQuery(); conector.getConect().commit(); return rS.next() ? new Administrador(rS.getInt(1), rS.getString(2), rS.getInt(3)) : null; } public Administrador buscarAdministradorDeUsuario(int id) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{ Conexion conector = new Conexion(); String query = "select * from Administrador where idUsuario = ?"; PreparedStatement pS; ResultSet rS; conector.setBd("proyecto_DDB"); conector.abrirConexion(); pS = conector.getConect().prepareStatement(query); conector.getConect().setAutoCommit(false); pS.setInt(1, id); rS = pS.executeQuery(); conector.getConect().commit(); return rS.next() ? new Administrador(rS.getInt(1), rS.getString(2), rS.getInt(3)) : null; } public void eliminarAdministrador(int id) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{ Conexion conector = new Conexion(); String query = "delete from Administrador where idUsuario=?"; PreparedStatement pS; conector.setBd("proyecto_DDB"); conector.abrirConexion(); pS = conector.getConect().prepareStatement(query); conector.getConect().setAutoCommit(false); pS.setInt(1,id); pS.execute(); conector.getConect().commit(); conector.cerrarConexion(); } public void actualizarAdministrador(Administrador a) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{ Conexion conector = new Conexion(); String query = "UPDATE usuario SET Codigo=?, idUsuario=? WHERE idAdministrador = ?"; PreparedStatement pS; conector.setBd("proyecto_DDB"); conector.abrirConexion(); pS = conector.getConect().prepareStatement(query); conector.getConect().setAutoCommit(false); pS.setString(1, a.getCodigo()); pS.setInt(2, a.getIdUsuario()); pS.setInt(3, a.getIdAdministrador()); pS.execute(); conector.getConect().commit(); } public List<Administrador> getAdministradores() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { Conexion conector = new Conexion(); String query = "SELECT * FROM Administrador ORDER BY idAdministrador"; PreparedStatement pS; ResultSet rS; conector.setBd("proyecto_DDB"); conector.abrirConexion(); pS = conector.getConect().prepareStatement(query); conector.getConect().setAutoCommit(false); rS = pS.executeQuery(); conector.getConect().commit(); List<Administrador> lista = new ArrayList<>(); while (rS.next()) { lista.add(new Administrador(rS.getInt(1), rS.getString(2), rS.getInt(3))); } return lista; } }
22ed1f8aaa6f4958f1eac66561691f0e77ab799f
f72a77c446c66fe0ee087707d901b36b3412d698
/src/main/java/com/iapppay/consumer/common/ServiceTypeEnum.java
c467206f7dc5957975a46b5e23b9fa15b61f5d02
[]
no_license
GAMEOVERFUTURE/ActiveMQ
969e74d1ae644f085792c61ba327bd102d099b7c
a58edd8e1fea9da6bac44494d5968285bf1584ab
refs/heads/master
2022-12-26T21:22:41.240329
2019-06-20T03:06:50
2019-06-20T03:06:50
192,831,742
0
0
null
2022-12-16T11:53:53
2019-06-20T02:05:50
Java
UTF-8
Java
false
false
684
java
package com.iapppay.consumer.common; /** * * @className: ServiceTypeEnum * @classDescription:服务类型 * @author lishiqiang * @create_date: 2019年5月7日 上午10:31:01 * @update_date: */ public enum ServiceTypeEnum { /** * 计费服务 */ CHARGE_SERVE("10"), /** * 计费委托结算 */ CHARGE_SETTLEMENT("11"), /** * 代理合作 */ PROXY_TEAMWORK("12"), /** * 渠道推广 */ CHANNEL_POP("13"), /** * 标准ODM */ STANDARD_ODM("14"); private String value; ServiceTypeEnum(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
6fbd123d05c18f0a171bba17ae807155ad7b40fb
7a97c9997afac69bbf080134e3e3d368433d0366
/src/com/riders/model/Usuario.java
bbd36e60175ec7b6c14ec48d0f6396ad42c9671e
[ "MIT" ]
permissive
dancreations/riders
542465b1d23990bf4aa444b89ed5161e6a0f3cd9
c11ef9d1d5c24e0cc43b74a4a38be61f5be1a7a2
refs/heads/master
2020-12-24T14:01:45.150536
2014-04-05T20:22:11
2014-04-05T20:22:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,338
java
package com.riders.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "usuario") @Inheritance(strategy=InheritanceType.JOINED) public class Usuario implements Serializable{ private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name = "pk_sequence", sequenceName = "id_usuario_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_sequence") @Column(name = "id_usuario", unique = true, nullable = false) private Integer id; @Column(name = "email") private String email; @Column(name = "password") private String password; public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
be2cbf1494dbd3a1be8e5119d3bb977f413656a4
d17f1ab28c36e991759f323fac87872da3281f15
/src/Array/RemoveDuplicatesFromSortedArray_26.java
d4f49e99010900b304ff4e2f437845a5e836493c
[]
no_license
bowenli0379/leetcode
d54ecfccc2ec742dca0ccf6654cf951deb4e700a
43315337b7a83ac39a072d16b8c65860e2010f14
refs/heads/master
2020-09-01T23:00:56.910994
2020-01-09T05:26:37
2020-01-09T05:26:37
219,076,124
0
0
null
null
null
null
UTF-8
Java
false
false
437
java
package Array; public class RemoveDuplicatesFromSortedArray_26 { public static int removeDuplicates(int[] nums){ int count = 1; for (int i = 1; i < nums.length; i++){ if (nums[i] != nums[i-1]) count++; } return count; } public static void main(String[] args){ int[] nums = {0,0,1,1,1,2,2,3,3,4}; System.out.println(removeDuplicates(nums)); } }
02249f66622fc824b7f645445e1424aee7b65353
69cb8b8fae97309aecc5bdb2ec2df185c85382d2
/src/test/java/org/culturegraph/mf/stream/converter/ObjectToLiteralTest.java
af5e54e2f30d9f0eb36a7dc9e1ab96127a400b14
[]
no_license
liyining/metafacture-core
74a2e0867442e95ba1545a3a38ad2ca7d5efc6c3
abde57d925e28aed257b5c6d71787398f2fbe006
refs/heads/master
2020-12-24T17:54:30.090884
2013-07-03T11:16:54
2013-07-03T11:16:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,740
java
/* * Copyright 2013 Deutsche Nationalbibliothek * * 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.culturegraph.mf.stream.converter; import org.culturegraph.mf.exceptions.FormatException; import org.culturegraph.mf.stream.converter.ObjectToLiteral; import org.culturegraph.mf.stream.sink.EventList; import org.culturegraph.mf.stream.sink.StreamValidator; import org.junit.Assert; import org.junit.Test; /** * @author Christoph Böhme * */ public final class ObjectToLiteralTest { private static final String LITERAL_NAME = "myObject"; private static final String OBJ_DATA = "This is a data object"; @Test public void test() { final EventList buffer = new EventList(); buffer.startRecord(null); buffer.literal(LITERAL_NAME, OBJ_DATA); buffer.endRecord(); buffer.closeStream(); final ObjectToLiteral<String> objectToLiteral = new ObjectToLiteral<String>(); objectToLiteral.setLiteralName(LITERAL_NAME); final StreamValidator validator = new StreamValidator(buffer.getEvents()); objectToLiteral.setReceiver(validator); try { objectToLiteral.process(OBJ_DATA); objectToLiteral.closeStream(); } catch(FormatException e) { Assert.fail(e.toString()); } } }
8beb262e34bd027b79699c555cf980f9722da3a0
aa7e8dbe2235b3c250692a8712f11f94f8aa70eb
/yuyoubang-xiaoyuan_fun1/yuyoubang-xiaoyuan_fun1.0/app/src/main/java/com/yuyoubang/activity/mine/business/ActionMangerActivity.java
d09fa097e1bfc8490314f7fb3c458dc7bf5ae3f8
[]
no_license
beizhongshashui/TestProject
5af74d9f67ab1016b2c4071c52536a77aa4ed052
4c04be65c8e455d979f22b79340e3418c6abf5bb
refs/heads/master
2020-06-27T22:23:33.741343
2017-07-13T05:36:39
2017-07-13T05:36:39
97,070,760
0
0
null
null
null
null
UTF-8
Java
false
false
3,030
java
package com.yuyoubang.activity.mine.business; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import com.yuyoubang.R; import com.yuyoubang.activity.base.BaseActivity; import com.yuyoubang.activity.mine.business.action.AllActionFragment; import com.yuyoubang.activity.mine.business.action.DelActionFragment; import com.yuyoubang.activity.mine.business.action.OfflineActionFragment; import com.yuyoubang.activity.mine.business.action.OnlineActionFragment; import com.yuyoubang.activity.mine.business.action.UnonlineActionFragment; import java.util.ArrayList; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by xiaoyuan on 16/12/1. */ public class ActionMangerActivity extends BaseActivity { @Bind(R.id.act_tablayout) TabLayout actTablayout; @Bind(R.id.act_vp) ViewPager actVp; private FragmentPagerAdapter adapter; public static void start(Context context) { Intent intent = new Intent(context, ActionMangerActivity.class); context.startActivity(intent); } @Override protected void initTitleBar(HeaderBuilder builder) { builder.setTitle("活动路线管理"); } @Override protected int getContentResId() { return R.layout.act_act_manger; } private void initView() { adapter = new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int position) { return getFragments().get(position); } @Override public int getCount() { return getFragments().size(); } }; actVp.setAdapter(adapter); actTablayout.setTabMode(TabLayout.MODE_FIXED); initTabLine(); } private void initTabLine() { actTablayout.setupWithViewPager(actVp); actTablayout.getTabAt(0).setText("全部"); actTablayout.getTabAt(1).setText("待审核"); actTablayout.getTabAt(2).setText("已上线"); actTablayout.getTabAt(3).setText("已下线"); actTablayout.getTabAt(4).setText("已删除");//by xiaoyuan } private ArrayList<Fragment> getFragments() { ArrayList<Fragment> fragments = new ArrayList<>(); fragments.add(AllActionFragment.newInstance()); fragments.add(UnonlineActionFragment.newInstance()); fragments.add(OnlineActionFragment.newInstance()); fragments.add(OfflineActionFragment.newInstance()); fragments.add(DelActionFragment.newInstance()); //by xiaoyuan return fragments; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); initView(); } }
f877a67ba1fd8437d45210f7a0788f66d13ca42b
8a88d3ee3d126db77682aea65597f88141586bfb
/src/first/first1.java
97ab0fa5c85dac195215429b49d9e34cb6ce8d29
[]
no_license
jadhavmanisha15/nishigandha_selenium
8fc5fc5fe4cbe0f6bee2a55d88c9c8a30c146619
ea03548e8930671ca90071fc82ef0838eb2010c2
refs/heads/main
2023-04-08T21:13:17.419562
2021-04-02T05:18:46
2021-04-02T05:18:46
362,075,588
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
722
java
package first; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.Test; public class first1 { @Test public void m1() { System.setProperty("webdriver.chrome.driver", "D:\\selenium software\\drivers\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.navigate().to("https://accounts.google.com"); driver.findElement(By.cssSelector("input#identifierId")).sendKeys("[email protected]");; driver.findElement(By.cssSelector("div.VfPpkd-RLmnJb")).click(); driver.navigate().back(); Assert.assertEquals(driver.getTitle(), "Sign in – Google accounts"); } }
ce6dcd3c7d7c01b885e2492c170ca992316d5ae7
81719679e3d5945def9b7f3a6f638ee274f5d770
/aws-java-sdk-appstream/src/main/java/com/amazonaws/services/appstream/model/DescribeUserStackAssociationsResult.java
a1071884f9af07c6c0d87b8f4f94ff6ac52df007
[ "Apache-2.0" ]
permissive
ZeevHayat1/aws-sdk-java
1e3351f2d3f44608fbd3ff987630b320b98dc55c
bd1a89e53384095bea869a4ea064ef0cf6ed7588
refs/heads/master
2022-04-10T14:18:43.276970
2020-03-07T12:15:44
2020-03-07T12:15:44
172,681,373
1
0
Apache-2.0
2019-02-26T09:36:47
2019-02-26T09:36:47
null
UTF-8
Java
false
false
7,588
java
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.appstream.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DescribeUserStackAssociations" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeUserStackAssociationsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The UserStackAssociation objects. * </p> */ private java.util.List<UserStackAssociation> userStackAssociations; /** * <p> * The pagination token to use to retrieve the next page of results for this operation. If there are no more pages, * this value is null. * </p> */ private String nextToken; /** * <p> * The UserStackAssociation objects. * </p> * * @return The UserStackAssociation objects. */ public java.util.List<UserStackAssociation> getUserStackAssociations() { return userStackAssociations; } /** * <p> * The UserStackAssociation objects. * </p> * * @param userStackAssociations * The UserStackAssociation objects. */ public void setUserStackAssociations(java.util.Collection<UserStackAssociation> userStackAssociations) { if (userStackAssociations == null) { this.userStackAssociations = null; return; } this.userStackAssociations = new java.util.ArrayList<UserStackAssociation>(userStackAssociations); } /** * <p> * The UserStackAssociation objects. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setUserStackAssociations(java.util.Collection)} or * {@link #withUserStackAssociations(java.util.Collection)} if you want to override the existing values. * </p> * * @param userStackAssociations * The UserStackAssociation objects. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeUserStackAssociationsResult withUserStackAssociations(UserStackAssociation... userStackAssociations) { if (this.userStackAssociations == null) { setUserStackAssociations(new java.util.ArrayList<UserStackAssociation>(userStackAssociations.length)); } for (UserStackAssociation ele : userStackAssociations) { this.userStackAssociations.add(ele); } return this; } /** * <p> * The UserStackAssociation objects. * </p> * * @param userStackAssociations * The UserStackAssociation objects. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeUserStackAssociationsResult withUserStackAssociations(java.util.Collection<UserStackAssociation> userStackAssociations) { setUserStackAssociations(userStackAssociations); return this; } /** * <p> * The pagination token to use to retrieve the next page of results for this operation. If there are no more pages, * this value is null. * </p> * * @param nextToken * The pagination token to use to retrieve the next page of results for this operation. If there are no more * pages, this value is null. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The pagination token to use to retrieve the next page of results for this operation. If there are no more pages, * this value is null. * </p> * * @return The pagination token to use to retrieve the next page of results for this operation. If there are no more * pages, this value is null. */ public String getNextToken() { return this.nextToken; } /** * <p> * The pagination token to use to retrieve the next page of results for this operation. If there are no more pages, * this value is null. * </p> * * @param nextToken * The pagination token to use to retrieve the next page of results for this operation. If there are no more * pages, this value is null. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeUserStackAssociationsResult withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getUserStackAssociations() != null) sb.append("UserStackAssociations: ").append(getUserStackAssociations()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeUserStackAssociationsResult == false) return false; DescribeUserStackAssociationsResult other = (DescribeUserStackAssociationsResult) obj; if (other.getUserStackAssociations() == null ^ this.getUserStackAssociations() == null) return false; if (other.getUserStackAssociations() != null && other.getUserStackAssociations().equals(this.getUserStackAssociations()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getUserStackAssociations() == null) ? 0 : getUserStackAssociations().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); return hashCode; } @Override public DescribeUserStackAssociationsResult clone() { try { return (DescribeUserStackAssociationsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
[ "" ]
ab08ca9fa0b65a3c18440a41e4426f1c2aabc0f7
66220fbb2b7d99755860cecb02d2e02f946e0f23
/src/net/sourceforge/plantuml/ugraphic/tikz/DriverLineTikz.java
4ac35b9ae077942c9498a6d935e2f15b1b4df413
[ "MIT" ]
permissive
isabella232/plantuml-mit
27e7c73143241cb13b577203673e3882292e686e
63b2bdb853174c170f304bc56f97294969a87774
refs/heads/master
2022-11-09T00:41:48.471405
2020-06-28T12:42:10
2020-06-28T12:42:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,550
java
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * Licensed under The MIT License (Massachusetts Institute of Technology License) * * See http://opensource.org/licenses/MIT * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.ugraphic.tikz; import net.sourceforge.plantuml.tikz.TikzGraphics; import net.sourceforge.plantuml.ugraphic.UDriver; import net.sourceforge.plantuml.ugraphic.ULine; import net.sourceforge.plantuml.ugraphic.UParam; import net.sourceforge.plantuml.ugraphic.UShape; import net.sourceforge.plantuml.ugraphic.color.ColorMapper; public class DriverLineTikz implements UDriver<TikzGraphics> { public void draw(UShape shape, double x, double y, ColorMapper mapper, UParam param, TikzGraphics tikz) { final ULine line = (ULine) shape; double x2 = x + line.getDX(); double y2 = y + line.getDY(); tikz.setStrokeColor(mapper.toColor(param.getColor())); tikz.setStrokeWidth(param.getStroke().getThickness(), param.getStroke().getDashTikz()); tikz.line(x, y, x2, y2); } }
d4df69e0d03734bab3415a4b96dd5a34aa8266c0
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/8/8_402be9a45b1f9baf94d75aaffa5f20b38188fa9f/WlAvatarContext/8_402be9a45b1f9baf94d75aaffa5f20b38188fa9f_WlAvatarContext_t.java
a813e0455a6196adf771de342ede5e7d95990970
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
2,979
java
/** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.modules.avatarbase.client.jme.cellrenderer; import imi.character.avatar.Avatar; import imi.character.statemachine.corestates.ActionInfo; import imi.character.statemachine.corestates.ActionState; import imi.character.statemachine.corestates.CycleActionState; import java.util.HashMap; /** * * Overload AvatarContext to add playMiscAnimation * * @author paulby */ public class WlAvatarContext extends imi.character.avatar.AvatarContext { private HashMap<String, ActionInfo> actionMap = new HashMap(); private ActionInfo currentActionInfo = null; public WlAvatarContext(Avatar avatar) { super(avatar); if (avatar.getCharacterParams().isAnimateBody()) for(ActionInfo actionInfo : getGenericAnimations()) { actionMap.put(actionInfo.getAnimationName(), actionInfo); } } /** * Return the names of the animations available to this character * @return */ public Iterable<String> getAnimationNames() { return actionMap.keySet(); } public void playMiscAnimation(String name) { if (getavatar().getCharacterParams().isAnimateBody()) { setMiscAnimation(name); // Force the trigger, note that this transition is so fast that the // state machine may not actually change state. Therefore in triggerAlert // we check for the trigger and force the state change. triggerReleased(TriggerNames.MiscAction.ordinal()); triggerPressed(TriggerNames.MiscAction.ordinal()); triggerReleased(TriggerNames.MiscAction.ordinal()); } } public void setMiscAnimation(String animationName) { currentActionInfo = actionMap.get(animationName); ActionState action = (ActionState) gameStates.get(CycleActionState.class); action.setAnimationSetBoolean(false); currentActionInfo.apply(action); } @Override protected void triggerAlert(int trigger, boolean pressed) { if (pressed && trigger==TriggerNames.MiscAction.ordinal()) { // Force animation to play if this is a Misc trigger setCurrentState((ActionState) gameStates.get(CycleActionState.class)); } } }
820ccc8273005d445bb17ddbc9d9f3f56941b5c6
bff7e328cc5f498a63a0a83393cd5a9c07e7699b
/ServiceDeskAula03/src/br/usjt/sdesk/controller/ManterChamadosController.java
d49d3962e7b61ea8e0269b67e805f7871e7e0827
[]
no_license
kayquefs/Aula03
41fdd6d863d5a6ca4f126b9864f2348504c3d771
b34f28ca44978549c9b855d47b8bbe41e04d4f94
refs/heads/master
2020-03-08T06:44:23.777370
2018-04-03T23:28:08
2018-04-03T23:28:08
127,978,716
0
0
null
null
null
null
UTF-8
Java
false
false
4,089
java
package br.usjt.sdesk.controller; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import br.usjt.sdesk.model.entity.Chamado; import br.usjt.sdesk.model.entity.Fila; import br.usjt.sdesk.model.service.ChamadoService; import br.usjt.sdesk.model.service.FilaService; /** * * @author Kayque Fernandes dos Santos 816121871 * */ @Controller public class ManterChamadosController { private FilaService filaService; private ChamadoService chamadoService; @Autowired public ManterChamadosController(FilaService fs, ChamadoService cs){ filaService = fs; chamadoService = cs; } @RequestMapping("index") public String inicio() { return "index"; } private ArrayList<Fila> carregarFilas() throws IOException { return filaService.listarFilas(); } @RequestMapping("/listar_filas") public String listarFilas(Model model) { try { model.addAttribute("lista", carregarFilas()); return "NovoChamado"; } catch (IOException e) { e.printStackTrace(); return "Erro"; } } @RequestMapping("/criar_chamado") public String criarChamado(@Valid Chamado chamado, BindingResult result, Model model) { if (result.hasErrors()) { try { model.addAttribute("lista", carregarFilas()); return "NovoChamado"; } catch (IOException e) { e.printStackTrace(); return "Erro"; } } else { try { int idChamado = chamadoService.novoChamado(chamado); chamado.setNumero(idChamado); return "NumeroChamado"; } catch (IOException e) { e.printStackTrace(); return "Erro"; } } } @RequestMapping("/listar_filas_fechar") public String listarFilasFechar(Model model) { try { ArrayList<Fila> filas = filaService.listarFilas(); model.addAttribute("filas", filas); return "ChamadoFechar"; } catch (IOException e) { e.printStackTrace(); return "Erro"; } } @RequestMapping("/listar_chamados_abertos") public String listarChamadosAbertos(Fila fila, Model model) { try { fila = filaService.carregar(fila.getId()); model.addAttribute("fila", fila); ArrayList<Chamado> chamados = chamadoService.listarChamadosAbertos(fila); model.addAttribute("chamados", chamados); return "ChamadoFecharSelecionar"; } catch (IOException e) { e.printStackTrace(); return "Erro"; } } @RequestMapping("/fechar_chamados") public String fecharChamados( @RequestParam Map<String, String> allRequestParams) { try { Set<String> chaves = allRequestParams.keySet(); Iterator<String> i = chaves.iterator(); ArrayList<Integer> lista = new ArrayList<>(); while (i.hasNext()) { String chave = i.next(); String valor = (String) allRequestParams.get(chave); if (valor.equals("on")) { lista.add(Integer.parseInt(chave)); } } if (lista.size() > 0) { chamadoService.fecharChamados(lista); } return "ChamadoFechado"; } catch (IOException e) { e.printStackTrace(); return "Erro"; } } @RequestMapping("/listar_filas_exibir") public String listarFilasExibir(Model model) { try { ArrayList<Fila> filas = filaService.listarFilas(); model.addAttribute("filas", filas); return "ChamadoListar"; } catch (IOException e) { e.printStackTrace(); return "Erro"; } } @RequestMapping("/listar_chamados_exibir") public String listarChamadosExibir(Fila fila, Model model) { try { fila = filaService.carregar(fila.getId()); model.addAttribute("fila", fila); ArrayList<Chamado> chamados = chamadoService.listarChamados(fila); model.addAttribute("chamados", chamados); return "ChamadoListarExibir"; } catch (IOException e) { e.printStackTrace(); return "Erro"; } } }
bde11d4fe328c2486fd72512444bf90de702357f
be1c8b038a665f8e6babf85c2fdf04eeaced76ef
/src/main/java/net/termer/twine/exceptions/ConfigException.java
217032ad7482d94a3f75a9b35fc6d63951fb11ea
[ "MIT" ]
permissive
termermc/Twine
aa3909d1c4ca028d28ba812b3b6d8c11af2e7fd5
a2235bbbff7bb8c844442978558c0c9b450465ee
refs/heads/master
2021-08-02T07:59:30.154822
2021-07-31T23:07:09
2021-07-31T23:07:09
197,664,105
5
0
null
null
null
null
UTF-8
Java
false
false
795
java
package net.termer.twine.exceptions; /** * Exception to be thrown in the case of errors in config files * @author termer * @since 2.0 */ public class ConfigException extends Exception { // Path to the config file the error originated in private final String _path; /** * Instantiates a new ConfigException * @param path Path to the config file the error originated in * @param msg The Exception message * @since 2.0 */ public ConfigException(String path, String msg) { super(msg); _path = path; } /** * Returns the path to the config file this error originated in * @return The path to the config file this error originated in * @since 2.0 */ public String getPath() { return _path; } }
e6df507f34076a6d145931c4ec3a6ca39b1c692d
4a4e746c28636e916c966596476341f79389842b
/app/src/test/java/com/babach/beatbox/ExampleUnitTest.java
bd216cbd96d45290cb2c972c958ab5565559f30e
[]
no_license
SBabach/BeatBox
7769dfbe72be355cfbccdbc24882e86971941a3c
b06602d8ceeba572b9dae0b1df9bed29089fd642
refs/heads/master
2020-05-07T20:31:06.594686
2019-05-02T16:31:15
2019-05-02T16:31:15
180,864,709
0
0
null
null
null
null
UTF-8
Java
false
false
383
java
package com.babach.beatbox; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
ff1585756b93059c7de56aafdd332208f1be1728
2ad861d6123ad8659fbcd4baaa7ee3a800524314
/component/viewer/wicket/model/src/main/java/org/apache/isis/viewer/wicket/model/models/ActionModel.java
e0909d3d5668f52ceee1d6b73cce3861622e8da5
[ "Apache-2.0" ]
permissive
moonskewer/isis
2fdfa74c2f569f8a8488c01c6ff6e04eda236783
a6aafd316d63429c1b8e03d631466e82abf59608
refs/heads/master
2021-01-15T09:37:09.771096
2014-01-22T22:38:29
2014-01-22T22:38:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
22,147
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.viewer.wicket.model.models; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.request.handler.resource.ResourceRequestHandler; import org.apache.wicket.request.handler.resource.ResourceStreamRequestHandler; import org.apache.wicket.request.http.handler.RedirectRequestHandler; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.request.resource.ByteArrayResource; import org.apache.wicket.request.resource.ContentDisposition; import org.apache.wicket.util.resource.StringResourceStream; import org.apache.isis.applib.ApplicationException; import org.apache.isis.applib.Identifier; import org.apache.isis.applib.annotation.ActionSemantics; import org.apache.isis.applib.annotation.BookmarkPolicy; import org.apache.isis.applib.value.Blob; import org.apache.isis.applib.value.Clob; import org.apache.isis.core.metamodel.adapter.ObjectAdapter; import org.apache.isis.core.metamodel.adapter.mgr.AdapterManager.ConcurrencyChecking; import org.apache.isis.core.metamodel.adapter.oid.OidMarshaller; import org.apache.isis.core.metamodel.adapter.oid.RootOid; import org.apache.isis.core.metamodel.adapter.oid.RootOidDefault; import org.apache.isis.core.metamodel.consent.Consent; import org.apache.isis.core.metamodel.facets.object.bookmarkable.BookmarkPolicyFacet; import org.apache.isis.core.metamodel.facets.object.encodeable.EncodableFacet; import org.apache.isis.core.metamodel.spec.ActionType; import org.apache.isis.core.metamodel.spec.ObjectSpecId; import org.apache.isis.core.metamodel.spec.ObjectSpecification; import org.apache.isis.core.metamodel.spec.feature.ObjectAction; import org.apache.isis.core.metamodel.spec.feature.ObjectActionParameter; import org.apache.isis.core.runtime.system.context.IsisContext; import org.apache.isis.viewer.wicket.model.mementos.ActionMemento; import org.apache.isis.viewer.wicket.model.mementos.ActionParameterMemento; import org.apache.isis.viewer.wicket.model.mementos.ObjectAdapterMemento; import org.apache.isis.viewer.wicket.model.mementos.PageParameterNames; /** * Models an action invocation, either the gathering of arguments for the * action's {@link Mode#PARAMETERS parameters}, or the handling of the * {@link Mode#RESULTS results} once invoked. */ public class ActionModel extends BookmarkableModel<ObjectAdapter> { private static final long serialVersionUID = 1L; private static final String NULL_ARG = "$nullArg$"; /** * Whether we are obtaining arguments (eg in a dialog), or displaying the * results */ private enum Mode { PARAMETERS, RESULTS } ////////////////////////////////////////////////// // Factory methods ////////////////////////////////////////////////// /** * @param objectAdapter * @param action * @return */ public static ActionModel create(ObjectAdapter objectAdapter, ObjectAction action) { final ObjectAdapterMemento serviceMemento = ObjectAdapterMemento.Functions.fromAdapter().apply(objectAdapter); final ActionMemento homePageActionMemento = ObjectAdapterMemento.Functions.fromAction().apply(action); final Mode mode = action.getParameterCount() > 0? Mode.PARAMETERS : Mode.RESULTS; return new ActionModel(serviceMemento, homePageActionMemento, mode); } public static ActionModel createForPersistent(final PageParameters pageParameters) { return new ActionModel(pageParameters); } /** * Factory method for creating {@link PageParameters}. * * see {@link #ActionModel(PageParameters)} */ public static PageParameters createPageParameters( final ObjectAdapter adapter, final ObjectAction objectAction, final ConcurrencyChecking concurrencyChecking) { final PageParameters pageParameters = new PageParameters(); final String oidStr = concurrencyChecking == ConcurrencyChecking.CHECK? adapter.getOid().enString(getOidMarshaller()): adapter.getOid().enStringNoVersion(getOidMarshaller()); PageParameterNames.OBJECT_OID.addStringTo(pageParameters, oidStr); final ActionType actionType = objectAction.getType(); PageParameterNames.ACTION_TYPE.addEnumTo(pageParameters, actionType); final ObjectSpecification actionOnTypeSpec = objectAction.getOnType(); if (actionOnTypeSpec != null) { PageParameterNames.ACTION_OWNING_SPEC.addStringTo(pageParameters, actionOnTypeSpec.getFullIdentifier()); } final String actionId = determineActionId(objectAction); PageParameterNames.ACTION_ID.addStringTo(pageParameters, actionId); return pageParameters; } public static Entry<Integer, String> parse(final String paramContext) { final Pattern compile = Pattern.compile("([^=]+)=(.+)"); final Matcher matcher = compile.matcher(paramContext); if (!matcher.matches()) { return null; } final int paramNum; try { paramNum = Integer.parseInt(matcher.group(1)); } catch (final Exception e) { // ignore return null; } final String oidStr; try { oidStr = matcher.group(2); } catch (final Exception e) { return null; } return new Map.Entry<Integer, String>() { @Override public Integer getKey() { return paramNum; } @Override public String getValue() { return oidStr; } @Override public String setValue(final String value) { return null; } }; } ////////////////////////////////////////////////// // BookmarkableModel ////////////////////////////////////////////////// public PageParameters getPageParameters() { final ObjectAdapter adapter = getTargetAdapter(); final ObjectAction objectAction = getActionMemento().getAction(); final PageParameters pageParameters = createPageParameters( adapter, objectAction, ConcurrencyChecking.NO_CHECK); // capture argument values final ObjectAdapter[] argumentsAsArray = getArgumentsAsArray(); for(ObjectAdapter argumentAdapter: argumentsAsArray) { final String encodedArg = encodeArg(argumentAdapter); PageParameterNames.ACTION_ARGS.addStringTo(pageParameters, encodedArg); } return pageParameters; } @Override public String getTitle() { final ObjectAdapter adapter = getTargetAdapter(); final ObjectAction objectAction = getActionMemento().getAction(); final StringBuilder buf = new StringBuilder(); final ObjectAdapter[] argumentsAsArray = getArgumentsAsArray(); for(ObjectAdapter argumentAdapter: argumentsAsArray) { if(buf.length() > 0) { buf.append(","); } buf.append(abbreviated(titleOf(argumentAdapter), 8)); } return adapter.titleString(null) + "." + objectAction.getName() + (buf.length()>0?"(" + buf.toString() + ")":""); } @Override public boolean hasAsRootPolicy() { return true; } ////////////////////////////////////////////////// // helpers ////////////////////////////////////////////////// private static String titleOf(ObjectAdapter argumentAdapter) { return argumentAdapter!=null?argumentAdapter.titleString(null):""; } private static String abbreviated(final String str, final int maxLength) { return str.length() < maxLength ? str : str.substring(0, maxLength - 3) + "..."; } private static String determineActionId(final ObjectAction objectAction) { final Identifier identifier = objectAction.getIdentifier(); if (identifier != null) { return identifier.toNameParmsIdentityString(); } // fallback (used for action sets) return objectAction.getId(); } public static Mode determineMode(final ObjectAction action) { return action.getParameterCount() > 0 ? Mode.PARAMETERS : Mode.RESULTS; } private final ObjectAdapterMemento targetAdapterMemento; private final ActionMemento actionMemento; private Mode actionMode; /** * Lazily populated in {@link #getArgumentModel(ActionParameterMemento)} */ private Map<Integer, ScalarModel> arguments = Maps.newHashMap(); private ActionExecutor executor; private ActionModel(final PageParameters pageParameters) { this(newObjectAdapterMementoFrom(pageParameters), newActionMementoFrom(pageParameters), actionModeFrom(pageParameters)); setArgumentsIfPossible(pageParameters); setContextArgumentIfPossible(pageParameters); } private static ActionMemento newActionMementoFrom(final PageParameters pageParameters) { final ObjectSpecId owningSpec = ObjectSpecId.of(PageParameterNames.ACTION_OWNING_SPEC.getStringFrom(pageParameters)); final ActionType actionType = PageParameterNames.ACTION_TYPE.getEnumFrom(pageParameters, ActionType.class); final String actionNameParms = PageParameterNames.ACTION_ID.getStringFrom(pageParameters); return new ActionMemento(owningSpec, actionType, actionNameParms); } private static Mode actionModeFrom(PageParameters pageParameters) { final ActionMemento actionMemento = newActionMementoFrom(pageParameters); if(actionMemento.getAction().getParameterCount() == 0) { return Mode.RESULTS; } final List<String> listFrom = PageParameterNames.ACTION_ARGS.getListFrom(pageParameters); return listFrom != null && !listFrom.isEmpty()? Mode.RESULTS: Mode.PARAMETERS; } private static ObjectAdapterMemento newObjectAdapterMementoFrom(final PageParameters pageParameters) { RootOid oid = oidFor(pageParameters); if(oid.isTransient()) { return null; } else { return ObjectAdapterMemento.createPersistent(oid); } } private static RootOid oidFor(final PageParameters pageParameters) { String oidStr = PageParameterNames.OBJECT_OID.getStringFrom(pageParameters); return getOidMarshaller().unmarshal(oidStr, RootOid.class); } private ActionModel(final ObjectAdapterMemento adapterMemento, final ActionMemento actionMemento, final Mode actionMode) { this.targetAdapterMemento = adapterMemento; this.actionMemento = actionMemento; this.actionMode = actionMode; } private void setArgumentsIfPossible(final PageParameters pageParameters) { List<String> args = PageParameterNames.ACTION_ARGS.getListFrom(pageParameters); final ObjectAction action = actionMemento.getAction(); final List<ObjectSpecification> parameterTypes = action.getParameterTypes(); for (int paramNum = 0; paramNum < args.size(); paramNum++) { String encoded = args.get(paramNum); setArgument(paramNum, parameterTypes.get(paramNum), encoded); } } public boolean hasParameters() { return actionMode == ActionModel.Mode.PARAMETERS; } private boolean setContextArgumentIfPossible(final PageParameters pageParameters) { final String paramContext = PageParameterNames.ACTION_PARAM_CONTEXT.getStringFrom(pageParameters); if (paramContext == null) { return false; } final ObjectAction action = actionMemento.getAction(); final List<ObjectSpecification> parameterTypes = action.getParameterTypes(); final int parameterCount = parameterTypes.size(); final Map.Entry<Integer, String> mapEntry = parse(paramContext); final int paramNum = mapEntry.getKey(); if (paramNum >= parameterCount) { return false; } final String encoded = mapEntry.getValue(); setArgument(paramNum, parameterTypes.get(paramNum), encoded); return true; } private void setArgument(final int paramNum, final ObjectSpecification argSpec, final String encoded) { final ObjectAdapter argumentAdapter = decodeArg(argSpec, encoded); setArgument(paramNum, argumentAdapter); } private String encodeArg(ObjectAdapter adapter) { if(adapter == null) { return NULL_ARG; } ObjectSpecification objSpec = adapter.getSpecification(); if(objSpec.isEncodeable()) { EncodableFacet encodeable = objSpec.getFacet(EncodableFacet.class); return encodeable.toEncodedString(adapter); } return adapter.getOid().enStringNoVersion(getOidMarshaller()); } private ObjectAdapter decodeArg(ObjectSpecification objSpec, String encoded) { if(NULL_ARG.equals(encoded)) { return null; } if(objSpec.isEncodeable()) { EncodableFacet encodeable = objSpec.getFacet(EncodableFacet.class); return encodeable.fromEncodedString(encoded); } try { final RootOid oid = RootOidDefault.deStringEncoded(encoded, getOidMarshaller()); return getAdapterManager().adapterFor(oid); } catch (final Exception e) { return null; } } private void setArgument(final int paramNum, final ObjectAdapter argumentAdapter) { final ObjectAction action = actionMemento.getAction(); final ObjectActionParameter actionParam = action.getParameters().get(paramNum); final ActionParameterMemento apm = new ActionParameterMemento(actionParam); final ScalarModel argumentModel = getArgumentModel(apm); argumentModel.setObject(argumentAdapter); } public ScalarModel getArgumentModel(final ActionParameterMemento apm) { int i = apm.getNumber(); ScalarModel scalarModel = arguments.get(i); if (scalarModel == null) { scalarModel = new ScalarModel(targetAdapterMemento, apm); final int number = scalarModel.getParameterMemento().getNumber(); arguments.put(number, scalarModel); } return scalarModel; } public ObjectAdapter getTargetAdapter() { return targetAdapterMemento.getObjectAdapter(getConcurrencyChecking()); } protected ConcurrencyChecking getConcurrencyChecking() { return actionMemento.getConcurrencyChecking(); } public ActionMemento getActionMemento() { return actionMemento; } @Override protected ObjectAdapter load() { // from getObject()/reExecute detach(); // force re-execute // TODO: think we need another field to determine if args have been populated. final ObjectAdapter results = executeAction(); this.actionMode = Mode.RESULTS; return results; } private ObjectAdapter executeAction() { final ObjectAdapter targetAdapter = getTargetAdapter(); final ObjectAdapter[] arguments = getArgumentsAsArray(); final ObjectAction action = getActionMemento().getAction(); // let any exceptions propogate, will be caught by UI layer // (ActionPanel at time of writing) final ObjectAdapter results = action.execute(targetAdapter, arguments); return results; } public String getReasonInvalidIfAny() { final ObjectAdapter targetAdapter = getTargetAdapter(); final ObjectAdapter[] proposedArguments = getArgumentsAsArray(); final ObjectAction objectAction = getActionMemento().getAction(); final Consent validity = objectAction.isProposedArgumentSetValid(targetAdapter, proposedArguments); return validity.isAllowed() ? null : validity.getReason(); } @Override public void setObject(final ObjectAdapter object) { throw new UnsupportedOperationException("target adapter for ActionModel cannot be changed"); } public ObjectAdapter[] getArgumentsAsArray() { if(this.arguments.size() < this.getActionMemento().getAction().getParameterCount()) { primeArgumentModels(); } final ObjectAction objectAction = getActionMemento().getAction(); final ObjectAdapter[] arguments = new ObjectAdapter[objectAction.getParameterCount()]; for (int i = 0; i < arguments.length; i++) { final ScalarModel scalarModel = this.arguments.get(i); arguments[i] = scalarModel.getObject(); } return arguments; } public ActionExecutor getExecutor() { return executor; } public void setExecutor(final ActionExecutor executor) { this.executor = executor; } public void reset() { this.actionMode = determineMode(actionMemento.getAction()); } public void clearArguments() { for (ScalarModel argumentModel : arguments.values()) { argumentModel.reset(); } this.actionMode = determineMode(actionMemento.getAction()); } /** * Bookmarkable if the {@link ObjectAction action} has a {@link BookmarkPolicyFacet bookmark} policy * of {@link BookmarkPolicy#AS_ROOT root}, and has safe {@link ObjectAction#getSemantics() semantics}. */ public boolean isBookmarkable() { final ObjectAction action = getActionMemento().getAction(); final BookmarkPolicyFacet bookmarkPolicy = action.getFacet(BookmarkPolicyFacet.class); final boolean safeSemantics = action.getSemantics() == ActionSemantics.Of.SAFE; return bookmarkPolicy.value() == BookmarkPolicy.AS_ROOT && safeSemantics; } // ////////////////////////////////////// private ActionPrompt actionPrompt; public void setActionPrompt(ActionPrompt actionPrompt) { this.actionPrompt = actionPrompt; } public ActionPrompt getActionPrompt() { return actionPrompt; } // ////////////////////////////////////// public static ApplicationException getApplicationExceptionIfAny(Exception ex) { Iterable<ApplicationException> appEx = Iterables.filter(Throwables.getCausalChain(ex), ApplicationException.class); Iterator<ApplicationException> iterator = appEx.iterator(); return iterator.hasNext() ? iterator.next() : null; } public static IRequestHandler redirectHandler(final Object value) { if(value instanceof java.net.URL) { java.net.URL url = (java.net.URL) value; return new RedirectRequestHandler(url.toString()); } return null; } public static IRequestHandler downloadHandler(final Object value) { if(value instanceof Clob) { return downloadHandler((Clob)value); } if(value instanceof Blob) { return downloadHandler((Blob)value); } return null; } private static IRequestHandler downloadHandler(final Blob blob) { ResourceRequestHandler handler = new ResourceRequestHandler(new ByteArrayResource(blob.getMimeType().toString(), blob.getBytes(), blob.getName()), null); return handler; } private static IRequestHandler downloadHandler(final Clob clob) { ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(new StringResourceStream(clob.getChars(), clob.getMimeType().toString()), clob.getName()); handler.setContentDisposition(ContentDisposition.ATTACHMENT); return handler; } // ////////////////////////////////////// public List<ActionParameterMemento> primeArgumentModels() { final ObjectAction objectAction = getActionMemento().getAction(); final List<ObjectActionParameter> parameters = objectAction.getParameters(); final List<ActionParameterMemento> mementos = buildParameterMementos(parameters); for (final ActionParameterMemento apm : mementos) { getArgumentModel(apm); } return mementos; } private static List<ActionParameterMemento> buildParameterMementos(final List<ObjectActionParameter> parameters) { final List<ActionParameterMemento> parameterMementoList = Lists.transform(parameters, ObjectAdapterMemento.Functions.fromActionParameter()); // we copy into a new array list otherwise we get lazy evaluation = // reference to a non-serializable object return Lists.newArrayList(parameterMementoList); } ////////////////////////////////////////////////// // Dependencies (from context) ////////////////////////////////////////////////// private static OidMarshaller getOidMarshaller() { return IsisContext.getOidMarshaller(); } }
79a121da222634c927c2ad94c56642dc9ab78851
1ed08c0729eb0c59b52afd3e905cc1018ec92e64
/java/DomXml/src/Dom4jTest/Dom4jTest.java
027e43dfd290120433af09d6d11be5355fe1cc0d
[]
no_license
eli01/code_history_area
a23ed0d4f35074b46aa3ea4713076af9b7bc29d7
61aa1243675171e10540c3b6b246ccba0cf97781
refs/heads/master
2016-09-16T03:45:32.632944
2014-02-25T06:45:40
2014-02-25T06:45:40
null
0
0
null
null
null
null
GB18030
Java
false
false
6,709
java
package Dom4jTest; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.dom4j.*; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Dom4jTest { //演示使用dom4j对xml文件进行crud操作 public static void main(String[] args) throws Exception { // TODO Auto-generated method stub //1.得到解析器 SAXReader saxReader=new SAXReader(); //2指定解析哪个xml文件 Document document=saxReader.read(new File("src/Dom4jTest/Dom4jXml.xml")); list(document.getRootElement());//得到根元素. //read(document); //add(document); //del(document); //update(document); //addByIndex(document); } //添加一个元素到指定位置( 林冲到 卢俊义后,在武松前) public static void addByIndex(Document document) throws Exception{ //创建一个元素 Element newHero=DocumentHelper.createElement("学生"); newHero.setText("林冲"); //得到所有学生的list List allHeros=document.getRootElement().elements("学生"); for(int i=0;i<allHeros.size();i++){ //取出各个人的名 Element name=((Element)allHeros.get(i)).element("名字"); if(name.getText().equals("卢俊义")){ //System.out.println("发现 "+i); allHeros.add(i+1, newHero); break; } } //allHeros.add(1,newHero); //更新 //直接输出会出现中文乱码: OutputFormat output=OutputFormat.createPrettyPrint(); output.setEncoding("utf-8");//输出的编码utf-8 //把我们的xml文件更新 // lets write to a file //new FileOutputStream(new File("src/myClass.xml")) XMLWriter writer = new XMLWriter( new FileOutputStream(new File("src/com/dom4j/test/myclasses3.xml")) /*new FileWriter( "src/com/dom4j/test/myclasses3.xml" )*/,output ); writer.write( document ); writer.close(); } //更新元素(要求把所有学生的年龄+3) public static void update(Document document ) throws Exception{ //得到所有学生的年龄 List<Element> stus =document.getRootElement().elements("学生"); for(Element el:stus){ //从el中取出年龄 Element age=el.element("年龄"); age.setText((Integer.parseInt(age.getText())+3)+""); Element name=el.element("名字"); //name.setAttributeValue("别名", "hello,world"); name.addAttribute("别名2", "okok"); } //更新 //直接输出会出现中文乱码: OutputFormat output=OutputFormat.createPrettyPrint(); output.setEncoding("utf-8");//输出的编码utf-8 //把我们的xml文件更新 // lets write to a file //new FileOutputStream(new File("src/myClass.xml")) XMLWriter writer = new XMLWriter( new FileOutputStream(new File("src/com/dom4j/test/myclasses3.xml")) /*new FileWriter( "src/com/dom4j/test/myclasses3.xml" )*/,output ); writer.write( document ); writer.close(); } //删除元素(要求:删除第一个学生) public static void del(Document document) throws Exception{ //找到该元素 Element stu1=document.getRootElement().element("学生").element("名字"); //删除元素 ///stu1.getParent().remove(stu1); //删除元素的某个属性 stu1.remove(stu1.attribute("别名")); //更新xml //直接输出会出现中文乱码: OutputFormat output=OutputFormat.createPrettyPrint(); output.setEncoding("utf-8");//输出的编码utf-8 //把我们的xml文件更新 // lets write to a file //new FileOutputStream(new File("src/myClass.xml")) XMLWriter writer = new XMLWriter( new FileOutputStream(new File("src/com/dom4j/test/myclasses3.xml")) /*new FileWriter( "src/com/dom4j/test/myclasses3.xml" )*/,output ); writer.write( document ); writer.close(); } //添加元素(要求: 添加一个学生到xml中) public static void add(Document docment) throws Exception{ //首先我们来创建一个学生节点对象 Element newStu=DocumentHelper.createElement("学生"); Element newStu_name=DocumentHelper.createElement("名字"); //如何给元素添加属性 newStu_name.addAttribute("别名", "江江"); newStu_name.setText("宋江"); Element newStu_age=DocumentHelper.createElement("年龄"); Element newStu_intro=DocumentHelper.createElement("介绍"); //把三个子元素(节点)加到 newStu下 newStu.add(newStu_name); newStu.add(newStu_age); newStu.add(newStu_intro); //再把newStu节点加到根元素 docment.getRootElement().add(newStu); //直接输出会出现中文乱码: OutputFormat output=OutputFormat.createPrettyPrint(); output.setEncoding("utf-8");//输出的编码utf-8 //把我们的xml文件更新 // lets write to a file //new FileOutputStream(new File("src/myClass.xml")) XMLWriter writer = new XMLWriter( new FileOutputStream(new File("src/Dom4jTest/Dom4jXml.xml")) /*new FileWriter( "src/com/dom4j/test/myclasses3.xml" )*/,output ); writer.write( docment ); writer.close(); } //如何指定读取某个元素(要求 :读取第一个学生的信息,) public static void read(Document docment){ //得到根元素 Element root=docment.getRootElement(); //root.elements("学生") :表示取出 root元素 下的所有学生元素 //root.element("学生") :表示取出 root元素 下的第一个学生元素 //root.elements("学生").get(0) : 表示取出 root元素 下的第一个学生元素 Element stu= (Element) root.elements("学生").get(0); Element stu_name=stu.element("名字"); System.out.println(stu_name.getText()+" 别名 "+stu_name.attributeValue("别名")); //System.out.println(((Element)stu.elements("名字").get(0)).getText()); //看看下面的代码是否能够(跨层取XXXXX) //Element stu2= (Element) root.elements("名字").get(0);//==>xpath //System.out.println(root.elements("名字").size()); //如果使用xpath,取出第一个学生 Element stu2=(Element) docment.selectSingleNode("/班级/学生[1]"); } //遍历我们的xml文件 public static void list(Element element){ System.out.println(element.getName()+element.getTextTrim()); Iterator iterator=element.elementIterator(); while(iterator.hasNext()){ Element e=(Element) iterator.next(); //递归 list(e); } } }
e9776ee2974b297f9441dc01cc55b71bcd4e3d13
e112d821f46bcc1ce24cfeaabe886f6093f9f4b9
/src/main/java/com/FizzBuzz/FizzBuzzStrategy.java
dc753f3647d1d57a8309821ca21799f40f20e771
[]
no_license
geekOramon/fizz-buzz-service
b1f097cffd9fb03710ce270636fe1e543d888c19
975cf58bcdbff99aacf4843a7245b3253ea8b20c
refs/heads/master
2021-01-25T07:40:50.211493
2017-06-12T09:44:06
2017-06-12T09:44:06
93,652,047
0
0
null
null
null
null
UTF-8
Java
false
false
541
java
package com.FizzBuzz; /** * Created by vasilis on 19-5-17. */ public class FizzBuzzStrategy implements RulePrintStrategy { public static final Integer FIZZ_BUZZ_VALUE = 15; public static final String FIZZ_BUZZ_STR = "fizzbuzz"; public boolean strategyApplies(Integer value) { boolean result = false; if(Math.floorMod(value, FIZZ_BUZZ_VALUE) == 0){ result = true; } return result; } public String printResponse(Integer givenNumber) { return FIZZ_BUZZ_STR; } }
f2ff01e7e084a04ee886f640465359289a422bac
129f58086770fc74c171e9c1edfd63b4257210f3
/src/testcases/CWE23_Relative_Path_Traversal/CWE23_Relative_Path_Traversal__URLConnection_09.java
359fa8a9498f10d40c6f4aed0f14d0ce1a6c8000
[]
no_license
glopezGitHub/Android23
1bd0b6a6c7ce3c7439a74f1e4dcef2c4c0fac4ba
6215d0684c4fbdc7217ccfbedfccfca69824cc5e
refs/heads/master
2023-03-07T15:14:59.447795
2023-02-06T13:59:49
2023-02-06T13:59:49
6,856,387
0
3
null
2023-02-06T18:38:17
2012-11-25T22:04:23
Java
UTF-8
Java
false
false
14,771
java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE23_Relative_Path_Traversal__URLConnection_09.java Label Definition File: CWE23_Relative_Path_Traversal.label.xml Template File: sources-sink-09.tmpl.java */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: URLConnection Read data from a web server with URLConnection * GoodSource: A hardcoded string * BadSink: readFile no validation * Flow Variant: 09 Control flow: if(IO.static_final_t) and if(IO.static_final_f) * * */ package testcases.CWE23_Relative_Path_Traversal; import testcasesupport.*; import java.io.*; import javax.servlet.http.*; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.Level; import java.util.logging.Logger; public class CWE23_Relative_Path_Traversal__URLConnection_09 extends AbstractTestCase { /* uses badsource and badsink */ public void bad() throws Throwable { String data; if(IO.static_final_t) { data = ""; /* Initialize data */ /* read input from URLConnection */ { URLConnection conn = (new URL("http://www.example.org/")).openConnection(); BufferedReader buffread = null; InputStreamReader instrread = null; try { instrread = new InputStreamReader(conn.getInputStream(), "UTF-8"); buffread = new BufferedReader(instrread); /* POTENTIAL FLAW: Read data from a web server with URLConnection */ data = buffread.readLine(); // This will be reading the first "line" of the response body, // which could be very long if there are no newlines in the HTML } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error with stream reading", ioe); } finally { /* clean up stream reading objects */ try { if( buffread != null ) { buffread.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", ioe); } try { if( instrread != null ) { instrread.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", ioe); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ /* FIX: Use a hardcoded string */ data = "foo"; } String root = "C:\\uploads\\"; if (data != null) { /* POTENTIAL FLAW: no validation of concatenated value */ File fIn = new File(root + data); FileInputStream fisSink = null; InputStreamReader isreadSink = null; BufferedReader buffreadSink = null; if( fIn.exists() && fIn.isFile() ) { try { fisSink = new FileInputStream(fIn); isreadSink = new InputStreamReader(fisSink, "UTF-8"); buffreadSink = new BufferedReader(isreadSink); IO.writeLine(buffreadSink.readLine()); } catch ( IOException ioe ) { IO.logger.log(Level.WARNING, "Error with stream reading", ioe); } finally { /* Close stream reading objects */ try { if( buffreadSink != null ) { buffreadSink.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", ioe); } try { if( isreadSink != null ) { isreadSink.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", ioe); } try { if( fisSink != null ) { fisSink.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", ioe); } } } } } /* goodG2B1() - use goodsource and badsink by changing IO.static_final_t to IO.static_final_f */ private void goodG2B1() throws Throwable { String data; if(IO.static_final_f) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ data = ""; /* Initialize data */ /* read input from URLConnection */ { URLConnection conn = (new URL("http://www.example.org/")).openConnection(); BufferedReader buffread = null; InputStreamReader instrread = null; try { instrread = new InputStreamReader(conn.getInputStream(), "UTF-8"); buffread = new BufferedReader(instrread); /* POTENTIAL FLAW: Read data from a web server with URLConnection */ data = buffread.readLine(); // This will be reading the first "line" of the response body, // which could be very long if there are no newlines in the HTML } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error with stream reading", ioe); } finally { /* clean up stream reading objects */ try { if( buffread != null ) { buffread.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", ioe); } try { if( instrread != null ) { instrread.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", ioe); } } } } else { /* FIX: Use a hardcoded string */ data = "foo"; } String root = "C:\\uploads\\"; if (data != null) { /* POTENTIAL FLAW: no validation of concatenated value */ File fIn = new File(root + data); FileInputStream fisSink = null; InputStreamReader isreadSink = null; BufferedReader buffreadSink = null; if( fIn.exists() && fIn.isFile() ) { try { fisSink = new FileInputStream(fIn); isreadSink = new InputStreamReader(fisSink, "UTF-8"); buffreadSink = new BufferedReader(isreadSink); IO.writeLine(buffreadSink.readLine()); } catch ( IOException ioe ) { IO.logger.log(Level.WARNING, "Error with stream reading", ioe); } finally { /* Close stream reading objects */ try { if( buffreadSink != null ) { buffreadSink.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", ioe); } try { if( isreadSink != null ) { isreadSink.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", ioe); } try { if( fisSink != null ) { fisSink.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", ioe); } } } } } /* goodG2B2() - use goodsource and badsink by reversing statements in if */ private void goodG2B2() throws Throwable { String data; if(IO.static_final_t) { /* FIX: Use a hardcoded string */ data = "foo"; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ data = ""; /* Initialize data */ /* read input from URLConnection */ { URLConnection conn = (new URL("http://www.example.org/")).openConnection(); BufferedReader buffread = null; InputStreamReader instrread = null; try { instrread = new InputStreamReader(conn.getInputStream(), "UTF-8"); buffread = new BufferedReader(instrread); /* POTENTIAL FLAW: Read data from a web server with URLConnection */ data = buffread.readLine(); // This will be reading the first "line" of the response body, // which could be very long if there are no newlines in the HTML } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error with stream reading", ioe); } finally { /* clean up stream reading objects */ try { if( buffread != null ) { buffread.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", ioe); } try { if( instrread != null ) { instrread.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", ioe); } } } } String root = "C:\\uploads\\"; if (data != null) { /* POTENTIAL FLAW: no validation of concatenated value */ File fIn = new File(root + data); FileInputStream fisSink = null; InputStreamReader isreadSink = null; BufferedReader buffreadSink = null; if( fIn.exists() && fIn.isFile() ) { try { fisSink = new FileInputStream(fIn); isreadSink = new InputStreamReader(fisSink, "UTF-8"); buffreadSink = new BufferedReader(isreadSink); IO.writeLine(buffreadSink.readLine()); } catch ( IOException ioe ) { IO.logger.log(Level.WARNING, "Error with stream reading", ioe); } finally { /* Close stream reading objects */ try { if( buffreadSink != null ) { buffreadSink.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing BufferedReader", ioe); } try { if( isreadSink != null ) { isreadSink.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing InputStreamReader", ioe); } try { if( fisSink != null ) { fisSink.close(); } } catch( IOException ioe ) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", ioe); } } } } } public void good() throws Throwable { goodG2B1(); goodG2B2(); } /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
0609e9400a38074e15667e37255f357c91e67e2b
9d02defbe04cc956cb4257aab1c0b6b62fea73d9
/src/main/java/com/miz/study/ch2/calc/BufferedReaderCallback.java
48fe5ca7cab5787e4872e8a7a066086b777d21ed
[]
no_license
mizm/spring-study
28da03f54ee5acdd08f8041efb014e40f62ecf2f
a78e3a606b693a5e47c78c6a2d37ad7a98c48f07
refs/heads/main
2023-05-10T15:19:12.467219
2021-06-11T15:27:32
2021-06-11T15:27:32
344,476,422
1
0
null
null
null
null
UTF-8
Java
false
false
210
java
package com.miz.study.ch2.calc; import java.io.BufferedReader; import java.io.IOException; public interface BufferedReaderCallback { Integer doSomethingWithReader(BufferedReader br) throws IOException; }
113945f3b14af8bed37db278de9d4bd7129ba714
96690d034d9e3d655576cc50cfe35a49d375a0ab
/OurMarket/src/ourmarket/webSocket/package-info.java
20bdcb7f6a9f8d23db3c5e929a66bb1b692efe7a
[]
no_license
yd-moon/OurMarket
2c9b001ab216916a53af42d6d618bc5ec348062f
a5bd997d0e4f783a93b0f6c89395a23a7f587f99
refs/heads/master
2021-08-23T08:53:42.163672
2017-12-04T11:29:16
2017-12-04T11:29:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
75
java
/** * */ /** * @author 16558 * */ package ourmarket.webSocket;
7264ccf346825a171e1687e9934b60735511c33a
6ff288cd7750b126fc70eaf9f68aa18535e535f7
/src/main/java/com/ssm/dao/UserRepositoryByName.java
184fd8946aee18f4775ba952f20f9a8999c8f8ab
[]
no_license
WillnessLiar/mymaven
18878a9eb210e1fbfc988d6e7d7358a88413a349
f96d4e5d77f73574cf86c2457b596d654b186143
refs/heads/master
2022-07-01T04:46:44.270268
2020-03-15T15:10:34
2020-03-15T15:10:34
200,242,444
0
0
null
2022-06-21T01:35:31
2019-08-02T13:48:40
JavaScript
UTF-8
Java
false
false
382
java
//package com.ssm.dao; // //import com.ssm.po.User; //import org.springframework.data.repository.Repository; // //import java.util.List; // // //public interface UserRepositoryByName extends Repository<User,Integer> { // //// 方法的名称必须要遵循驼峰状命名规则,findBy(关键字)+属性名称+查询条件 // public List<User>findByName(String name); // //}
26d89585c85a83e922de4c4546f22bd1928f09da
e9054b26017c0948ea4806ea7422996af4e9c8ba
/src/main/java/com/mmall/controller/portal/ProductController.java
889173a4899b158279ea176df8fa00ff4b93d6da
[]
no_license
NeoSuzipeng/mmal_su
93d3048c92570faad96a0575510bd6b585b92f93
faca66ba98037cecccda3d1b288c4f951bb3096c
refs/heads/master
2021-05-14T19:22:33.041317
2018-07-09T16:21:35
2018-07-09T16:21:35
116,106,568
1
0
null
null
null
null
UTF-8
Java
false
false
2,204
java
package com.mmall.controller.portal; import com.github.pagehelper.PageInfo; import com.mmall.common.ServerResponse; import com.mmall.pojo.Product; import com.mmall.service.IProductService; import com.mmall.vo.ProductDetailVo; import com.mmall.vo.ProductListVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /** * Created by 10353 on 2018/1/5. * 商品管理模块 * 1.产品搜索(动态排序) * 2.产品详情 */ @Controller @RequestMapping(value = "/product/") public class ProductController { @Autowired private IProductService iProductService; /** * 产品详情 * @param productId * @return */ @RequestMapping(value = "detail.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<ProductDetailVo> getProductDetail(Integer productId){ return iProductService.getProductDetail(productId); } /** * 产品搜索(动态排序) * @param categoryId * @param keyword * @param pageNum * @param pageSize * @param orderBy * @return */ @RequestMapping(value = "list.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<PageInfo> getProductList(@RequestParam(value = "categoryId", required = false) Integer categoryId, @RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, @RequestParam(value = "orderBy", defaultValue = "") String orderBy){ return iProductService.getProductList(categoryId, keyword, pageNum, pageSize, orderBy); } }
97041ed445863afd4d524073a743749437dffa23
a2ffc9252fb6d478b45e3ba3a7a92d964f3b216d
/APCS-Karel-Unit-1-SOLUTIONS/Karel-Conditional Harvester-SOLUTION/HurdleRunner.java
c5fd2beca9eab5d8d0859458764c6319454ea34c
[]
no_license
MasonDS4/APCS-A-CH-0-Karel
518c6f378c1a9828d95be8141d5737f3703f1f18
616c0ea377436bb6f74b10df8d1f57b2f92493bf
refs/heads/master
2021-03-12T19:27:49.463313
2017-09-05T19:17:20
2017-09-05T19:17:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
607
java
import kareltherobot.*; import java.awt.Color; /** * @author : * teacher : * due date: */ public class HurdleRunner implements Directions { public static void main(String [] args) { Hurdler karel = new Hurdler(1, 1, East, 0); karel.runRace(); karel.turnOff(); } static { World.reset(); World.readWorld("fig5-2.kwld"); World.setBeeperColor(Color.magenta); World.setStreetColor(Color.blue); World.setNeutroniumColor(Color.green.darker()); World.setDelay(10); World.setVisible(true); } }
0bbc0be94b7ab24ada3665f885d0227cc4a63e51
9019dadbcb6dbc57272182e9f0d04cb4793ecbc9
/robobinding/src/test/java/org/robobinding/viewattribute/listview/SetCheckedItemPositionsAttributeTest.java
d18428d018151c42fb9295e0962a8c084654d159
[ "Apache-2.0" ]
permissive
romanlum/RoboBinding
fdbb855581195a8f5694f6fc4d8c76f914e111d9
570274320d0119db09c8e3d1224b6bfa3aff7139
refs/heads/master
2021-01-12T21:53:30.678186
2013-09-25T10:19:54
2013-09-25T10:19:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,135
java
/** * Copyright 2012 Cheng Wei, Robert Taylor * * 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.robobinding.viewattribute.listview; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.robobinding.property.ValueModel; import org.robobinding.viewattribute.listview.CheckedItemPositionsAttribute.SetCheckedItemPositionsAttribute; import android.widget.ListView; import com.google.common.collect.Sets; /** * * @since 1.0 * @version $Revision: 1.0 $ * @author Cheng Wei */ public class SetCheckedItemPositionsAttributeTest extends AbstractCheckedItemPositionsAttributeTest<ListView, SetCheckedItemPositionsAttribute> { private Set<Integer> checkedItemPositions; @Before public void setUp() { super.setUp(); checkedItemPositions = SparseBooleanArrayUtils.toSet(anySparseBooleanArray()); } @Test public void whenValueModelUpdated_thenViewShouldReflectChanges() { attribute.valueModelUpdated(checkedItemPositions); assertThat(SparseBooleanArrayUtils.toSet(view.getCheckedItemPositions()), equalTo(checkedItemPositions)); } @Test public void whenCheckedItemPositionChanged_thenValueModelUpdatedAccordingly() { @SuppressWarnings({ "unchecked", "rawtypes" }) ValueModel<Set<Integer>> valueModel = (ValueModel) twoWayBindToProperty(Set.class, Sets.newHashSet()); setItemsChecked(checkedItemPositions); assertThat(valueModel.getValue(), equalTo(checkedItemPositions)); } }
c97d9d7c4421db32424515f88495ded0aedc4357
9ddf18ce8eb14782a53926643b6f4de4649671c5
/src/main/java/com/june/app/dao/UserDao.java
9f834a2a260561013d1098277baa257637aa90a4
[]
no_license
taerimmk/springbook_maven
cd0e34ada57a537deef5be0630b3cc6406bd48c0
8777f445d71446102da388042761d7536381cef7
refs/heads/master
2020-04-06T00:33:30.445382
2013-01-07T09:21:53
2013-01-07T09:21:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,041
java
package com.june.app.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.june.app.domain.User; public class UserDao { private ConnectionMaker connectionMaker; public UserDao(){ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DaoFactory.class); this.connectionMaker = context.getBean("connectionMaker", ConnectionMaker.class); } /*public UserDao(){ DaoFactory daoFactory = new DaoFactory(); this.connectionMaker = daoFactory.connectionMaker(); }*/ public void add(User user) throws ClassNotFoundException, SQLException { Connection c = connectionMaker.makeConnection(); PreparedStatement ps = c .prepareStatement("insert into users(id, name, password) values (?,?,?)"); ps.setString(1, user.getId()); ps.setString(2, user.getName()); ps.setString(3, user.getPassword()); ps.executeUpdate(); ps.close(); c.close(); } public User get(String id) throws ClassNotFoundException, SQLException { Connection c = connectionMaker.makeConnection(); PreparedStatement ps = c .prepareStatement("select * from users where id = ?"); ps.setString(1, id); ResultSet rs = ps.executeQuery(); rs.next(); User user = new User(); user.setId(rs.getString("id")); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); rs.close(); ps.close(); c.close(); return user; } //public abstract Connection getConnection() throws ClassNotFoundException,SQLException; /*public class NUserDao extends UserDao { public Connection getConnection()throws ClassNotFoundException, SQLException { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection c = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "mindware", "2101"); return c; } }*/ }
bc3a4cb3a7e5f62d6054e7a91a07509a6b4de337
532a04c573b41450935078d47106b19b938d5d95
/src/Homework/Homework1/Task3.java
7a6483b87027514bb944aab1038e827a1ef71e00
[]
no_license
SvetikM/Homework
ed1fb42921e4216cd6898bff9de6f81f6c033253
8be3d00f0a2583ff8c3673e82d691b15f19233a0
refs/heads/master
2020-05-24T08:09:20.663336
2019-06-24T14:41:09
2019-06-24T14:41:09
187,178,749
0
0
null
2019-06-24T14:41:41
2019-05-17T08:34:27
Java
UTF-8
Java
false
false
1,435
java
package Homework.Homework1; import java.util.Scanner; // Группа людей участвует в марафоне, их имена и время за которое они пробежали марафон вы можете увидеть ниже. public class Task3 { public static void main(String[] args) { String[] names = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex", "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate"}; int[] time = {341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265}; for (int i = names.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (time[j] > time[j + 1]) { int tempTime = time[j]; time[j] = time[j + 1]; time[j + 1] = tempTime; String tempName = names[j]; names[j] = names[j + 1]; names[j + 1] = tempName; } } } for (int i = 0; i < names.length; ) { System.out.printf("name: %s time: %d \n", names[i], time[i]); i++; } Scanner in1 = new Scanner(System.in); System.out.print("Input a number of place: "); int place = in1.nextInt(); System.out.printf("name: %s time: %d \n", names[place - 1], time[place - 1]); } }
394d7c4803382422b626c7b319a264b4ddc0a46d
1fa669c04e6bc9b3a3c77a4555e7a5e25857aefa
/StoreAverage.java
190d7608b0929d01c1bfebc56648919b0377c706
[]
no_license
VashishthSingh/MajPro
e04a8b19263c3081c219c63bc211f30db99025ff
1b5bdb231d23851690ec726df353bffea05c727a
refs/heads/master
2020-12-23T14:39:53.719462
2020-01-30T09:38:13
2020-01-30T09:38:13
237,180,908
0
0
null
null
null
null
UTF-8
Java
false
false
2,923
java
package com.clientserver.program; import java.sql.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.concurrent.TimeUnit; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; public class StoreAverage { public static void main(String []args){ float ramAverage=0.0f,diskAverage=0.0f,cpuAverage=0.0f; try{ while(true) { // 1. Registering the Driver Class.forName("com.mysql.jdbc.Driver"); // 2. Creating connection between java code and database Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/report?useSSL=false","root","password"); // 3. Creating statement Statement stmt=(Statement) con.createStatement(); Statement stmt1=(Statement) con.createStatement(); LocalDateTime currentDateTtime = LocalDateTime.now(); // getting system current date and time LocalDateTime startingTime = currentDateTtime.minusSeconds(60); //setting start range DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); String str=formatter.format(startingTime); startingTime=LocalDateTime.parse(str, formatter); LocalDateTime endingTime=startingTime.plusSeconds(59); //setting end range // 4. Executing query // Calculating average of reading ResultSet rs = stmt.executeQuery("select avg(ramUti),avg(diskUti),avg(cpuUti),count(ramUti) from storePercentData"+" where redDateTime>='"+startingTime+"' and redDateTime<='"+endingTime+"'"); rs.next(); // Getting averages ramAverage=rs.getFloat(1); diskAverage=rs.getFloat(2); cpuAverage=rs.getFloat(3); // Storing the averages up to 4 decimal place ramAverage=(float) (Math.round(ramAverage * 10000.0) / 10000.0); diskAverage=(float) (Math.round(diskAverage * 10000.0) / 10000.0); cpuAverage=(float) (Math.round(cpuAverage * 10000.0) / 10000.0); // Inserting average value to the Mean Table stmt1.executeUpdate("insert into storePercentMeanData(ramUti,diskUti,cpuUti,redDateTime)values("+ramAverage+","+diskAverage+","+cpuAverage+",'"+startingTime+"')"); DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // Printing output on console System.out.println(ramAverage+" "+diskAverage+" "+cpuAverage+" "+formatter1.format(startingTime)+" "+formatter1.format(endingTime)); // 5. Closing the connection con.close(); stmt.close(); stmt1.close(); rs.close(); try{TimeUnit.SECONDS.sleep(60);} catch(InterruptedException E){System.out.println(E);} }//end of while }//end of try catch(Exception e){ System.out.println("Exception"); System.out.println(e); } }//end of main function }//end of class
e16524cb87d79299fb9bf921bb221e2904579a2b
1fdd9f8d783fdeadbeeee4c2e27718e6c2f673d9
/day4/代码/day4/src/polymorphic/inte/Dog.java
bf0e77e18900eef1d09a7117b93826ad9f6ff70d
[]
no_license
ywz147258/mnuSE1802
c4b8eb92cb7457f6d41b384168c8208711fc2841
1c2e406f2d9d901b1e7f87a999c41fa70f87b556
refs/heads/main
2023-08-24T05:06:43.922825
2021-10-19T01:43:54
2021-10-19T01:43:54
406,188,734
0
0
null
null
null
null
UTF-8
Java
false
false
186
java
package polymorphic.inte; import polymorphic.clas.Pet; public class Dog implements PetI { @Override public void health() { System.out.println("给狗看病"); } }
d28d0beab4cc8cef74fe8878cf0a5e39e989dfe4
405069ebae83ae104716d23a6ef5e30deb5465e3
/manager/src/main/java/com/wu/manager/pojo/User.java
872a7dc9f45e616826bc50d706e417b53adace42
[]
no_license
WuRuoHui/iosbbs
4b2106cdadc630963e4c4cd5e290a20980fb85b4
1a9489f0552d1c64e0b2ee34e67537dc40206335
refs/heads/master
2022-06-23T13:17:41.991402
2020-04-06T13:40:58
2020-04-06T13:40:58
231,938,142
1
0
null
2022-06-21T02:50:28
2020-01-05T15:35:12
Java
UTF-8
Java
false
false
1,191
java
package com.wu.manager.pojo; import lombok.Data; import lombok.ToString; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.ArrayList; import java.util.Collection; import java.util.List; @ToString @Data public class User implements UserDetails { private Integer id; private String username; private String password; private Long gmtCreate; private Long gmtModified; private String avatarUrl; private Integer vipLevel; private String vipName; private Boolean status; private String name; private Integer sex; private String description; private List<Role> roleList = new ArrayList(); @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return roleList; } }
7d56b9cdc1e235d6b72c6fe74494cada78225aba
70219c8e6cfd29fce57235aab5513aa1cc1226b8
/src/com/owncloud/android/operations/SynchronizeFolderOperation.java
823a36ebdfc063a19af95adbbd1a156bc15bd894
[]
no_license
tallship/android
4f45d9436ac41164973af1da6d82cf13c9509dd7
405e801bf6a3271bc475b485b367a2904e44f3ad
refs/heads/master
2021-01-24T01:28:23.326626
2012-11-08T09:09:47
2012-11-08T09:09:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,510
java
/* ownCloud Android client application * Copyright (C) 2012 Bartek Przybylski * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.owncloud.android.operations; import java.util.List; import java.util.Vector; import org.apache.http.HttpStatus; import org.apache.jackrabbit.webdav.MultiStatus; import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; import android.accounts.Account; import android.content.Context; import android.content.Intent; import android.util.Log; import com.owncloud.android.datamodel.DataStorageManager; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.files.services.FileDownloader; import com.owncloud.android.files.services.FileObserverService; import eu.alefzero.webdav.WebdavClient; import eu.alefzero.webdav.WebdavEntry; import eu.alefzero.webdav.WebdavUtils; /** * Remote operation performing the synchronization a the contents of a remote folder with the local database * * @author David A. Velasco */ public class SynchronizeFolderOperation extends RemoteOperation { private static final String TAG = SynchronizeFolderOperation.class.getSimpleName(); /** Remote folder to synchronize */ private String mRemotePath; /** Timestamp for the synchronization in progress */ private long mCurrentSyncTime; /** Id of the folder to synchronize in the local database */ private long mParentId; /** Access to the local database */ private DataStorageManager mStorageManager; /** Account where the file to synchronize belongs */ private Account mAccount; /** Android context; necessary to send requests to the download service; maybe something to refactor */ private Context mContext; /** Files and folders contained in the synchronized folder */ private List<OCFile> mChildren; public SynchronizeFolderOperation( String remotePath, long currentSyncTime, long parentId, DataStorageManager dataStorageManager, Account account, Context context ) { mRemotePath = remotePath; mCurrentSyncTime = currentSyncTime; mParentId = parentId; mStorageManager = dataStorageManager; mAccount = account; mContext = context; } /** * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete. * * @return List of files and folders contained in the synchronized folder. */ public List<OCFile> getChildren() { return mChildren; } @Override protected RemoteOperationResult run(WebdavClient client) { RemoteOperationResult result = null; // code before in FileSyncAdapter.fetchData PropFindMethod query = null; try { Log.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath); // remote request query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath)); int status = client.executeMethod(query); // check and process response - /// TODO take into account all the possible status per child-resource if (isMultiStatus(status)) { MultiStatus resp = query.getResponseBodyAsMultiStatus(); // synchronize properties of the parent folder, if necessary if (mParentId == DataStorageManager.ROOT_PARENT_ID) { WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath()); OCFile parent = fillOCFile(we); parent.setParentId(mParentId); mStorageManager.saveFile(parent); mParentId = parent.getFileId(); } // read contents in folder List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1); for (int i = 1; i < resp.getResponses().length; ++i) { WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath()); OCFile file = fillOCFile(we); file.setParentId(mParentId); OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath()); if (oldFile != null) { if (oldFile.keepInSync() && file.getModificationTimestamp() > oldFile.getModificationTimestamp()) { disableObservance(file); // first disable observer so we won't get file upload right after download requestContentDownload(file); } file.setKeepInSync(oldFile.keepInSync()); } updatedFiles.add(file); } // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed) mStorageManager.saveFiles(updatedFiles); // removal of obsolete files mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId)); OCFile file; String currentSavePath = FileDownloader.getSavePath(mAccount.name); for (int i=0; i < mChildren.size(); ) { file = mChildren.get(i); if (file.getLastSyncDate() != mCurrentSyncTime) { Log.d(TAG, "removing file: " + file); mStorageManager.removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath))); mChildren.remove(i); } else { i++; } } } else { client.exhaustResponse(query.getResponseBodyAsStream()); } // prepare result object result = new RemoteOperationResult(isMultiStatus(status), status); Log.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage()); } catch (Exception e) { result = new RemoteOperationResult(e); Log.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException()); } finally { if (query != null) query.releaseConnection(); // let the connection available for other methods } return result; } public boolean isMultiStatus(int status) { return (status == HttpStatus.SC_MULTI_STATUS); } /** * Creates and populates a new {@link OCFile} object with the data read from the server. * * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder). * @return New OCFile instance representing the remote resource described by we. */ private OCFile fillOCFile(WebdavEntry we) { OCFile file = new OCFile(we.decodedPath()); file.setCreationTimestamp(we.createTimestamp()); file.setFileLength(we.contentLength()); file.setMimetype(we.contentType()); file.setModificationTimestamp(we.modifiedTimesamp()); file.setLastSyncDate(mCurrentSyncTime); return file; } /** * Request to stop the observance of local updates for a file. * * @param file OCFile representing the remote file to stop to monitor for local updates */ private void disableObservance(OCFile file) { Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath()); Intent intent = new Intent(mContext, FileObserverService.class); intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE); intent.putExtra(FileObserverService.KEY_CMD_ARG, file.getRemotePath()); mContext.startService(intent); } /** * Requests a download to the file download service * * @param file OCFile representing the remote file to download */ private void requestContentDownload(OCFile file) { Intent intent = new Intent(mContext, FileDownloader.class); intent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount); intent.putExtra(FileDownloader.EXTRA_FILE, file); mContext.startService(intent); } }
7fa842ca7246fb141dd937a7bca54606164fb17c
98822611424ce2c5980ee2c361aca3930b4a82ef
/modules/src/main/java/com/grimaldo/functional/example/_03_immutable/immutable/ImmutablePerson.java
11f118d259df9a7a57c06e7cef6fc9ff716cbded
[]
no_license
paulgrimaldo/java-functional-programming-examples
636031900fc3e630ec41e5260c694347ec3a3536
bb0e6cf37f5a041d7265c95562d4055cb9bf4558
refs/heads/master
2022-10-02T06:41:00.695344
2020-06-07T08:54:50
2020-06-07T08:54:50
270,248,663
0
0
null
null
null
null
UTF-8
Java
false
false
1,399
java
package com.grimaldo.functional.example._03_immutable.immutable; import java.util.LinkedList; import java.util.List; /** * Clase final de nuestro diseño. * * Cuenta con mas de una mejora: * * 1. Es final, asi nadie puede extender de ella. No mas suplantaciones * 2. Las propiedades son finales, una vez creado un objeto no puede mutar * 3. El constructor exige todas las propiedades para generar un objeto * (podria incluso generarse un builder derivado de este constructor) * 4. Cuando se accede a los emails, se quenera una copia! no se envia la lista mutable! */ public final class ImmutablePerson { private final String firstName; private final String lastName; private final List<String> emails; public ImmutablePerson(String firstName, String lastName, List<String> emails) { this.firstName = firstName; this.lastName = lastName; this.emails = emails; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public final List<String> getEmails() { return new LinkedList<>(emails); } @Override public String toString() { return "ImmutablePerson{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", emails=" + emails + '}'; } }
3a87450644c357b727fde70a7eeacc0497b7b263
d16f17f3b9d0aa12c240d01902a41adba20fad12
/src/leetcode/leetcode19xx/leetcode1921/SolutionTest.java
ee89f2a65ffd1e10fe1e8d72a3f3da16d814060f
[]
no_license
redsun9/leetcode
79f9293b88723d2fd123d9e10977b685d19b2505
67d6c16a1b4098277af458849d352b47410518ee
refs/heads/master
2023-06-23T19:37:42.719681
2023-06-09T21:11:39
2023-06-09T21:11:39
242,967,296
38
3
null
null
null
null
UTF-8
Java
false
false
645
java
package leetcode.leetcode19xx.leetcode1921; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class SolutionTest { @Test void test1() { int[] dist = {1, 3, 4}, speed = {1, 1, 1}; assertEquals(3, new Solution().eliminateMaximum(dist, speed)); } @Test void test2() { int[] dist = {1, 1, 2, 3}, speed = {1, 1, 1, 1}; assertEquals(1, new Solution().eliminateMaximum(dist, speed)); } @Test void test3() { int[] dist = {3, 2, 4}, speed = {5, 3, 2}; assertEquals(1, new Solution().eliminateMaximum(dist, speed)); } }
27b483c964892deda5ea8511a611e31e119788c4
7fa9c6b0fa1d0726ae1cda0199716c811a1ea01b
/Crawler/data/DvmField.java
2fd99babbb552295d1f12c61d2e33e6dfc56db36
[]
no_license
NayrozD/DD2476-Project
b0ca75799793d8ced8d4d3ba3c43c79bb84a72c0
94dfb3c0a470527b069e2e0fd9ee375787ee5532
refs/heads/master
2023-03-18T04:04:59.111664
2021-03-10T15:03:07
2021-03-10T15:03:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,345
java
16 https://raw.githubusercontent.com/wmm1996528/unidbg_douyin10/master/src/main/java/com/github/unidbg/linux/android/dvm/DvmField.java package com.github.unidbg.linux.android.dvm; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; class DvmField implements Hashable { private static final Log log = LogFactory.getLog(DvmField.class); private final DvmClass dvmClass; final String fieldName; final String fieldType; DvmField(DvmClass dvmClass, String fieldName, String fieldType) { this.dvmClass = dvmClass; this.fieldName = fieldName; this.fieldType = fieldType; } DvmObject<?> getStaticObjectField() { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("getStaticObjectField dvmClass=" + dvmClass + ", fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature); } BaseVM vm = dvmClass.vm; return vm.jni.getStaticObjectField(vm, dvmClass, signature); } int getStaticIntField() { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("getStaticIntField dvmClass=" + dvmClass + ", fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature); } BaseVM vm = dvmClass.vm; return dvmClass.vm.jni.getStaticIntField(vm, dvmClass, signature); } DvmObject<?> getObjectField(DvmObject<?> dvmObject) { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("getObjectField dvmObject=" + dvmObject + ", fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature); } BaseVM vm = dvmClass.vm; return vm.jni.getObjectField(vm, dvmObject, signature); } int getIntField(DvmObject<?> dvmObject) { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("getIntField dvmObject=" + dvmObject + ", fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature); } return dvmClass.vm.jni.getIntField(dvmClass.vm, dvmObject, signature); } long getLongField(DvmObject<?> dvmObject) { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("getLongField dvmObject=" + dvmObject + ", fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature); } return dvmClass.vm.jni.getLongField(dvmClass.vm, dvmObject, signature); } void setObjectField(DvmObject<?> dvmObject, DvmObject<?> value) { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("setObjectField dvmObject=" + dvmObject + ", fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature + ", value=" + value); } dvmClass.vm.jni.setObjectField(dvmClass.vm, dvmObject, signature, value); } int getBooleanField(DvmObject<?> dvmObject) { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("getBooleanField dvmObject=" + dvmObject + ", fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature); } return dvmClass.vm.jni.getBooleanField(dvmClass.vm, dvmObject, signature) ? VM.JNI_TRUE : VM.JNI_FALSE; } void setIntField(DvmObject<?> dvmObject, int value) { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("setIntField dvmObject=" + dvmObject + ", fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature + ", value=" + value); } dvmClass.vm.jni.setIntField(dvmClass.vm, dvmObject, signature, value); } void setLongField(DvmObject<?> dvmObject, long value) { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("setLongField dvmObject=" + dvmObject + ", fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature + ", value=" + value); } dvmClass.vm.jni.setLongField(dvmClass.vm, dvmObject, signature, value); } void setBooleanField(DvmObject<?> dvmObject, boolean value) { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("setBooleanField dvmObject=" + dvmObject + ", fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature + ", value=" + value); } dvmClass.vm.jni.setBooleanField(dvmClass.vm, dvmObject, signature, value); } void setDoubleField(DvmObject<?> dvmObject, double value) { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("setDoubleField dvmObject=" + dvmObject + ", fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature + ", value=" + value); } dvmClass.vm.jni.setDoubleField(dvmClass.vm, dvmObject, signature, value); } void setStaticLongField(long value) { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("setStaticLongField fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature + ", value=" + value); } dvmClass.vm.jni.setStaticLongField(dvmClass.vm, signature, value); } long getStaticLongField() { String signature = dvmClass.getClassName() + "->" + fieldName + ":" + fieldType; if (log.isDebugEnabled()) { log.debug("getStaticLongField fieldName=" + fieldName + ", fieldType=" + fieldType + ", signature=" + signature); } return dvmClass.vm.jni.getStaticLongField(dvmClass.vm, signature); } }
508e880e13871168cd4dd880b520c9fefed472b7
79df008f050705455fb5dda9e3953af36c2cbda9
/Computer Programming Technology/Board games/src/es/ucm/fdi/tp/assignment5/connectN/ConnectNSwingPlayer.java
892f6eb1be586ecaaf9056d50fafac2584176cd3
[]
no_license
argalad/FP-and-PT
53cdc6c31442936b4ecb745fd091208ed420716b
25fb2bf5f6cb47ed4eed8f919257915ca37b81d5
refs/heads/master
2023-04-16T03:37:06.800209
2021-05-03T16:39:17
2021-05-03T16:39:17
52,953,749
2
0
null
null
null
null
UTF-8
Java
false
false
889
java
package es.ucm.fdi.tp.assignment5.connectN; import java.util.List; import es.ucm.fdi.tp.basecode.bgame.control.Player; import es.ucm.fdi.tp.basecode.bgame.model.Board; import es.ucm.fdi.tp.basecode.bgame.model.GameMove; import es.ucm.fdi.tp.basecode.bgame.model.GameRules; import es.ucm.fdi.tp.basecode.bgame.model.Piece; import es.ucm.fdi.tp.basecode.connectn.ConnectNMove; @SuppressWarnings("serial") public class ConnectNSwingPlayer extends Player { private int row, col; @Override public GameMove requestMove(Piece p, Board board, List<Piece> pieces, GameRules rules) { return new ConnectNMove(row, col, p); } /** * Set the given positions to assign them to our move attributes. * * @param row * is the given row. * @param col * is the given column. */ public void setMove(int row, int col) { this.row = row; this.col = col; } }
d0b1f41b38f11917c05abed1d5bd800668085ad7
2beac37c7dc0911140ecc1064410e8d76cb01db9
/src/com/company/lesson7/homework/startString.java
f246eedcba0fdd745bbf2feaec1e1212da8cc44e
[]
no_license
Vivioza5/ideaFirst
781ba0a54e738c12dd42bab5be21948ff2be2fd0
5bccf74107ed6bc47df12f0107bc92c323dc21b2
refs/heads/master
2020-09-20T13:42:04.182729
2020-01-18T22:35:57
2020-01-18T22:35:57
224,499,108
0
0
null
2020-01-18T22:35:59
2019-11-27T19:05:15
Java
UTF-8
Java
false
false
399
java
package com.company.lesson7.homework; // Напишите программу Java, чтобы проверить, начинается ли заданная строка с содержимым другой строки. public class startString { public static void main(String[] args) { String testString = "testing"; System.out.println(testString.startsWith("test")); } }
5bff6635e2220411b169a7262340cc02f8fb5625
a624224b88a740b0b0e08c601d263b8b500b7eaa
/shweta_aswani_assign2/racingDrivers/src/racingDrivers/util/Results.java
745c643fe7d959e0d7ca482fee0504c067f1728c
[]
no_license
it2aswanishweta/CS-542
e5690c7f789570dd3e4dd5648f98acd9e589c3c4
0613c3b31038620bae88e4a855804c9071dace8e
refs/heads/master
2020-06-19T21:36:35.128207
2019-09-05T22:43:47
2019-09-05T22:43:47
196,882,332
0
0
null
null
null
null
UTF-8
Java
false
false
1,404
java
package racingDrivers.util; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import racingDrivers.driverStates.RaceContextClass; public class Results implements FileDisplayInterface, StdoutDisplayInterface { private static List<String> arrList = new ArrayList<String>(); static int x=0; static int driver = RaceContextClass.no; int counter = 0; /** Storing the output from the list to file **/ public void writeToFile(String s) { PrintWriter writer = null; try { writer = new PrintWriter(s, "UTF-8"); for(String st: arrList) { writer.print(st + " "); counter ++; if(counter == driver) { writer.println("\n"); counter = 0; } } } catch (Exception e) { e.printStackTrace(); } finally { writer.close(); } } @Override public void writeToStdout(String s) { System.out.println(s); } /** Writing the new result to the Array List **/ public static void storeNewResult(String test) { arrList.add(test); } public static void printResult(String s) { Results res1=new Results(); res1.writeToFile(s); } }
c809f52c07debb5a5f88961bfe4d6bae1b560351
38c1e9ecfb06d81f8ef96161576ea81db6ac4c16
/modules/kernel/src/main/java/com/thegoate/utils/to/To.java
29d74266ba77213cdfb4e3c9824154c424ac3d8b
[ "MIT" ]
permissive
gtque/GoaTE
5b25e272472493ea0ab958938ec397cc09addda9
7db1d3409a5fdfee160c214ce53c1194bdcd019b
refs/heads/dev
2023-08-07T22:40:09.709800
2023-07-28T16:49:28
2023-07-28T16:49:28
88,788,345
5
2
null
2023-02-07T14:10:54
2017-04-19T20:34:02
HTML
UTF-8
Java
false
false
2,336
java
/* * Copyright (c) 2017. Eric Angeli * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software * and associated documentation files (the "Software"), * to deal in the Software without restriction, * including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission * notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.thegoate.utils.to; import com.thegoate.utils.UnknownUtilType; /** * The generic togoate class. * This will attempt to look up the specific to goate utility for the type detected. * Created by Eric Angeli on 5/5/2017. */ public class To extends UnknownUtilType<To> implements ToUtility { ToUtility tool = null; protected Object original = null; public To(Object o) { this.original = o; // useCache = true; } @Override public boolean isType(Object check) { return false; } @Override public Object convert() { Object result = null; if (declaredType != null && declaredType.isAssignableFrom(original.getClass())) { result = original; } else { tool = (ToUtility) buildUtil(original, ToUtil.class); if (tool != null) { result = tool.convert(); } } return result; } @Override public boolean checkType(Class tool, Class type) { ToUtil tu = (ToUtil) tool.getAnnotation(ToUtil.class); return tu != null ? tu.type() != null ? (tu.type() == type) : (type == null) : false; } }
7debfcc131a4f07d5a0d5059d53290d01073df90
686caa4f304ffc350f344469ff996638f0d1b7de
/src/comercio/Precio.java
2fc6a8e67352f62d91cb968c3c887d486832da60
[]
no_license
PabNoce/Comercio
9af6a91f4b15c839b0210c9a64ebfcf517ec3639
0cd227034520ecbb3175da609ec6c8c771d8019d
refs/heads/master
2021-05-05T08:05:56.442072
2018-01-25T13:44:34
2018-01-25T13:44:34
118,917,926
0
0
null
null
null
null
UTF-8
Java
false
false
746
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package comercio; /** * * @author pnocedalopez */ public class Precio { private String refPrecio; private float Precio; public Precio(String refPrecio, float Precio) { this.refPrecio = refPrecio; this.Precio = Precio; } public String getRefPrecio() { return refPrecio; } public void setRefPrecio(String refPrecio) { this.refPrecio = refPrecio; } public float getPrecio() { return Precio; } public void setPrecio(float Precio) { this.Precio = Precio; } }
902bd103a7201279205996f631657a08c1dab835
2a3282ef62c9d92c9abfe0e1eae170ec2a384555
/src/main/java/com/ledgy98/spring/lesson04/model/NewUser.java
a59eb7b88b82fa515cf5d0548759475b1ab35175
[]
no_license
colleenInKorea/WebSpringExample0816
e133a21789e2a533683feca1691c95e8f88e3d69
ed67750f05be4890680f1baddc6df26ebe6209d3
refs/heads/master
2023-08-22T14:56:54.293139
2021-10-14T11:46:39
2021-10-14T11:46:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,083
java
package com.ledgy98.spring.lesson04.model; import java.util.Date; public class NewUser { private int id; private String name; private String yyyymmdd; private String email; private String introduce; private Date createdAt; private Date updatedAt; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getYyyymmdd() { return yyyymmdd; } public void setYyyymmdd(String yyyymmdd) { this.yyyymmdd = yyyymmdd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getIntroduce() { return introduce; } public void setIntroduce(String introduce) { this.introduce = introduce; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } }
01966df5dda2c1791ea78efdeaa6550333757ac2
7d7718936e2daf900e62ef183ff72bd4336ce6fd
/src/main/java/com/robertx22/age_of_exile/database/data/stats/datapacks/stats/spell_related/PerSpellCooldownStat.java
e69800d84b90a67c51f5366945f8c12c5e8671f6
[]
no_license
SF-s-Translation-repository/Age-of-Exile
75d1543736a4fc792066afd32f9a34efa0b6ba36
df075178517584c2b16fa5877a96e48aa4fc109e
refs/heads/master
2023-04-15T22:51:03.276732
2021-04-23T14:00:24
2021-04-23T14:00:24
282,349,542
0
0
null
2021-04-23T13:48:29
2020-07-25T01:42:42
Java
UTF-8
Java
false
false
2,338
java
package com.robertx22.age_of_exile.database.data.stats.datapacks.stats.spell_related; import com.robertx22.age_of_exile.database.data.spells.components.Spell; import com.robertx22.age_of_exile.database.data.spells.spell_classes.SpellModEnum; import com.robertx22.age_of_exile.database.data.stats.Stat; import com.robertx22.age_of_exile.database.data.stats.datapacks.stats.base.DatapackSpellStat; import com.robertx22.age_of_exile.database.data.stats.effects.base.BaseSpellCalcEffect; import com.robertx22.age_of_exile.database.data.stats.name_regex.StatNameRegex; import com.robertx22.age_of_exile.saveclasses.unit.StatData; import com.robertx22.age_of_exile.uncommon.effectdatas.SpellStatsCalcEffect; import com.robertx22.age_of_exile.uncommon.interfaces.IExtraStatEffect; import com.robertx22.age_of_exile.uncommon.interfaces.IStatEffect; public class PerSpellCooldownStat extends DatapackSpellStat implements IExtraStatEffect { public static String SER_ID = "spell_cooldown"; public PerSpellCooldownStat(Spell spell) { super(SER_ID); this.spell = spell.GUID(); this.spellname = spell.locNameForLangFile(); this.id = spell.GUID() + "_cooldown"; this.is_percent = true; } public PerSpellCooldownStat(String spell) { super(SER_ID); this.spell = spell; this.is_percent = true; } @Override public StatNameRegex getStatNameRegex() { return StatNameRegex.BASIC; } @Override public String locDescForLangFile() { return "Changes cooldown of spell"; } @Override public String locNameForLangFile() { return spellname + " Cooldown"; } @Override public IStatEffect getEffect() { return EFF; } static Effect EFF = new Effect(); private static class Effect extends BaseSpellCalcEffect { @Override public SpellStatsCalcEffect activate(SpellStatsCalcEffect effect, StatData data, Stat stat) { try { DatapackSpellStat es = (DatapackSpellStat) stat; if (es.spell.equals(effect.spell_id)) { effect.data.add(SpellModEnum.COOLDOWN, data); } } catch (Exception e) { e.printStackTrace(); } return effect; } } }
ef2bb484ca4b498c3a777431c8199e7e64c38c17
720b21519f1bea96ce81fed438f405811c5d2f38
/src/main/java/ThePokerPlayer/screens/PokerManualButton.java
a52a1e6df9a7caccd992d32b01e26aae42a6fc88
[ "MIT" ]
permissive
Celicath/PokerPlayerMod
484d0e6d165f21d84abc0398bff0493686089afe
cbad600aaabb1887bc21c7fb80b4b16f005233ac
refs/heads/master
2022-09-12T13:08:00.306855
2022-08-28T05:51:14
2022-08-28T05:51:14
155,950,592
0
3
MIT
2019-04-20T23:34:31
2018-11-03T04:40:50
Java
UTF-8
Java
false
false
3,894
java
package ThePokerPlayer.screens; import ThePokerPlayer.PokerPlayerMod; import ThePokerPlayer.patches.CurrentScreenEnum; import basemod.TopPanelItem; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.helpers.TipHelper; import com.megacrit.cardcrawl.helpers.input.InputHelper; public class PokerManualButton extends TopPanelItem { private static final Texture IMG = new Texture(PokerPlayerMod.makePath("ui/PokerManual.png")); public static final String ID = PokerPlayerMod.makeID("PokerManualButton"); public PokerManualButton() { super(IMG, ID); } @Override protected void onClick() { if (!CardCrawlGame.isPopupOpen) { toggleScreen(); } } private static void toggleScreen() { if (AbstractDungeon.screen == CurrentScreenEnum.POKER_MANUAL) { AbstractDungeon.closeCurrentScreen(); } else { if (AbstractDungeon.screen == AbstractDungeon.CurrentScreen.COMBAT_REWARD) { AbstractDungeon.closeCurrentScreen(); AbstractDungeon.previousScreen = AbstractDungeon.CurrentScreen.COMBAT_REWARD; } else if (!AbstractDungeon.isScreenUp) { } else if (AbstractDungeon.screen == AbstractDungeon.CurrentScreen.MASTER_DECK_VIEW) { if (AbstractDungeon.previousScreen != null) { AbstractDungeon.screenSwap = true; } AbstractDungeon.closeCurrentScreen(); } else if (AbstractDungeon.screen == AbstractDungeon.CurrentScreen.DEATH) { AbstractDungeon.previousScreen = AbstractDungeon.CurrentScreen.DEATH; AbstractDungeon.deathScreen.hide(); } else if (AbstractDungeon.screen == AbstractDungeon.CurrentScreen.BOSS_REWARD) { AbstractDungeon.previousScreen = AbstractDungeon.CurrentScreen.BOSS_REWARD; AbstractDungeon.bossRelicScreen.hide(); } else if (AbstractDungeon.screen == AbstractDungeon.CurrentScreen.SHOP) { AbstractDungeon.overlayMenu.cancelButton.hide(); AbstractDungeon.previousScreen = AbstractDungeon.CurrentScreen.SHOP; } else if (AbstractDungeon.screen == AbstractDungeon.CurrentScreen.MAP && !AbstractDungeon.dungeonMapScreen.dismissable) { AbstractDungeon.previousScreen = AbstractDungeon.CurrentScreen.MAP; } else if (AbstractDungeon.screen != AbstractDungeon.CurrentScreen.SETTINGS && AbstractDungeon.screen != AbstractDungeon.CurrentScreen.MAP) { if (AbstractDungeon.screen == AbstractDungeon.CurrentScreen.INPUT_SETTINGS) { if (AbstractDungeon.previousScreen != null) { AbstractDungeon.screenSwap = true; } AbstractDungeon.closeCurrentScreen(); } else if (AbstractDungeon.screen == AbstractDungeon.CurrentScreen.CARD_REWARD) { AbstractDungeon.previousScreen = AbstractDungeon.CurrentScreen.CARD_REWARD; AbstractDungeon.dynamicBanner.hide(); } else if (AbstractDungeon.screen == AbstractDungeon.CurrentScreen.GRID) { AbstractDungeon.previousScreen = AbstractDungeon.CurrentScreen.GRID; AbstractDungeon.gridSelectScreen.hide(); } else if (AbstractDungeon.screen == AbstractDungeon.CurrentScreen.HAND_SELECT) { AbstractDungeon.previousScreen = AbstractDungeon.CurrentScreen.HAND_SELECT; } } else { if (AbstractDungeon.previousScreen != null) { AbstractDungeon.screenSwap = true; } AbstractDungeon.closeCurrentScreen(); } if (AbstractDungeon.screen != AbstractDungeon.CurrentScreen.VICTORY) { PokerPlayerMod.pokerManualScreen.open(); } } InputHelper.justClickedLeft = false; } @Override public void render(SpriteBatch sb) { super.render(sb); if (hitbox.hovered) { float x = 1550.0F * Settings.scale; float y = (float) Settings.HEIGHT - 120.0F * Settings.scale; TipHelper.renderGenericTip(x, y, PokerManualScreen.TEXT[0], PokerManualScreen.TEXT[1]); } } }
b870a0d189b4097369c9c7dcb61282e2999e6542
d641d77d9c48dbb6e29139cbae8fc5555b5ecee0
/src/com/offer/a笔试/OPPO/Main1.java
476b0edbb7c253132e44fee74d6666ceb9382c7e
[]
no_license
lixuehan1129/algorithm
8dbbd68b6b2161ac71ea1297c4600e3fcf7d5e9d
40f1c14b64b239e809f31c228df9b0702e2d7f07
refs/heads/master
2023-01-05T07:08:19.383860
2020-11-09T00:48:18
2020-11-09T00:48:18
294,684,418
0
0
null
null
null
null
UTF-8
Java
false
false
482
java
package com.offer.a笔试.OPPO; import java.util.Scanner; /** * java String中indexof方法可以找到第一个匹配字符串的位置 */ public class Main1 { public static void main(String[] args) { //输入两个字符串 A B Scanner sc = new Scanner(System.in); String A = sc.nextLine(); String B = sc.nextLine(); sc.close(); //返回出现的第一个位置(从0开始) System.out.println(A.indexOf(B)); } }
4769ad527fd08bde81ab6d973ac4ef3610f842ee
44e59e28d0f8dda15a2d88db49d69d97898cf685
/src/main/java/com/pengu/lostthaumaturgy/core/block/BlockLyingItem.java
f4cc0b33eddc024402306788e5abcd2f07bc2f66
[]
no_license
limuness/LostThaumaturgy
661ed826f5aed86ab1ab60d5ed07af33b3b92d82
f50b540aac6d0af2bc53db0a5681716263893133
refs/heads/1.12
2021-06-25T23:17:08.522775
2017-09-06T12:39:54
2017-09-06T12:39:54
103,036,052
1
0
null
2017-09-10T14:31:48
2017-09-10T14:31:47
null
UTF-8
Java
false
false
4,015
java
package com.pengu.lostthaumaturgy.core.block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.NonNullList; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import com.pengu.hammercore.api.ITileBlock; import com.pengu.hammercore.common.utils.WorldUtil; import com.pengu.lostthaumaturgy.api.event.LyingItemPickedUpEvent; import com.pengu.lostthaumaturgy.core.block.def.BlockRendered; import com.pengu.lostthaumaturgy.core.tile.TileLyingItem; import com.pengu.lostthaumaturgy.init.BlocksLT; public class BlockLyingItem extends BlockRendered implements ITileEntityProvider, ITileBlock<TileLyingItem> { public BlockLyingItem() { super(Material.ROCK); setUnlocalizedName("lying_item"); } @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { TileLyingItem item = WorldUtil.cast(world.getTileEntity(pos), TileLyingItem.class); return item != null ? item.lying.get().copy() : ItemStack.EMPTY; } public static TileLyingItem place(World world, BlockPos pos, ItemStack stack) { if(world.isBlockLoaded(pos) && world.getBlockState(pos).getBlock().isReplaceable(world, pos)) { world.setBlockState(pos, BlocksLT.LYING_ITEM.getDefaultState()); TileLyingItem tile = WorldUtil.cast(world.getTileEntity(pos), TileLyingItem.class); if(tile == null) world.setTileEntity(pos, tile = new TileLyingItem()); tile.lying.set(stack.copy()); return tile; } return null; } public static final AxisAlignedBB aabb = new AxisAlignedBB(0, 0, 0, 0, 0, 0); @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return aabb; } @Override public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) { if(entityIn instanceof EntityPlayer) { TileLyingItem tile = WorldUtil.cast(worldIn.getTileEntity(pos), TileLyingItem.class); if(tile != null) { try { LyingItemPickedUpEvent evt = new LyingItemPickedUpEvent((EntityPlayer) entityIn, pos, tile.lying.get().copy(), tile.placedByPlayer.get() != Boolean.TRUE); if(MinecraftForge.EVENT_BUS.post(evt)) return; EntityItem ei = ((EntityPlayer) entityIn).dropItem(evt.drop, true); if(ei != null) ei.setNoPickupDelay(); } finally { worldIn.setBlockToAir(pos); } } } } @Override public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) { } @Override public boolean isOpaqueCube(IBlockState state) { return false; } public boolean isFullCube(IBlockState state) { return false; } @Override public EnumBlockRenderType getRenderType(IBlockState state) { return EnumBlockRenderType.ENTITYBLOCK_ANIMATED; } @Override public boolean canRenderInLayer(IBlockState state, BlockRenderLayer layer) { return false; } @Override public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileLyingItem(); } @Override public Class<TileLyingItem> getTileClass() { return TileLyingItem.class; } @Override public String getParticleSprite(World world, BlockPos pos) { return "minecraft:blocks/stone_andesite"; } }
b64b7fcac28c9f0b31521a3ed99b5803d462196e
03e7cb567d98864390221bf01294e72156b56543
/model/src/main/java/com/epam/brest/model/Interval.java
df1c97889073e034b03d594d0d690062cabfb01e
[]
no_license
Brest-Java-Course-2018/ViachaslauStrelnikau
a8abbd5433c2add69b08f0954ebb9ba97abbe3c6
8182ee3e74df289aa6f94ad340c53377141f6503
refs/heads/master
2023-01-27T20:21:11.701505
2019-07-02T13:09:05
2019-07-02T13:09:05
120,646,797
2
1
null
2023-01-07T04:34:50
2018-02-07T17:19:45
JavaScript
UTF-8
Java
false
false
1,308
java
package com.epam.brest.model; import java.sql.Date; import java.util.Objects; /** * Interval class */ public class Interval { /** * Property dateFrom. */ private Date dateFrom; /** * Property dateTo. */ private Date dateTo; public Interval(Date dateFrom, Date dateTo) { this.dateFrom = dateFrom; this.dateTo = dateTo; } public Interval() { } public Date getDateFrom() { return dateFrom; } public Date getDateTo() { return dateTo; } public void setDateFrom(Date dateFrom) { this.dateFrom = dateFrom; } public void setDateTo(Date dateTo) { this.dateTo = dateTo; } @Override public String toString() { return "Interval{" + "dateFrom=" + dateFrom + ", dateTo=" + dateTo + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Interval interval = (Interval) o; return Objects.equals(dateFrom, interval.dateFrom) && Objects.equals(dateTo, interval.dateTo); } @Override public int hashCode() { return Objects.hash(dateFrom, dateTo); } }
2da64252d10f49efa6a8ba48cfb0f421252d2c72
a533dd7ccf94fc838da4f88fea0be4fb16fa77db
/testgreendao/src/main/java/com/example/testgreendao/entity/dao/GunDao.java
58a5badea121fe2707d77c3a1e6ba5685f9c160c
[]
no_license
androidxiejun/demoworkspace
2ff2235eb9a2e204c6116f684059e8c23c2911c0
f5b8d5903ac4a4e92ea4f2e8186bb5839742303c
refs/heads/master
2020-05-07T21:44:46.189361
2019-08-26T03:53:11
2019-08-26T03:53:11
180,914,859
1
0
null
null
null
null
UTF-8
Java
false
false
5,634
java
package com.example.testgreendao.entity.dao; import java.util.List; import android.database.Cursor; import android.database.sqlite.SQLiteStatement; import org.greenrobot.greendao.AbstractDao; import org.greenrobot.greendao.Property; import org.greenrobot.greendao.internal.DaoConfig; import org.greenrobot.greendao.database.Database; import org.greenrobot.greendao.database.DatabaseStatement; import org.greenrobot.greendao.query.Query; import org.greenrobot.greendao.query.QueryBuilder; import com.example.testgreendao.entity.bean.Gun; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table "db_gun". */ public class GunDao extends AbstractDao<Gun, Long> { public static final String TABLENAME = "db_gun"; /** * Properties of entity Gun.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Id = new Property(0, Long.class, "id", true, "_id"); public final static Property GunName = new Property(1, String.class, "gunName", false, "gun_name"); public final static Property GunNo = new Property(2, String.class, "gunNo", false, "gun_no"); public final static Property CustomId = new Property(3, Long.class, "customId", false, "custom_id"); } private Query<Gun> user_GunsQuery; public GunDao(DaoConfig config) { super(config); } public GunDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(Database db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "\"db_gun\" (" + // "\"_id\" INTEGER PRIMARY KEY ," + // 0: id "\"gun_name\" TEXT," + // 1: gunName "\"gun_no\" TEXT," + // 2: gunNo "\"custom_id\" INTEGER);"); // 3: customId } /** Drops the underlying database table. */ public static void dropTable(Database db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"db_gun\""; db.execSQL(sql); } @Override protected final void bindValues(DatabaseStatement stmt, Gun entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String gunName = entity.getGunName(); if (gunName != null) { stmt.bindString(2, gunName); } String gunNo = entity.getGunNo(); if (gunNo != null) { stmt.bindString(3, gunNo); } Long customId = entity.getCustomId(); if (customId != null) { stmt.bindLong(4, customId); } } @Override protected final void bindValues(SQLiteStatement stmt, Gun entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String gunName = entity.getGunName(); if (gunName != null) { stmt.bindString(2, gunName); } String gunNo = entity.getGunNo(); if (gunNo != null) { stmt.bindString(3, gunNo); } Long customId = entity.getCustomId(); if (customId != null) { stmt.bindLong(4, customId); } } @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } @Override public Gun readEntity(Cursor cursor, int offset) { Gun entity = new Gun( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // gunName cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // gunNo cursor.isNull(offset + 3) ? null : cursor.getLong(offset + 3) // customId ); return entity; } @Override public void readEntity(Cursor cursor, Gun entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setGunName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setGunNo(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2)); entity.setCustomId(cursor.isNull(offset + 3) ? null : cursor.getLong(offset + 3)); } @Override protected final Long updateKeyAfterInsert(Gun entity, long rowId) { entity.setId(rowId); return rowId; } @Override public Long getKey(Gun entity) { if(entity != null) { return entity.getId(); } else { return null; } } @Override public boolean hasKey(Gun entity) { return entity.getId() != null; } @Override protected final boolean isEntityUpdateable() { return true; } /** Internal query to resolve the "guns" to-many relationship of User. */ public List<Gun> _queryUser_Guns(Long customId) { synchronized (this) { if (user_GunsQuery == null) { QueryBuilder<Gun> queryBuilder = queryBuilder(); queryBuilder.where(Properties.CustomId.eq(null)); user_GunsQuery = queryBuilder.build(); } } Query<Gun> query = user_GunsQuery.forCurrentThread(); query.setParameter(0, customId); return query.list(); } }
fe94c625f730845d2b16e42a1d60ea7b15bb6d86
a8fb3de7266373330ca6531ee380d11465eed80c
/src/main/java/cz/uhk/restaurace/service/authentication/user/UserDetails.java
c46b061b45529579afbcd1863049af0cf0671618
[]
no_license
romankristof/restaurant
654aa0e26b419833f78e519303c420e3183dabfc
c379a6e6606bc97bf0acef6166f696ab4a9c5126
refs/heads/master
2022-08-09T04:58:46.886976
2015-01-25T15:42:45
2015-01-25T15:42:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,526
java
package cz.uhk.restaurace.service.authentication.user; import cz.uhk.restaurace.model.*; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; import java.util.Collection; /** * Created by dann on 20.11.2014. * Class whose objects store user data used in various views */ public class UserDetails extends User{ private static final long serialVersionUID = 32L; private String surname; private String firstname; private String email; private String telephone; private Address address; private Collection<Role> roles; public UserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) { super(username, password, authorities); } public UserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities, String surname, String firstname, String email, String telephone, Address address) { this(username, password, authorities); this.address = address; this.firstname = firstname; this.surname = surname; this.telephone = telephone; this.email = email; } public UserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities, String surname, String firstname, String email, String telephone, Address address, Collection<Role> roles) { this(username, password, authorities, surname, firstname, email, telephone, address); this.roles = roles; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Collection<Role> getRoles() { return roles; } public void setRoles(Collection<Role> roles) { this.roles = roles; } }
17ede3c3c01d7198f8f067cab95b3360eb8de85f
e270b6894e36e2ef8864786d7cadf1ffd2d75b31
/app/src/main/java/com/example/permission/PermissionUtils.java
d901dd6186a32576f237069886001893ed8ba6a2
[]
no_license
VisionDivyeshAppMaster/PermissionFirebase
4b8f1a080d16d80d4b9c02cf60c26d41946014d7
98dc08311eb8dfa12046f406b7da8f4b50777fe6
refs/heads/master
2023-09-02T07:02:53.391464
2021-11-24T13:02:16
2021-11-24T13:02:16
431,486,623
0
0
null
null
null
null
UTF-8
Java
false
false
5,565
java
package com.example.permission; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.widget.Toast; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.util.ArrayList; import java.util.List; public class PermissionUtils { public static final int REQUEST_PERMISSION_MULTIPLE = 0; public static final int REQUEST_PERMISSION_CAMERA = 1; public static final int REQUEST_PERMISSION_LOCATION = 2; public static final int REQUEST_WRITE_EXTERNAL = 3; public static boolean checkAndRequestPermissions(Activity activity){ int permissionCamera = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA); int permissionLocation = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION); int permissionWriteExternal = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); List<String> listPermissionsNeeded = new ArrayList<>(); if (permissionCamera != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) { Toast.makeText(activity, "Camera Permission is required for this app to run", Toast.LENGTH_SHORT) .show(); } listPermissionsNeeded.add(Manifest.permission.CAMERA); } if (permissionWriteExternal != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if (permissionLocation != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(activity, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_PERMISSION_MULTIPLE); return false; } return true; } public static void requestCameraPermission(Activity activity) { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) { ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.CAMERA }, REQUEST_PERMISSION_CAMERA); } else { ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.CAMERA }, REQUEST_PERMISSION_CAMERA); } } else { System.out.println("requestCameraPermission() PERMISSION ALREADY GRANTED"); } } public static void requestLocationPermission(Activity activity) { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) { Toast.makeText(activity, "LOCATION permission is needed to display location info ", Toast.LENGTH_SHORT) .show(); ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_PERMISSION_LOCATION); Toast.makeText(activity, "REQUEST LOCATION PERMISSION", Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_PERMISSION_LOCATION); Toast.makeText(activity, "REQUEST LOCATION PERMISSION", Toast.LENGTH_LONG).show(); } } else { }} public static void requestWriteExternalPermission(Activity activity) { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { Toast.makeText(activity, "Write permission is needed to create Excel file ", Toast.LENGTH_SHORT).show(); ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL); Toast.makeText(activity, "REQUEST LOCATION PERMISSION", Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL); } } } public static boolean hasPermissions(Context context, String... permissions) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } }
fad10354c064c296944dcd9aa3d8a9b250731acf
48e835e6f176a8ac9ae3ca718e8922891f1e5a18
/benchmark/test/org/springframework/batch/sample/JobOperatorFunctionalTests.java
e43783355b198eea51c0b887ee1118a13082de02
[]
no_license
STAMP-project/dspot-experiments
f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5
121487e65cdce6988081b67f21bbc6731354a47f
refs/heads/master
2023-02-07T14:40:12.919811
2019-11-06T07:17:09
2019-11-06T07:17:09
75,710,758
14
19
null
2023-01-26T23:57:41
2016-12-06T08:27:42
null
UTF-8
Java
false
false
4,187
java
/** * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.springframework.batch.sample; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.configuration.JobRegistry; import org.springframework.batch.core.launch.JobOperator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/infiniteLoopJob.xml" }) public class JobOperatorFunctionalTests { private static final Log LOG = LogFactory.getLog(JobOperatorFunctionalTests.class); @Autowired private JobOperator operator; @Autowired private Job job; @Autowired private JobRegistry jobRegistry; @Test public void testStartStopResumeJob() throws Exception { String params = new JobParametersBuilder().addLong("jobOperatorTestParam", 7L).toJobParameters().toString(); long executionId = operator.start(job.getName(), params); Assert.assertEquals(params, operator.getParameters(executionId)); stopAndCheckStatus(executionId); long resumedExecutionId = operator.restart(executionId); Assert.assertEquals(params, operator.getParameters(resumedExecutionId)); stopAndCheckStatus(resumedExecutionId); List<Long> instances = operator.getJobInstances(job.getName(), 0, 1); Assert.assertEquals(1, instances.size()); long instanceId = instances.get(0); List<Long> executions = operator.getExecutions(instanceId); Assert.assertEquals(2, executions.size()); // latest execution is the first in the returned list Assert.assertEquals(resumedExecutionId, executions.get(0).longValue()); Assert.assertEquals(executionId, executions.get(1).longValue()); } @Test public void testMultipleSimultaneousInstances() throws Exception { String jobName = job.getName(); Set<String> names = operator.getJobNames(); Assert.assertEquals(1, names.size()); Assert.assertTrue(names.contains(jobName)); long exec1 = operator.startNextInstance(jobName); long exec2 = operator.startNextInstance(jobName); Assert.assertTrue((exec1 != exec2)); Assert.assertTrue((!(operator.getParameters(exec1).equals(operator.getParameters(exec2))))); // Give the asynchronous task executor a chance to start executions Thread.sleep(1000); Set<Long> executions = operator.getRunningExecutions(jobName); Assert.assertTrue(executions.contains(exec1)); Assert.assertTrue(executions.contains(exec2)); int count = 0; boolean running = (operator.getSummary(exec1).contains("STARTED")) && (operator.getSummary(exec2).contains("STARTED")); while (((count++) < 10) && (!running)) { Thread.sleep(100L); running = (operator.getSummary(exec1).contains("STARTED")) && (operator.getSummary(exec2).contains("STARTED")); } Assert.assertTrue(String.format("Jobs not started: [%s] and [%s]", operator.getSummary(exec1), operator.getSummary(exec1)), running); operator.stop(exec1); operator.stop(exec2); } }
70941290681635d1a97f5ec5c37a55b23a9b5e60
3279f8f6c89768727869d76c8573a52d2fb6472d
/mantis-tests/src/test/java/ru/stqa/pft/tests/ChangePasswdTest.java
697a3e32893e3292d98c58303b0ccb4cd4e1ab17
[]
no_license
Meshchaninov-A/LessonOne
ba4db1687f67f23db1913ce046414b31df52b627
6dbc060e685ec81f40dd275e3353ee6e893836ea
refs/heads/master
2021-10-15T23:36:19.582892
2019-02-06T21:41:31
2019-02-06T21:41:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,841
java
package ru.stqa.pft.tests; import org.openqa.selenium.By; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import ru.stqa.pft.model.User; import javax.mail.MessagingException; import java.io.IOException; public class ChangePasswdTest extends TestBase { String email; String user; int userID; String password = "password"; @BeforeTest public void getListUsers() throws IOException, MessagingException { //Проверяем, что у нас помимо администратора есть еще пользователи. Если нет - создаем.Если есть - берем первого попавшегося if (app.db().users().size() <= 1) { long now = System.currentTimeMillis(); app.registration().registerNewUser(String.format("user%s", now), String.format("user%s@localhost", now), password); } User userData = app.db().users().stream().filter(o -> !o.getUsername().equals("administrator")).findFirst().get(); email = userData.getEmail(); user = userData.getUsername(); userID = userData.getId(); System.out.println(userData.toString()); } @Test public void loginAsRootAndResetPasswd() throws IOException, InterruptedException, MessagingException { app.james().drainEmail(user, password); app.registration().login("administrator", "root"); app.getDriver().findElement(By.cssSelector("a[class='manage-menu-link']")).click(); app.getDriver().findElement(By.cssSelector("a[href='/mantisbt/manage_user_page.php']")).click(); app.getDriver().findElement(By.cssSelector(String.format("a[href='manage_user_edit_page.php?user_id=%s']", userID))).click(); app.getDriver().findElement(By.cssSelector("input[value='Reset Password']")).click(); app.registration().waitMail(user, email, password); } }
d2817e260e9a91c3eca33f18608b1db08a8ef9f7
b94254566cf35283f269582b64cb1f8c4692d9d3
/策略部分/release/src/quoridor/MoveInterface.java
89a2ebf03759692c1ffeccbea248024cd18eea02
[]
no_license
zxc2012/NXP_Creative
f361cdead71458610631a94b10aecac8e7c98f4a
db5fbf83c3b6cd5f4b3167c2ed097a4e1e47dbd0
refs/heads/master
2022-05-15T13:11:45.399463
2022-05-01T07:52:01
2022-05-01T07:52:01
219,664,254
5
0
null
2022-05-01T07:52:03
2019-11-05T05:24:55
Java
UTF-8
Java
false
false
447
java
package quoridor; /** * An abstract class for quoridor moves. * @author Team Stump */ public abstract class MoveInterface { public PlayerInterface owner; /** * Sets the owner for this move object * @param player */ public void setOwner(PlayerInterface player) { this.owner = player; } /** * Accessor for the owner of this move object * @return player owner */ public PlayerInterface getOwner() { return owner; } }
7494653b038baaec1160e72c03f71c9af6f0eae6
bb6ec86d3321a9eff2465fc932820ade4ecfa1eb
/test-rabbitmq-consumer/src/main/java/com/xuecheng/test/rabbitmq/RabbitmqConfig.java
ba67f259fb2c473a74567d79d8c86d13af920f5d
[]
no_license
fengyinhan/XC_PROJIECT
30ce608246b3dd090f7fb52c6a0a486d29c46419
4d9af7607be3c1b450d2d3f1cd65d543f39225ef
refs/heads/master
2022-12-04T20:28:18.044205
2019-08-22T11:36:31
2019-08-22T11:36:31
203,778,607
0
0
null
2022-11-24T06:26:49
2019-08-22T11:11:52
Java
UTF-8
Java
false
false
1,982
java
package com.xuecheng.test.rabbitmq; import org.springframework.amqp.core.*; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitmqConfig { //队列名称 public static final String QUEUE_INFORM_EMAIL = "queue_inform_email"; public static final String QUEUE_INFORM_SMS = "queue_inform_sms"; //交换机名称 public static final String EXCHANGE_TOPICS_INFORM="exchange_topics_inform"; public static final String ROUTINGKEY_EMAIL="inform.#.email.#"; public static final String ROUTINGKEY_SMS="inform.#.sms.#"; //声明交换机 @Bean(EXCHANGE_TOPICS_INFORM) public Exchange EXCHANGE_TOPICS_INFORM(){ //durable(true) 持久化 mq重启后交换机还在 return ExchangeBuilder.topicExchange(EXCHANGE_TOPICS_INFORM).durable(true).build(); } //声明QUEUE_INFORM_EMAIL队列 @Bean(QUEUE_INFORM_EMAIL) public Queue QUEUE_INFORM_EMAIL(){ return new Queue(QUEUE_INFORM_EMAIL); } //声明QUEUE_INFORM_SMS队列 @Bean(QUEUE_INFORM_SMS) public Queue QUEUE_INFORM_SMS(){ return new Queue(QUEUE_INFORM_SMS); } //ROUTINGKEY_EMAIL队列绑定交换机,指定routingKey @Bean public Binding BINDING_QUEUE_INFORM_EMAIL(@Qualifier(QUEUE_INFORM_EMAIL) Queue queue, @Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange){ return BindingBuilder.bind(queue).to(exchange).with(ROUTINGKEY_EMAIL).noargs(); } //ROUTINGKEY_SMS队列绑定交换机,指定routingKey @Bean public Binding BINDING_QUEUE_INFORM_SMS(@Qualifier(QUEUE_INFORM_SMS) Queue queue, @Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange){ return BindingBuilder.bind(queue).to(exchange).with(ROUTINGKEY_SMS).noargs(); } }
a84d6393bf35b14db0ff06e2a1792e65981d300c
f11af842486e9806ddcc15306924559bbd02895b
/ARS/build/generated/src/org/apache/jsp/click1_jsp.java
29e24e44426794cc3769810722b186f5ab02dd74
[]
no_license
AlokMishraR/MyLearning
fbbf9a7a5b1f4395d8ecd93d0fa70b5a831819d9
2e8a8ae124bdcd9d45f085e804b0edd305d47e3b
refs/heads/master
2021-05-06T14:41:30.710904
2018-01-16T11:06:35
2018-01-16T11:06:35
113,319,774
0
0
null
null
null
null
UTF-8
Java
false
false
7,651
java
package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class click1_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List<String> _jspx_dependants; private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_p_link_action; private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector; public java.util.List<String> getDependants() { return _jspx_dependants; } public void _jspInit() { _jspx_tagPool_p_link_action = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); } public void _jspDestroy() { _jspx_tagPool_p_link_action.release(); } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); out.write("\n"); out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); out.write("<head>\n"); out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n"); out.write("<title>Untitled Document</title>\n"); out.write("<style type=\"text/css\">\n"); out.write("<!--\n"); out.write(".style1 {\n"); out.write("\tfont-size: 24px;\n"); out.write("\tfont-weight: bold;\n"); out.write("}\n"); out.write("body {\n"); out.write("\tbackground-color: #FFFFCC;\n"); out.write("}\n"); out.write("-->\n"); out.write("</style>\n"); out.write("</head>\n"); out.write("\n"); out.write("<body>\n"); out.write("\n"); out.write("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n"); out.write(" <!--DWLayoutTable-->\n"); out.write(" <tr>\n"); out.write(" <td width=\"447\" height=\"75\">&nbsp;</td>\n"); out.write(" <td width=\"478\">&nbsp;</td>\n"); out.write(" <td width=\"359\">&nbsp;</td>\n"); out.write(" </tr>\n"); out.write(" <tr>\n"); out.write(" <td height=\"330\">&nbsp;</td>\n"); out.write(" <td valign=\"top\"><table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n"); out.write(" <!--DWLayoutTable-->\n"); out.write(" <tr>\n"); out.write(" <td height=\"59\" colspan=\"3\" valign=\"top\" bgcolor=\"#0000FF\"><div align=\"center\" class=\"style1\">Hi Admin To go To your Home Page click Below </div></td>\n"); out.write(" </tr>\n"); out.write(" <tr>\n"); out.write(" <td width=\"204\" height=\"56\">&nbsp;</td>\n"); out.write(" <td width=\"106\">&nbsp;</td>\n"); out.write(" <td width=\"168\">&nbsp;</td>\n"); out.write(" </tr>\n"); out.write(" <tr>\n"); out.write(" <td height=\"25\">&nbsp;</td>\n"); out.write(" <td valign=\"top\" bgcolor=\"#9999FF\">\n"); if (_jspx_meth_p_link_0(_jspx_page_context)) return; out.write("</td>\n"); out.write(" <td>&nbsp;</td>\n"); out.write(" </tr>\n"); out.write(" <tr>\n"); out.write(" <td height=\"190\">&nbsp;</td>\n"); out.write(" <td>&nbsp;</td>\n"); out.write(" <td>&nbsp;</td>\n"); out.write(" </tr>\n"); out.write(" </table> </td>\n"); out.write(" <td>&nbsp;</td>\n"); out.write(" </tr>\n"); out.write(" <tr>\n"); out.write(" <td height=\"193\">&nbsp;</td>\n"); out.write(" <td>&nbsp;</td>\n"); out.write(" <td>&nbsp;</td>\n"); out.write(" </tr>\n"); out.write(" <tr>\n"); out.write(" <td height=\"52\" colspan=\"3\" valign=\"top\" bgcolor=\"#FFFFFF\"><div id=\"copyrights\">\n"); out.write(" <div align=\"center\"><strong>This Site works best when viewed in Mozilla Firefox (3.6.1 or higher)</strong></div>\n"); out.write(" </div>\n"); out.write(" <div id=\"copyrights\">\n"); out.write(" <div align=\"center\">Copyright &copy; ALOK INFOTECH. All rights reserved.</div>\n"); out.write(" </div>\n"); out.write(" <div id=\"designedby\">\n"); out.write(" <div align=\"center\">Designed by ALOK MISHRA </div>\n"); out.write(" </div></td>\n"); out.write(" </tr>\n"); out.write("</table>\n"); out.write("</body>\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_p_link_0(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // p:link org.apache.struts.taglib.html.LinkTag _jspx_th_p_link_0 = (org.apache.struts.taglib.html.LinkTag) _jspx_tagPool_p_link_action.get(org.apache.struts.taglib.html.LinkTag.class); _jspx_th_p_link_0.setPageContext(_jspx_page_context); _jspx_th_p_link_0.setParent(null); _jspx_th_p_link_0.setAction("/log22"); int _jspx_eval_p_link_0 = _jspx_th_p_link_0.doStartTag(); if (_jspx_eval_p_link_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { if (_jspx_eval_p_link_0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.pushBody(); _jspx_th_p_link_0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out); _jspx_th_p_link_0.doInitBody(); } do { out.write("Go To Home"); int evalDoAfterBody = _jspx_th_p_link_0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); if (_jspx_eval_p_link_0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) out = _jspx_page_context.popBody(); } if (_jspx_th_p_link_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_p_link_action.reuse(_jspx_th_p_link_0); return true; } _jspx_tagPool_p_link_action.reuse(_jspx_th_p_link_0); return false; } }
f431d0085154693906a33e0a8ba04ac046f25b52
fbb7278a81374cb962df4150ffd592d55644d845
/samples/client/petstore/android-java/src/main/java/com/wordnik/client/JsonUtil.java
3d96fa3ac71cb69287bbcb7b82469124d363dc6b
[ "Apache-2.0" ]
permissive
isabella232/swagger-codegen
6b292d8211efeb718707e77a533a78c0aa45726d
2ea6c2a3a7520f35ac4aa135e6135525b144423a
refs/heads/master
2023-03-10T14:44:33.639406
2014-05-30T21:25:57
2014-05-30T21:25:57
310,349,732
0
0
NOASSERTION
2021-02-23T12:43:00
2020-11-05T16:00:41
null
UTF-8
Java
false
false
567
java
package com.wordnik.client; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.core.JsonGenerator.Feature; public class JsonUtil { public static ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); } public static ObjectMapper getJsonMapper() { return mapper; } }
8633323f92635c31722f9ad3015b3cec717d9932
b111ee3aecfaf9e0b1f0cda5415525d6fa5f997e
/binarysearchandlinearsearch/LinearSearch.java
2c4b71cf871a1845901637212b69f9459b956366
[]
no_license
chrisadubois/datastructuresandalgorithms
a330227735c1bb77d0244c53166a063bd19d0457
62d3e7b6cac66df81d0901467553b776240a2f35
refs/heads/master
2021-01-25T08:29:58.151924
2015-08-20T20:06:07
2015-08-20T20:06:07
41,116,493
0
0
null
null
null
null
UTF-8
Java
false
false
2,820
java
package hw6; //@Author Christopher DuBois //implements the linear search method for Strings iteratively and recursively //the recursive method will cause stack overflow as n gets very large public class LinearSearch extends SearchAlgorithm {//"is a" abstract class, searchalgorithm has some interface methods to fill in, and other methods to simply reuse public LinearSearch() {//no data necessary, the count variable is held in the parent class } @Override public int search(String[] arr, String targ) {//iterative search, takes in an array of Strings, and a target to search for if (arr == null || targ == null) {//if either the array passed in is null or the target string is null throw new NullPointerException("Cannot pass in a null array or a null target string");//throw an exception } for (int i = 0; i < arr.length; i++) {//for the entire length of the String array incrementCount();//increment the count for the number of comparisons each time we are checking if (targ.equals(arr[i])) {//using strings equals method, if target equals the array at index return i;//then return that index } } int a = -1;//else throw an exception not found if (a == -1) {//-1 will only happen if it's not found because above it returns i throw new ItemNotFoundException();//throw the exception } return a;//else return -1; this will never happen here because the exception will be thrown } @Override public int recSearch(String[] arr, String targ) {//facade if (arr == null || targ == null) throw new NullPointerException("Cannot pass in null array or target string");//null checks on the array and the target String int a = recSearch(0, arr, targ);//finds the index (and finds -1 if not found) if (a == -1) throw new ItemNotFoundException();//if not found, throw an exception else return recSearch(0, arr, targ);//otherwise throw the not found exception } private int recSearch(int index, String[] arr, String targ) {//recursive linear search if (index >= arr.length) {//if the index being passed in to the recursive method is larger than the arrays length (or equal to), we must break out because the item cannot be found, as the index passed in is the index to check at return -1;//if not found return -1 } if (targ.equals(arr[index])) {//uses strings equal method return index;//if the item was found return the index it was found at } else {//otherwise... incrementCount();//this is where the comparison incrementation is, and it is here because the above part is the case IF the word was found, otherwise, //we must move to the next spot and check, thus, increment count here return recSearch(index+1, arr, targ);//pass in the same array, and the same target string, but increment the index to check the target against in the array } } }
2030503a1f6306be8c9fafa2222ea8dc4e2c3994
45274ad2f3e90656b79bee909282369e48819db5
/src/main/java/my/study/DI/controllers/I18nController.java
8428b92e9821fb5b1e0346cd69db47c08971d66b
[]
no_license
VolodymyrShv/DI
4caef9f1ad3f754ae2cf0b6e312f6e1394253255
f0784886f8370b2b6ba36df9a81386bd7f131941
refs/heads/master
2023-06-15T00:51:20.212535
2021-07-08T20:06:01
2021-07-08T20:06:01
384,236,142
0
0
null
null
null
null
UTF-8
Java
false
false
516
java
package my.study.DI.controllers; import my.study.DI.services.GreetingService; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; @Controller public class I18nController { private final GreetingService greetingService; public I18nController(@Qualifier("i18nService") GreetingService greetingService) { this.greetingService = greetingService; } public String sayHello() { return greetingService.sayGreeting(); } }
9f86bf9b1fad37218beffe46b1d319a581974a95
47baf048e64a0304c654b3f3e6bbd6fd6257f6f5
/SoftwareCompare_Java_20170516/Fase 1/zz TIS/TowaInfrastructure/Oint.java
ada507c34e09a52966e4a1adf0d1d5054dab0bb4
[]
no_license
elielr01/towa_java
7812d7a129265d7e030d5acb46c50312c78b0b3a
6e8824d303697c01e669d5c5cd48f52ea43a351b
refs/heads/master
2020-12-07T15:36:30.870518
2017-07-23T20:56:19
2017-07-23T20:56:19
95,550,260
0
0
null
null
null
null
UTF-8
Java
false
false
1,465
java
/*TASK Boxing Boxing of primitives*/ package TowaInfrastructure; //AUTHOR: Towa (GLG-Gerardo López). //CO-AUTHOR: Towa (). //DATE: February 19, 2016. //PURPOSE: //Base for all Bxxx. //===================================================================================================================== public /*OPEN*/ class Oint extends BboxBaseBoxingAbstract //Boxing int. { //----------------------------------------------------------------------------------------------------------------- /*INSTANCE VARIABLE*/ public int /*NSTD*/v/*END-NSTD*/; //----------------------------------------------------------------------------------------------------------------- /*OBJECT CONSTRUCTORS*/ //----------------------------------------------------------------------------------------------------------------- public Oint () {} public Oint ( //Box a int. //this.*[O], assign variable. int int_I ) { this.v = int_I; } } //===================================================================================================================== /*END-TASK*/
1e587b9cda367e8d669e6ff9ece12ca14ef74ff1
b6450cc5c18068a99bc3e2bc7064e119ed026fa6
/steel-store/api-gateway-server/src/main/java/com/ryit/gateway/config/RateLimiterConfig.java
d8f67709f8d92c2f1b50e85afde6a5d685dbb6bf
[ "Apache-2.0" ]
permissive
samphin/finish-projects
0f36eec553d49c04454a3871e85bd385f46173ae
19d2cb352e8c8209867573e6de00f144ddbe124e
refs/heads/master
2022-12-28T05:51:02.774038
2020-04-03T09:13:52
2020-04-03T09:13:52
225,137,147
1
2
Apache-2.0
2022-12-16T00:39:36
2019-12-01T09:38:16
Java
UTF-8
Java
false
false
1,434
java
package com.ryit.gateway.config; import com.ryit.commons.constants.JwtConstant; import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import reactor.core.publisher.Mono; /** * 限流配置 */ @Configuration public class RateLimiterConfig { /** * 根据远程请求地址 * * @return */ @Bean public KeyResolver remoteAddrKeyResolver() { return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()); } /** * 按URL限流,即以每秒内请求数按URL分组统计,超出限流的url请求都将返回429状态 * * @return */ @Bean KeyResolver apiKeyResolver() { return exchange -> Mono.just(exchange.getRequest().getPath().toString()); } /** * 按用户限流(现阶段以用户来限流) * * @return */ @Bean @Primary KeyResolver tokenResolver() { return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst(JwtConstant.AUTHORIZATION)); } /** * 按IP来限流 * * @return */ @Bean KeyResolver ipResolver() { return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName()); } }
075a7298be2f22a492a372b03b2d3690123ad25c
34c7c10fb7d32fad737e6a3175e477e6591badcd
/src/main/java/refactoringLearnings/initial/RegularPrice.java
b940d315f2ff260e9260338d8f6972df1fea0219
[]
no_license
guptajyoti845/Clean-code-learning
228a55e07032f4484d763cd57c6059a0172914ea
1d94456dc696a82a0e8ad57001dbb13036cb3f32
refs/heads/main
2023-03-10T10:29:26.156516
2021-02-21T19:17:40
2021-02-21T19:17:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
298
java
package refactoringLearnings.initial; public class RegularPrice extends Price { int getPriceCode() { return Movie.REGULAR; } double getCharge(int daysRented){ double result = 2; if (daysRented > 2) result += (daysRented - 2) * 1.5; return result; } }
380fd780bfb2ca2dff35c63d6d06e5f2c6523fae
a2435e2adc2a86811681ed5dacfe5d79db0aa2df
/in-class activity/Interface/Trio.java
881579630cf3df565cf3902c3cdb00806b90be7c
[]
no_license
Mookiies/AP-Computer-Science2015-2016
8995308b76bcbef0c3a71188144e4bd4e613a8af
52bd6fa572027e66e7de9b4f6629f672491c60a4
refs/heads/master
2021-06-15T23:47:13.916861
2017-03-30T21:26:49
2017-03-30T21:26:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
636
java
import java.util.*; /** * Write a description of class Trio here. * * @author (your name) * @version (a version number or a date) */ public class Trio implements MenuItem { private String name; private double price; public Trio(Sandwitche sand, Coke coke, Salad salad) { name = sand.getName() + "/" + coke.getName() + "/" + salad.getName(); double[] pr = {sand.getPrice(), coke.getPrice(), salad.getPrice()}; Arrays.sort(pr); price = pr[1] + pr[2]; } public String getName(){ return name; } public double getPrice(){ return price; } }
3df241fafd9a4e5db0f1e673f609bc76a401624c
bc794d54ef1311d95d0c479962eb506180873375
/keren_sms/smsgateway/src/main/java/com/keren/smsgateway/modem/athandler/ATHandler_Siemens_S55.java
d5ce224009d09ce04f2231a012bd653ce90fc147
[]
no_license
Teratech2018/Teratech
d1abb0f71a797181630d581cf5600c50e40c9663
612f1baf9636034cfa5d33a91e44bbf3a3f0a0cb
refs/heads/master
2021-04-28T05:31:38.081955
2019-04-01T08:35:34
2019-04-01T08:35:34
122,177,253
0
0
null
null
null
null
UTF-8
Java
false
false
1,123
java
// SMSLib for Java v3 // A Java API library for sending and receiving SMS via a GSM modem // or other supported gateways. // Web Site: http://www.smslib.org // // Copyright (C) 2002-2009, Thanasis Delenikas, Athens/GREECE. // SMSLib is distributed under the terms of the Apache License version 2.0 // // 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.keren.smsgateway.modem.athandler; import com.keren.smsgateway.modem.ModemGateway; public class ATHandler_Siemens_S55 extends ATHandler { public ATHandler_Siemens_S55(ModemGateway myGateway) { super(myGateway); setStorageLocations("MTSMMESR"); } }
dd3d934a7dc1371e87568fde5a8f522171b1edf9
606ba140b738deac354d33120f818435cd33c1b3
/app/src/main/java/cdfproject/com/github/CDFandroidUI/view/LXiuXiu.java
09ed2c42ba2efec99c97770aeb691de2b2715175
[]
no_license
cdfproject/CDFandroidUI
0d7f659c740ead2faa16c994990577d40a7ffd65
2849fb29a333daa57489e0398d4cb7b6d3707c56
refs/heads/master
2016-09-13T12:39:37.941846
2016-04-25T05:53:40
2016-04-25T05:53:40
57,004,032
0
0
null
null
null
null
UTF-8
Java
false
false
9,841
java
package cdfproject.com.github.CDFandroidUI.view; import java.util.ArrayList; import java.util.Iterator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.RadialGradient; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.Shader.TileMode; import android.graphics.drawable.BitmapDrawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; /** * 支付宝咻一咻的View实现版 因为不太喜欢原版的部分效果 所以略有改动 * 使用新的BitmapShader绘制圆形图片,算是对LView里面的圆形图片制作方式的弥补 * * @author LiuJ * */ public class LXiuXiu extends ImageView { private Paint paint; private Bitmap bitmap; private Bitmap img; private int color = 0; private int width, height; private ArrayList<Integer> radius; private int maxRadiu; private Integer step = 0; private float imgRatio = 0.3f; private Shader mRadialGradient = null; private int red, green, blue; private LXiuXiuOnClickListener listener; private XiuXiuType xiuXiuType = XiuXiuType.OUT; private WaveType waveType = WaveType.SHADE; private int stepRatio = 5; private Matrix matrix; int bitmapRadiu = 0; private Paint bitmapPaint; private void init() { bitmapRadiu = (int) (maxRadiu * imgRatio); if (bitmapRadiu > Math.min(width, height) / 2) { bitmapRadiu = Math.min(width, height) / 2; } img = ((BitmapDrawable) getDrawable()).getBitmap(); //使用Xfermode绘制圆形图片 // bitmap = getCroppedRoundBitmap(img, bitmapRadiu); //使用BitmapShader绘制圆形图片 getCroppedRoundBitmap2(img, bitmapRadiu); if (color == 0) color = img.getPixel(img.getWidth() / 2, img.getHeight() / 2); if (step == 0) step = (maxRadiu - bitmapRadiu) / 100 * stepRatio; red = Color.red(color); green = Color.green(color); blue = Color.blue(color); onChange(); } private void onChange() { Iterator<Integer> it = radius.iterator(); switch (xiuXiuType) { case IN: while (it.hasNext()) { if (it.next() >= maxRadiu * (1 - imgRatio)) it.remove(); } break; case OUT: while (it.hasNext()) { if (it.next() >= maxRadiu) it.remove(); } break; } for (int i = 0; i < radius.size(); i++) { radius.set(i, radius.get(i) + step); } } private void setColor(int r) { int alpha = 0; switch (xiuXiuType) { case IN: alpha = (int) ((maxRadiu * (1 - imgRatio) - r) * 1.0 / maxRadiu * 255); break; case OUT: alpha = (int) ((maxRadiu - r) * 1.0 / maxRadiu * 255); break; } if (alpha > 255) alpha = 255; if (alpha < 0) alpha = 0; int edgeColor = Color.argb(alpha, red, green, blue); mRadialGradient = new RadialGradient(width / 2, height / 2, r + maxRadiu * imgRatio, Color.TRANSPARENT, edgeColor, TileMode.REPEAT); paint.setShader(mRadialGradient); } private void setColor2(int r) { int alpha = 0; switch (xiuXiuType) { case IN: alpha = (int) ((maxRadiu * (1 - imgRatio) - r) * 1.0 / maxRadiu * 255); break; case OUT: alpha = (int) ((maxRadiu - r) * 1.0 / maxRadiu * 255); break; } if (alpha > 255) alpha = 255; if (alpha < 0) alpha = 0; paint.setAlpha(alpha); } @Override protected void onDraw(Canvas canvas) { switch (waveType) { case ALWAYS: paint.setColor(color); for (Integer i : radius) { setColor2(i); canvas.drawCircle(width / 2, height / 2, i + (maxRadiu * imgRatio), paint); } paint.setAlpha(255); break; case SHADE: for (Integer i : radius) { setColor(i); canvas.drawCircle(width / 2, height / 2, i + (maxRadiu * imgRatio), paint); } break; } //使用Xfermode绘制圆形图片 // canvas.drawBitmap(bitmap, width / 2 - bitmap.getWidth() / 2, height / 2 - bitmap.getHeight() / 2, paint); //使用BitmapShader绘制圆形图片 canvas.save(); canvas.translate(width / 2-bitmapRadiu, height/2-bitmapRadiu); canvas.drawCircle(bitmapRadiu, bitmapRadiu, bitmapRadiu, bitmapPaint); canvas.restore(); if (radius.size() > 0) { onChange(); invalidate(); } } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_UP: if(isClick(event.getX(),event.getY())){ radius.add(0); invalidate(); if (listener != null) { listener.onXiu(this); } return true; } break; default: break; } // return super.onTouchEvent(event); return true; } private boolean isClick(float x,float y){ double x1 = Math.abs(x-width/2); double y1 = Math.abs(y-height/2); double r = Math.abs(Math.sqrt(x1*x1+y1*y1)); if(r<bitmapRadiu) return true; return false; } public LXiuXiu(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Style.FILL); bitmapPaint = new Paint(); bitmapPaint.setAntiAlias(true); radius = new ArrayList<Integer>(); } public LXiuXiu(Context context, AttributeSet attrs) { this(context, attrs, 0); } public LXiuXiu(Context context) { this(context, null); } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { width = getWidth(); height = getHeight(); switch (this.xiuXiuType) { case IN: maxRadiu = Math.min(height, width) / 2; break; case OUT: maxRadiu = Math.max(height, width) / 2; break; } init(); super.onWindowFocusChanged(hasWindowFocus); } /** * 获取裁剪后的圆形图片 * * @param radius * 半径 */ public Bitmap getCroppedRoundBitmap(Bitmap bmp, int radius) { Bitmap scaledSrcBmp; int diameter = radius * 2; // 为了防止宽高不相等,造成圆形图片变形,因此截取长方形中处于中间位置最大的正方形图片 int bmpWidth = bmp.getWidth(); int bmpHeight = bmp.getHeight(); int squareWidth = 0, squareHeight = 0; int x = 0, y = 0; Bitmap squareBitmap; if (bmpHeight > bmpWidth) {// 高大于宽 squareWidth = squareHeight = bmpWidth; x = 0; y = (bmpHeight - bmpWidth) / 2; // 截取正方形图片 squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth, squareHeight); } else if (bmpHeight < bmpWidth) {// 宽大于高 squareWidth = squareHeight = bmpHeight; x = (bmpWidth - bmpHeight) / 2; y = 0; squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth, squareHeight); } else { squareBitmap = bmp; } if (squareBitmap.getWidth() != diameter || squareBitmap.getHeight() != diameter) { scaledSrcBmp = Bitmap.createScaledBitmap(squareBitmap, diameter, diameter, true); } else { scaledSrcBmp = squareBitmap; } Bitmap output = Bitmap.createBitmap(scaledSrcBmp.getWidth(), scaledSrcBmp.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); Paint paint = new Paint(); Rect rect = new Rect(0, 0, scaledSrcBmp.getWidth(), scaledSrcBmp.getHeight()); paint.setAntiAlias(true); paint.setFilterBitmap(true); paint.setDither(true); canvas.drawARGB(0, 0, 0, 0); canvas.drawCircle(scaledSrcBmp.getWidth() / 2, scaledSrcBmp.getHeight() / 2, scaledSrcBmp.getWidth() / 2, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(scaledSrcBmp, rect, rect, paint); bmp = null; squareBitmap = null; scaledSrcBmp = null; return output; } /** * 使用渲染来绘制圆形图片 * * @param bmp * @param radius * @return */ public void getCroppedRoundBitmap2(Bitmap bmp, int radius) { // 将bmp作为着色器,就是在指定区域内绘制bmp Shader mBitmapShader = new BitmapShader(bmp, TileMode.CLAMP, TileMode.CLAMP); float scale = 1.0f; // 如果图片的宽或者高与view的宽高不匹配,计算出需要缩放的比例;缩放后的图片的宽高,一定要大于我们view的宽高;所以我们这里取大值; scale = Math.max(radius * 2.0f / bmp.getWidth(), radius * 2.0f / bmp.getHeight()); if(matrix==null){ matrix = new Matrix(); } // shader的变换矩阵,我们这里主要用于放大或者缩小 matrix.setScale(scale, scale); // 设置变换矩阵 mBitmapShader.setLocalMatrix(matrix); // 设置shader bitmapPaint.setShader(mBitmapShader); } public interface LXiuXiuOnClickListener { public void onXiu(View v); } public LXiuXiuOnClickListener getListener() { return listener; } public void setListener(LXiuXiuOnClickListener listener) { this.listener = listener; } public int getColor() { return color; } public Integer getStep() { return stepRatio; } /** * 最大99 最小1 * * @param step */ public void setStep(int step) { stepRatio = step; } public float getImgRatio() { return imgRatio; } public void setImgRatio(float imgRatio) { this.imgRatio = imgRatio; } public XiuXiuType getXiuXiuType() { return xiuXiuType; } /** * 设置波浪范围 * * @param xiuXiuType */ public void setXiuXiuType(XiuXiuType xiuXiuType) { this.xiuXiuType = xiuXiuType; switch (this.xiuXiuType) { case IN: maxRadiu = Math.min(height, width) / 2; break; case OUT: maxRadiu = Math.max(height, width) / 2; break; } } public WaveType getWaveType() { return waveType; } /** * 设置波浪样式 * * @param waveType */ public void setWaveType(WaveType waveType) { this.waveType = waveType; } public enum WaveType { SHADE, ALWAYS } public enum XiuXiuType { IN, OUT } }
d64bfb3fdacb8b54f43fcd063ba0f43c38c863b2
e42f8a352420d11623a27ad35bd5adc9add4dbb7
/src/main/java/org/tat/gginl/api/common/PolicyInsuredPerson.java
daf86ff873aa70746747bb369cb8257cc270e533
[]
no_license
LifeTeam-TAT/GGINL-API
e9f05c015ade6675c0dfa5b7cfdb32852e1110e5
d04a6367769c71eb87030805c0c8f393f9422386
refs/heads/master
2023-04-01T12:50:59.026177
2021-04-02T13:51:04
2021-04-02T13:51:04
354,031,898
0
0
null
null
null
null
UTF-8
Java
false
false
40,834
java
package org.tat.gginl.api.common; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.Version; import org.tat.gginl.api.common.emumdata.ClaimStatus; import org.tat.gginl.api.common.emumdata.ClassificationOfHealth; import org.tat.gginl.api.common.emumdata.EndorsementStatus; import org.tat.gginl.api.common.emumdata.Gender; import org.tat.gginl.api.common.emumdata.IdType; import org.tat.gginl.api.common.emumdata.PeriodType; import org.tat.gginl.api.common.emumdata.SumInsuredType; import org.tat.gginl.api.common.emumdata.SurveyAnswerOne; import org.tat.gginl.api.common.emumdata.SurveyAnswerTwo; import org.tat.gginl.api.domains.Attachment; import org.tat.gginl.api.domains.Customer; import org.tat.gginl.api.domains.GradeInfo; import org.tat.gginl.api.domains.InsuredPersonAddon; import org.tat.gginl.api.domains.InsuredPersonAttachment; import org.tat.gginl.api.domains.InsuredPersonBeneficiaries; import org.tat.gginl.api.domains.InsuredPersonKeyFactorValue; import org.tat.gginl.api.domains.LifePolicy; import org.tat.gginl.api.domains.Occupation; import org.tat.gginl.api.domains.PolicyInsuredPersonAddonHistory; import org.tat.gginl.api.domains.PolicyInsuredPersonAttachment; import org.tat.gginl.api.domains.PolicyInsuredPersonAttachmentHistory; import org.tat.gginl.api.domains.PolicyInsuredPersonBeneficiariesHistory; import org.tat.gginl.api.domains.PolicyInsuredPersonHistory; import org.tat.gginl.api.domains.PolicyInsuredPersonKeyFactorValue; import org.tat.gginl.api.domains.PolicyInsuredPersonKeyFactorValueHistory; import org.tat.gginl.api.domains.Product; import org.tat.gginl.api.domains.ProposalInsuredPerson; import org.tat.gginl.api.domains.RelationShip; import org.tat.gginl.api.domains.School; import org.tat.gginl.api.domains.TypesOfSport; @Entity @Table(name = TableName.LIFEPOLICYINSUREDPERSON) @TableGenerator(name = "LPOLINSURPERSON_GEN", table = "ID_GEN", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL", pkColumnValue = "LPOLINSURPERSON_GEN", allocationSize = 10) @NamedQueries(value = { @NamedQuery(name = "PolicyInsuredPerson.findAll", query = "SELECT s FROM PolicyInsuredPerson s "), @NamedQuery(name = "PolicyInsuredPerson.findById", query = "SELECT s FROM PolicyInsuredPerson s WHERE s.id = :id"), @NamedQuery(name = "PolicyInsuredPerson.updateClaimStatus", query = "UPDATE PolicyInsuredPerson p SET p.claimStatus = :claimStatus WHERE p.id = :id") }) @Access(value = AccessType.FIELD) public class PolicyInsuredPerson implements IInsuredItem, Serializable { private static final long serialVersionUID = -1810680158208016018L; @Transient private String id; private String prefix; @Column(name = "PERIODOFMONTH") private int periodMonth; @Column(name = "PERIODOFYEAR") private int periodYear; @Column(name = "PERIODOFWEEK") private int periodWeek; @Column(name = "AGE") private int age; private int paymentTerm; private double sumInsured; private double premium; private double basicTermPremium; private double addOnTermPremium; private double endorsementNetBasicPremium; private double endorsementNetAddonPremium; private double interest; @Column(name = "INPERSONCODENO") private String insPersonCodeNo; @Column(name = "INPERSONGROUPCODENO") private String inPersonGroupCodeNo; private String initialId; private String idNo; private String fatherName; private String parentName; private String parentIdNo; @Enumerated(value = EnumType.STRING) private IdType parentIdType; private Date parentDOB; private int unit; private int weight; private int height; private double bmi; private SurveyAnswerOne surveyquestionOne; private SurveyAnswerTwo surveyquestionTwo; @Temporal(TemporalType.DATE) private Date dateOfBirth; @Temporal(TemporalType.DATE) private Date startDate; @Temporal(TemporalType.DATE) private Date endDate; @Enumerated(value = EnumType.STRING) private Gender gender; @Enumerated(value = EnumType.STRING) private IdType idType; @Enumerated(EnumType.STRING) private EndorsementStatus endorsementStatus; @Enumerated(EnumType.STRING) private ClaimStatus claimStatus; @Enumerated(value = EnumType.STRING) private ClassificationOfHealth clsOfHealth; @Enumerated(value = EnumType.STRING) private PeriodType periodType; @Embedded private ResidentAddress residentAddress; @Embedded private Name name; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "PRODUCTID", referencedColumnName = "ID") private Product product; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "OCCUPATIONID", referencedColumnName = "ID") private Occupation occupation; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "CUSTOMERID", referencedColumnName = "ID") private Customer customer; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "TYPESOFSPORTID", referencedColumnName = "ID") private TypesOfSport typesOfSport; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "LIFEPOLICYID", referencedColumnName = "ID") private LifePolicy lifePolicy; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "RELATIONSHIPID", referencedColumnName = "ID") private RelationShip relationShip; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "SCHOOLID", referencedColumnName = "ID") private School school; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "GRATEINFOID", referencedColumnName = "ID") private GradeInfo gradeInfo; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "policyInsuredPerson", orphanRemoval = true) private List<PolicyInsuredPersonAttachment> attachmentList; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "HOLDERID", referencedColumnName = "ID") private List<Attachment> birthCertificateAttachment; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "policyInsuredPerson", orphanRemoval = true) private List<PolicyInsuredPersonAddon> policyInsuredPersonAddOnList; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "policyInsuredPerson", orphanRemoval = true) private List<PolicyInsuredPersonKeyFactorValue> policyInsuredPersonkeyFactorValueList; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "policyInsuredPerson", orphanRemoval = true) private List<PolicyInsuredPersonBeneficiaries> policyInsuredPersonBeneficiariesList; @Transient private String bpmsInsuredPersonId; @Version private int version; @Transient private boolean newCustomer; @Embedded private CommonCreateAndUpateMarks recorder; @Enumerated(value = EnumType.STRING) private SumInsuredType sumInsuredType; public boolean isNewCustomer() { return newCustomer; } public void setNewCustomer(boolean newCustomer) { this.newCustomer = newCustomer; } public PolicyInsuredPerson() { } public PolicyInsuredPerson(ProposalInsuredPerson insuredPerson) { this.dateOfBirth = insuredPerson.getDateOfBirth(); this.recorder = insuredPerson.getRecorder(); this.clsOfHealth = insuredPerson.getClsOfHealth(); this.sumInsured = insuredPerson.getProposedSumInsured(); this.periodMonth = insuredPerson.getPeriodMonth(); this.startDate = insuredPerson.getStartDate(); this.endDate = insuredPerson.getEndDate(); this.product = insuredPerson.getProduct(); this.premium = insuredPerson.getApprovedPremium(); this.paymentTerm = insuredPerson.getPaymentTerm(); this.basicTermPremium = insuredPerson.getBasicTermPremium(); this.addOnTermPremium = insuredPerson.getAddOnTermPremium(); this.endorsementNetBasicPremium = insuredPerson.getEndorsementNetBasicPremium(); this.endorsementNetAddonPremium = insuredPerson.getEndorsementNetAddonPremium(); this.interest = insuredPerson.getInterest(); this.insPersonCodeNo = insuredPerson.getInsPersonCodeNo(); this.endorsementStatus = insuredPerson.getEndorsementStatus(); this.initialId = insuredPerson.getInitialId(); this.idNo = insuredPerson.getIdNo(); this.idType = insuredPerson.getIdType(); this.name = insuredPerson.getName(); this.gender = insuredPerson.getGender(); this.residentAddress = insuredPerson.getResidentAddress(); this.occupation = insuredPerson.getOccupation(); this.fatherName = insuredPerson.getFatherName(); this.parentName = insuredPerson.getParentName(); this.parentDOB = insuredPerson.getParentDOB(); this.parentIdType = insuredPerson.getParentIdType(); this.parentIdNo = insuredPerson.getParentIdNo(); this.customer = insuredPerson.getCustomer(); this.age = insuredPerson.getAge(); this.inPersonGroupCodeNo = insuredPerson.getInPersonGroupCodeNo(); this.typesOfSport = insuredPerson.getTypesOfSport(); this.unit = insuredPerson.getUnit(); this.relationShip = insuredPerson.getRelationship(); this.school = insuredPerson.getSchool(); this.gradeInfo = insuredPerson.getGradeInfo(); this.bpmsInsuredPersonId = insuredPerson.getBpmsInsuredPersonId(); this.newCustomer = insuredPerson.isNewCustomer(); this.sumInsuredType = insuredPerson.getSumInsuredType(); this.periodType = insuredPerson.getPeriodType(); this.bmi = insuredPerson.getBmi(); this.weight = insuredPerson.getWeight(); this.height = insuredPerson.getHeight(); this.surveyquestionOne = insuredPerson.getSurveyquestionOne(); this.surveyquestionTwo = insuredPerson.getSurveyquestionTwo(); this.periodWeek = insuredPerson.getPeriodWeek(); this.periodYear = insuredPerson.getPeriodYear(); for (InsuredPersonAttachment attachment : insuredPerson.getAttachmentList()) { addAttachment(new PolicyInsuredPersonAttachment(attachment)); } for (Attachment attachment : insuredPerson.getBirthCertificateAttachment()) { addBirthCertificateAttachment(new Attachment(attachment)); } for (InsuredPersonAddon addOn : insuredPerson.getInsuredPersonAddOnList()) { addInsuredPersonAddOn(new PolicyInsuredPersonAddon(addOn)); } for (InsuredPersonKeyFactorValue keyFactorValue : insuredPerson.getKeyFactorValueList()) { addPolicyInsuredPersonKeyFactorValue(new PolicyInsuredPersonKeyFactorValue(keyFactorValue)); } for (InsuredPersonBeneficiaries insuredPersonBeneficiaries : insuredPerson.getInsuredPersonBeneficiariesList()) { addInsuredPersonBeneficiaries(new PolicyInsuredPersonBeneficiaries(insuredPersonBeneficiaries)); } } public PolicyInsuredPerson(PolicyInsuredPersonHistory history) { this.periodMonth = history.getPeriodMonth(); this.age = history.getAge(); this.paymentTerm = history.getPaymentTerm(); this.sumInsured = history.getSumInsured(); this.premium = history.getPremium(); this.basicTermPremium = history.getBasicTermPremium(); this.addOnTermPremium = history.getAddOnTermPremium(); this.endorsementNetBasicPremium = history.getEndorsementNetBasicPremium(); this.endorsementNetAddonPremium = history.getEndorsementNetAddonPremium(); this.interest = history.getInterest(); this.insPersonCodeNo = history.getInPersonCodeNo(); this.inPersonGroupCodeNo = history.getInPersonGroupCodeNo(); this.initialId = history.getInitialId(); this.idNo = history.getIdNo(); this.fatherName = history.getFatherName(); this.dateOfBirth = history.getDateOfBirth(); this.startDate = history.getStartDate(); this.endDate = history.getEndDate(); this.gender = history.getGender(); this.idType = history.getIdType(); this.endorsementStatus = history.getEndorsementStatus(); this.claimStatus = history.getClaimStatus(); this.clsOfHealth = history.getClsOfHealth(); this.residentAddress = history.getResidentAddress(); this.name = history.getName(); this.product = history.getProduct(); this.occupation = history.getOccupation(); this.customer = history.getCustomer(); this.typesOfSport = history.getTypesOfSport(); this.relationShip = history.getRelationShip(); this.school = history.getSchool(); this.gradeInfo = history.getGradeInfo(); this.sumInsuredType = history.getSumInsuredType(); for (PolicyInsuredPersonAttachmentHistory attachment : history.getAttachmentList()) { addAttachment(new PolicyInsuredPersonAttachment(attachment)); } for (Attachment attachment : history.getBirthCertificateAttachment()) { addBirthCertificateAttachment(new Attachment(attachment)); } for (PolicyInsuredPersonKeyFactorValueHistory keyFactorValue : history.getPolicyInsuredPersonkeyFactorValueList()) { addPolicyInsuredPersonKeyFactorValue(new PolicyInsuredPersonKeyFactorValue(keyFactorValue)); } for (PolicyInsuredPersonBeneficiariesHistory insuredPersonBeneficiaries : history.getPolicyInsuredPersonBeneficiariesList()) { addInsuredPersonBeneficiaries(new PolicyInsuredPersonBeneficiaries(insuredPersonBeneficiaries)); } for (PolicyInsuredPersonAddonHistory addOn : history.getPolicyInsuredPersonAddOnList()) { addInsuredPersonAddOn(new PolicyInsuredPersonAddon(addOn)); } } public PolicyInsuredPerson(InsuredPersonInfoDTO dto) { this.periodMonth = dto.getPeriodMonth(); this.age = dto.getAge(); this.paymentTerm = dto.getPaymentTerm(); this.sumInsured = dto.getSumInsuredInfo(); this.premium = dto.getPremium(); this.basicTermPremium = dto.getBasicTermPremium(); this.addOnTermPremium = dto.getAddOnTermPremium(); this.endorsementNetBasicPremium = dto.getEndorsementBasicPremium(); this.endorsementNetAddonPremium = dto.getEndorsementAddonPremium(); this.interest = dto.getInterest(); this.insPersonCodeNo = dto.getInsPersonCodeNo(); this.inPersonGroupCodeNo = dto.getInPersonGroupCodeNo(); this.initialId = dto.getInitialId(); this.idNo = dto.getIdNo(); this.fatherName = dto.getFatherName(); this.dateOfBirth = dto.getDateOfBirth(); this.startDate = dto.getStartDate(); this.endDate = dto.getEndDate(); this.gender = dto.getGender(); this.idType = dto.getIdType(); this.endorsementStatus = dto.getEndorsementStatus(); this.claimStatus = dto.getClaimStatus(); this.clsOfHealth = dto.getClassificationOfHealth(); this.residentAddress = dto.getResidentAddress(); this.name = dto.getName(); this.product = dto.getProduct(); this.occupation = dto.getOccupation(); this.customer = dto.getCustomer(); this.typesOfSport = dto.getTypesOfSport(); this.relationShip = dto.getRelationShip(); this.school = dto.getSchool(); this.gradeInfo = dto.getGradeInfo(); this.sumInsuredType = dto.getSumInsuredType(); for (PolicyInsuredPersonAttachment attach : dto.getPrePolicyAttachmentList()) { addAttachment(attach); } for (Attachment attach : dto.getBirthCertificateAttachments()) { addBirthCertificateAttachment(attach); } for (PolicyInsuredPersonKeyFactorValue kfv : dto.getPolicyKeyFactorValueList()) { addPolicyInsuredPersonKeyFactorValue(kfv); } for (BeneficiariesInfoDTO beneficiary : dto.getBeneficiariesInfoDTOList()) { addInsuredPersonBeneficiaries(new PolicyInsuredPersonBeneficiaries(beneficiary)); } for (InsuredPersonAddOnDTO addOn : dto.getInsuredPersonAddOnDTOMap().values()) { addInsuredPersonAddOn(new PolicyInsuredPersonAddon(addOn)); } if (dto.isExistsEntity()) { this.id = dto.getTempId(); this.version = dto.getVersion(); } } public PolicyInsuredPerson(Date dateOfBirth, double sumInsured, Product product, LifePolicy lifePolicy, int periodMonth, Date startDate, Date endDate, double premium, double endorsementNetBasicPremium, double endorsementNetAddonPremium, double interest, String insPersonCodeNo, EndorsementStatus endorsementStatus, String inPersonGroupCodeNo) { this.endorsementStatus = endorsementStatus; this.dateOfBirth = dateOfBirth; this.sumInsured = sumInsured; this.product = product; this.lifePolicy = lifePolicy; this.periodMonth = periodMonth; this.startDate = startDate; this.endDate = endDate; this.premium = premium; this.endorsementNetBasicPremium = endorsementNetAddonPremium; this.endorsementNetAddonPremium = endorsementNetAddonPremium; this.insPersonCodeNo = insPersonCodeNo; this.interest = interest; this.inPersonGroupCodeNo = inPersonGroupCodeNo; } public PolicyInsuredPerson(Date dateOfBirth, double sumInsured, Product product, LifePolicy lifePolicy, int periodMonth, Date startDate, Date endDate, double premium, String initialId, String idNo, IdType idType, Name name, Gender gender, ResidentAddress residentAddress, Occupation occupation, String fatherName, double endorsementNetBasicPremium, double endorsementNetAddonPremium, double interest, EndorsementStatus status, String insPersonCodeNo, Customer customer, int age, String inPersonGroupCodeNo, int paymentTerm, double basicTermPremium, double addOnTermPremium, ClaimStatus claimStatus) { this.dateOfBirth = dateOfBirth; this.sumInsured = sumInsured; this.product = product; this.lifePolicy = lifePolicy; this.periodMonth = periodMonth; this.startDate = startDate; this.endDate = endDate; this.premium = premium; this.initialId = initialId; this.idNo = idNo; this.idType = idType; this.name = name; this.residentAddress = residentAddress; this.gender = gender; this.occupation = occupation; this.fatherName = fatherName; this.endorsementNetBasicPremium = endorsementNetBasicPremium; this.endorsementNetAddonPremium = endorsementNetAddonPremium; this.interest = interest; this.endorsementStatus = status; this.insPersonCodeNo = insPersonCodeNo; this.customer = customer; this.age = age; this.inPersonGroupCodeNo = inPersonGroupCodeNo; this.paymentTerm = paymentTerm; this.basicTermPremium = basicTermPremium; this.addOnTermPremium = addOnTermPremium; this.claimStatus = claimStatus; } @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "LPOLINSURPERSON_GEN") @Access(value = AccessType.PROPERTY) public String getId() { return id; } public void setId(String id) { if (id != null) { this.id = FormatID.formatId(id, getPrefix(), 10); } } public void overwriteId(String id) { this.id = id; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public int getPeriodMonth() { return periodMonth; } public int getPeriodYears() { return periodMonth / 12; } public void setPeriodMonth(int periodMonth) { this.periodMonth = periodMonth; } public int getPeriodYear() { return periodYear; } public void setPeriodYear(int periodYear) { this.periodYear = periodYear; } public int getPeriodWeek() { return periodWeek; } public void setPeriodWeek(int periodWeek) { this.periodWeek = periodWeek; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public double getSumInsured() { return sumInsured; } public void setSumInsured(double sumInsured) { this.sumInsured = sumInsured; } public double getPremium() { return premium; } public void setPremium(double premium) { this.premium = premium; } public int getPaymentTerm() { return paymentTerm; } public void setPaymentTerm(int paymentTerm) { this.paymentTerm = paymentTerm; } public double getBasicTermPremium() { return basicTermPremium; } public void setBasicTermPremium(double basicTermPremium) { this.basicTermPremium = basicTermPremium; } public double getAddOnTermPremium() { return addOnTermPremium; } public void setAddOnTermPremium(double addOnTermPremium) { this.addOnTermPremium = addOnTermPremium; } public EndorsementStatus getEndorsementStatus() { return endorsementStatus; } public void setEndorsementStatus(EndorsementStatus endorsementStatus) { this.endorsementStatus = endorsementStatus; } public double getEndorsementNetBasicPremium() { return endorsementNetBasicPremium; } public void setEndorsementNetBasicPremium(double endorsementNetBasicPremium) { this.endorsementNetBasicPremium = endorsementNetBasicPremium; } public double getEndorsementNetAddonPremium() { return endorsementNetAddonPremium; } public void setEndorsementNetAddonPremium(double endorsementNetAddonPremium) { this.endorsementNetAddonPremium = endorsementNetAddonPremium; } public double getInterest() { return interest; } public void setInterest(double interest) { this.interest = interest; } public String getInsPersonCodeNo() { return insPersonCodeNo; } public void setInsPersonCodeNo(String insPersonCodeNo) { this.insPersonCodeNo = insPersonCodeNo; } public String getInPersonGroupCodeNo() { return inPersonGroupCodeNo; } public void setInPersonGroupCodeNo(String inPersonGroupCodeNo) { this.inPersonGroupCodeNo = inPersonGroupCodeNo; } public List<PolicyInsuredPersonAttachment> getAttachmentList() { if (this.attachmentList == null) { this.attachmentList = new ArrayList<PolicyInsuredPersonAttachment>(); } return this.attachmentList; } public void setAttachmentList(List<PolicyInsuredPersonAttachment> attachmentList) { this.attachmentList = attachmentList; } public List<Attachment> getBirthCertificateAttachment() { if (this.birthCertificateAttachment == null) { this.birthCertificateAttachment = new ArrayList<Attachment>(); } return birthCertificateAttachment; } public void setBirthCertificateAttachment(List<Attachment> birthCertificateAttachment) { this.birthCertificateAttachment = birthCertificateAttachment; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public LifePolicy getLifePolicy() { return lifePolicy; } public void setLifePolicy(LifePolicy lifePolicy) { this.lifePolicy = lifePolicy; } public List<PolicyInsuredPersonAddon> getPolicyInsuredPersonAddOnList() { if (policyInsuredPersonAddOnList == null) { policyInsuredPersonAddOnList = new ArrayList<PolicyInsuredPersonAddon>(); } return policyInsuredPersonAddOnList; } public void setPolicyInsuredPersonAddOnList(List<PolicyInsuredPersonAddon> policyInsuredPersonAddOnList) { this.policyInsuredPersonAddOnList = policyInsuredPersonAddOnList; } public List<PolicyInsuredPersonKeyFactorValue> getPolicyInsuredPersonkeyFactorValueList() { if (policyInsuredPersonkeyFactorValueList == null) { policyInsuredPersonkeyFactorValueList = new ArrayList<PolicyInsuredPersonKeyFactorValue>(); } return policyInsuredPersonkeyFactorValueList; } public void setPolicyInsuredPersonkeyFactorValueList(List<PolicyInsuredPersonKeyFactorValue> policyInsuredPersonkeyFactorValueList) { this.policyInsuredPersonkeyFactorValueList = policyInsuredPersonkeyFactorValueList; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public List<PolicyInsuredPersonBeneficiaries> getPolicyInsuredPersonBeneficiariesList() { if (this.policyInsuredPersonBeneficiariesList == null) { this.policyInsuredPersonBeneficiariesList = new ArrayList<PolicyInsuredPersonBeneficiaries>(); } return this.policyInsuredPersonBeneficiariesList; } public void setPolicyInsuredPersonBeneficiariesList(List<PolicyInsuredPersonBeneficiaries> policyInsuredPersonBeneficiariesList) { this.policyInsuredPersonBeneficiariesList = policyInsuredPersonBeneficiariesList; } public void addAttachment(PolicyInsuredPersonAttachment attachment) { attachment.setPolicyInsuredPerson(this); getAttachmentList().add(attachment); } public void addBirthCertificateAttachment(Attachment attachment) { getBirthCertificateAttachment().add(attachment); } public void addInsuredPersonAddOn(PolicyInsuredPersonAddon policyInsuredPersonAddOn) { policyInsuredPersonAddOn.setPolicyInsuredPersonInfo(this); getPolicyInsuredPersonAddOnList().add(policyInsuredPersonAddOn); } public void addPolicyInsuredPersonKeyFactorValue(PolicyInsuredPersonKeyFactorValue keyFactorValue) { keyFactorValue.setPolicyInsuredPersonInfo(this); getPolicyInsuredPersonkeyFactorValueList().add(keyFactorValue); } public void addInsuredPersonBeneficiaries(PolicyInsuredPersonBeneficiaries policyInsuredPersonBeneficiaries) { policyInsuredPersonBeneficiaries.setPolicyInsuredPerson(this); getPolicyInsuredPersonBeneficiariesList().add(policyInsuredPersonBeneficiaries); } public int getPremiumTerm() { return getPeriodYears() - 3; } public ClaimStatus getClaimStatus() { return claimStatus; } public void setClaimStatus(ClaimStatus claimStatus) { this.claimStatus = claimStatus; } public ClassificationOfHealth getClsOfHealth() { return clsOfHealth; } public void setClsOfHealth(ClassificationOfHealth clsOfHealth) { this.clsOfHealth = clsOfHealth; } public String getInitialId() { return initialId; } public void setInitialId(String initialId) { this.initialId = initialId; } public String getIdNo() { return idNo; } public void setIdNo(String idNo) { this.idNo = idNo; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public IdType getIdType() { return idType; } public void setIdType(IdType idType) { this.idType = idType; } public ResidentAddress getResidentAddress() { return residentAddress; } public void setResidentAddress(ResidentAddress residentAddress) { this.residentAddress = residentAddress; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } public Occupation getOccupation() { return occupation; } public void setOccupation(Occupation occupation) { this.occupation = occupation; } public String getFatherName() { return fatherName; } public void setFatherName(String fatherName) { this.fatherName = fatherName; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } public RelationShip getRelationShip() { return relationShip; } public void setRelationShip(RelationShip relationShip) { this.relationShip = relationShip; } public School getSchool() { return school; } public void setSchool(School school) { this.school = school; } public GradeInfo getGradeInfo() { return gradeInfo; } public void setGradeInfo(GradeInfo gradeInfo) { this.gradeInfo = gradeInfo; } public String getParentIdNo() { return parentIdNo; } public void setParentIdNo(String parentIdNo) { this.parentIdNo = parentIdNo; } public IdType getParentIdType() { return parentIdType; } public void setParentIdType(IdType parentIdType) { this.parentIdType = parentIdType; } public Date getParentDOB() { return parentDOB; } public void setParentDOB(Date parentDOB) { this.parentDOB = parentDOB; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public TypesOfSport getTypesOfSport() { return typesOfSport; } public void setTypesOfSport(TypesOfSport typesOfSport) { this.typesOfSport = typesOfSport; } public int getUnit() { return unit; } public void setUnit(int unit) { this.unit = unit; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public double getBmi() { return bmi; } public void setBmi(double bmi) { this.bmi = bmi; } public SurveyAnswerOne getSurveyquestionOne() { return surveyquestionOne; } public void setSurveyquestionOne(SurveyAnswerOne surveyquestionOne) { this.surveyquestionOne = surveyquestionOne; } public SurveyAnswerTwo getSurveyquestionTwo() { return surveyquestionTwo; } public void setSurveyquestionTwo(SurveyAnswerTwo surveyquestionTwo) { this.surveyquestionTwo = surveyquestionTwo; } public PeriodType getPeriodType() { return periodType; } public void setPeriodType(PeriodType periodType) { this.periodType = periodType; } public CommonCreateAndUpateMarks getRecorder() { return recorder; } public void setRecorder(CommonCreateAndUpateMarks recorder) { this.recorder = recorder; } public double getAddOnPremium() { double premium = 0.0; if (policyInsuredPersonAddOnList != null && !policyInsuredPersonAddOnList.isEmpty()) { for (PolicyInsuredPersonAddon pia : policyInsuredPersonAddOnList) { premium = Utils.getTwoDecimalPoint(premium + pia.getPremium()); } } return premium; } public double getTotalPermium() { return Utils.getTwoDecimalPoint(premium + getAddOnPremium()); } public double getTotalTermPermium() { return Utils.getTwoDecimalPoint(getBasicTermPremium() + getAddOnTermPremium()); } public double getAddOnSumInsure() { double premium = 0.0; if (policyInsuredPersonAddOnList != null && !policyInsuredPersonAddOnList.isEmpty()) { for (PolicyInsuredPersonAddon pia : policyInsuredPersonAddOnList) { premium = premium + pia.getSumInsured(); } } return premium; } public String getFullAddress() { String result = ""; if (residentAddress != null) { if (residentAddress.getResidentAddress() != null && !residentAddress.getResidentAddress().isEmpty()) { result = result + residentAddress.getResidentAddress(); } if (residentAddress.getResidentTownship() != null && !residentAddress.getResidentTownship().getFullTownShip().isEmpty()) { result = result + ", " + residentAddress.getResidentTownship().getFullTownShip(); } } return result; } public List<Date> getTimeSlotList() { List<Date> result = new ArrayList<Date>(); result.add(startDate); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); int months = lifePolicy.getPaymentType().getMonth(); if (months > 0) { int a = 12 / months; for (int i = 1; i < a; i++) { cal.add(Calendar.MONTH, months); result.add(cal.getTime()); } } return result; } public String getTimeSlotListStr() { List<String> result = new ArrayList<String>(); String resultStr = ""; Calendar cal = Calendar.getInstance(); cal.setTime(startDate); int months = lifePolicy.getPaymentType().getMonth(); if (months == 1) { resultStr = "Every " + DateUtils.getHtmlDayString(cal.getTime()) + " day of every month Until " + DateUtils.formatDateToString(lifePolicy.getPaymentEndDate()); return resultStr; } else if (months > 0 && months != 12) { int a = 12 / months; for (int i = 1; i <= a; i++) { result.add(org.tat.gginl.api.common.emumdata.Utils.formattedDate(cal.getTime(), "dd-MMM")); cal.add(Calendar.MONTH, months); } } else if (months == 12) { result.add(org.tat.gginl.api.common.emumdata.Utils.formattedDate(cal.getTime(), "dd-MMM")); } return result != null ? result.toString().substring(1, result.toString().length() - 1) : null; } public Date getLastPaymentDate() { List<Date> dateList = getTimeSlotList(); dateList.add(startDate); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); int months = lifePolicy.getPaymentType().getMonth(); if (months > 0) { for (int i = 1; i < paymentTerm; i++) { cal.add(Calendar.MONTH, months); dateList.add(cal.getTime()); } } if (!dateList.isEmpty()) { int lastIndex = dateList.size() - 1; return dateList.get(lastIndex); } return null; } public int getPaymentTimes() { int monthTimes = lifePolicy.getPaymentType().getMonth(); if (monthTimes > 0) { return periodMonth / monthTimes; } else { return 1; } } public void setPaymentTimes(int paymentTimes) { // do nothing } public int getAgeForNextYear() { Calendar cal_1 = Calendar.getInstance(); int currentYear = cal_1.get(Calendar.YEAR); Calendar cal_2 = Calendar.getInstance(); cal_2.setTime(dateOfBirth); cal_2.set(Calendar.YEAR, currentYear); if (new Date().after(cal_2.getTime())) { Calendar cal_3 = Calendar.getInstance(); cal_3.setTime(dateOfBirth); int year_1 = cal_3.get(Calendar.YEAR); int year_2 = cal_1.get(Calendar.YEAR) + 1; return year_2 - year_1; } else { Calendar cal_3 = Calendar.getInstance(); cal_3.setTime(dateOfBirth); int year_1 = cal_3.get(Calendar.YEAR); int year_2 = cal_1.get(Calendar.YEAR); return year_2 - year_1; } } /** * @see org.ace.insurance.common.interfaces.IPolicy#getTotalPremium() */ public double getTotalPremium() { // TODO Auto-generated method stub return Utils.getTwoDecimalPoint(premium + getAddOnPremium()); } public String getFullName() { String result = ""; if (name != null) { if (initialId != null && !initialId.isEmpty()) { result = initialId.trim(); } if (name.getFirstName() != null && !name.getFirstName().isEmpty()) { result = result + " " + name.getFirstName().trim(); } if (name.getMiddleName() != null && !name.getMiddleName().isEmpty()) { result = result + " " + name.getMiddleName().trim(); } if (name.getLastName() != null && !name.getLastName().isEmpty()) { result = result + " " + name.getLastName().trim(); } } return result; } public String getPeriod() { if (periodMonth / 12 < 1) { return periodMonth + " - Months"; } else { return periodMonth / 12 + " - Year"; } } public String getSchoolName() { if (school != null) return school.getName(); return "-"; } public String getSchoolAddress() { if (school != null && school.getAddress() != null) return school.getFullAddress(); return "-"; } public String getGradeInfoName() { if (gradeInfo != null) return gradeInfo.getName(); return "-"; } public String getBpmsInsuredPersonId() { return bpmsInsuredPersonId; } public void setBpmsInsuredPersonId(String bpmsInsuredPersonId) { this.bpmsInsuredPersonId = bpmsInsuredPersonId; } public SumInsuredType getSumInsuredType() { return sumInsuredType; } public void setSumInsuredType(SumInsuredType sumInsuredType) { this.sumInsuredType = sumInsuredType; } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(addOnTermPremium); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + age; temp = Double.doubleToLongBits(basicTermPremium); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((claimStatus == null) ? 0 : claimStatus.hashCode()); result = prime * result + ((clsOfHealth == null) ? 0 : clsOfHealth.hashCode()); result = prime * result + ((dateOfBirth == null) ? 0 : dateOfBirth.hashCode()); result = prime * result + ((endDate == null) ? 0 : endDate.hashCode()); temp = Double.doubleToLongBits(endorsementNetAddonPremium); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(endorsementNetBasicPremium); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((endorsementStatus == null) ? 0 : endorsementStatus.hashCode()); result = prime * result + ((fatherName == null) ? 0 : fatherName.hashCode()); result = prime * result + ((gender == null) ? 0 : gender.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((idNo == null) ? 0 : idNo.hashCode()); result = prime * result + ((idType == null) ? 0 : idType.hashCode()); result = prime * result + ((inPersonGroupCodeNo == null) ? 0 : inPersonGroupCodeNo.hashCode()); result = prime * result + ((initialId == null) ? 0 : initialId.hashCode()); result = prime * result + ((insPersonCodeNo == null) ? 0 : insPersonCodeNo.hashCode()); temp = Double.doubleToLongBits(interest); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + paymentTerm; result = prime * result + periodMonth; result = prime * result + ((prefix == null) ? 0 : prefix.hashCode()); temp = Double.doubleToLongBits(premium); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((residentAddress == null) ? 0 : residentAddress.hashCode()); result = prime * result + ((startDate == null) ? 0 : startDate.hashCode()); temp = Double.doubleToLongBits(sumInsured); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + unit; result = prime * result + version; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PolicyInsuredPerson other = (PolicyInsuredPerson) obj; if (Double.doubleToLongBits(addOnTermPremium) != Double.doubleToLongBits(other.addOnTermPremium)) return false; if (age != other.age) return false; if (Double.doubleToLongBits(basicTermPremium) != Double.doubleToLongBits(other.basicTermPremium)) return false; if (claimStatus != other.claimStatus) return false; if (clsOfHealth != other.clsOfHealth) return false; if (dateOfBirth == null) { if (other.dateOfBirth != null) return false; } else if (!dateOfBirth.equals(other.dateOfBirth)) return false; if (endDate == null) { if (other.endDate != null) return false; } else if (!endDate.equals(other.endDate)) return false; if (Double.doubleToLongBits(endorsementNetAddonPremium) != Double.doubleToLongBits(other.endorsementNetAddonPremium)) return false; if (Double.doubleToLongBits(endorsementNetBasicPremium) != Double.doubleToLongBits(other.endorsementNetBasicPremium)) return false; if (endorsementStatus != other.endorsementStatus) return false; if (fatherName == null) { if (other.fatherName != null) return false; } else if (!fatherName.equals(other.fatherName)) return false; if (gender != other.gender) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (idNo == null) { if (other.idNo != null) return false; } else if (!idNo.equals(other.idNo)) return false; if (idType != other.idType) return false; if (inPersonGroupCodeNo == null) { if (other.inPersonGroupCodeNo != null) return false; } else if (!inPersonGroupCodeNo.equals(other.inPersonGroupCodeNo)) return false; if (initialId == null) { if (other.initialId != null) return false; } else if (!initialId.equals(other.initialId)) return false; if (insPersonCodeNo == null) { if (other.insPersonCodeNo != null) return false; } else if (!insPersonCodeNo.equals(other.insPersonCodeNo)) return false; if (Double.doubleToLongBits(interest) != Double.doubleToLongBits(other.interest)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (paymentTerm != other.paymentTerm) return false; if (periodMonth != other.periodMonth) return false; if (prefix == null) { if (other.prefix != null) return false; } else if (!prefix.equals(other.prefix)) return false; if (Double.doubleToLongBits(premium) != Double.doubleToLongBits(other.premium)) return false; if (residentAddress == null) { if (other.residentAddress != null) return false; } else if (!residentAddress.equals(other.residentAddress)) return false; if (startDate == null) { if (other.startDate != null) return false; } else if (!startDate.equals(other.startDate)) return false; if (Double.doubleToLongBits(sumInsured) != Double.doubleToLongBits(other.sumInsured)) return false; if (unit != other.unit) return false; if (version != other.version) return false; return true; } }
6b8331044ef9cf893141dea68870ad6be2a33df6
11b9a30ada6672f428c8292937dec7ce9f35c71b
/src/main/java/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java
c3291bc512b4702ed052fb5810909e72d5765a49
[]
no_license
bogle-zhao/jdk8
5b0a3978526723b3952a0c5d7221a3686039910b
8a66f021a824acfb48962721a20d27553523350d
refs/heads/master
2022-12-13T10:44:17.426522
2020-09-27T13:37:00
2020-09-27T13:37:00
299,039,533
0
0
null
null
null
null
UTF-8
Java
false
false
2,986
java
/***** Lobxxx Translate Finished ******/ /* * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * <p> *  根据一个或多个贡献者许可协议授予Apache软件基金会(ASF)。有关版权所有权的其他信息,请参阅随此作品分发的NOTICE文件。 * ASF根据Apache许可证2.0版("许可证")向您授予此文件;您不能使用此文件,除非符合许可证。您可以通过获取许可证的副本。 * *  http://www.apache.org/licenses/LICENSE-2.0 * *  除非适用法律要求或书面同意,否则根据许可证分发的软件按"原样"分发,不附带任何明示或暗示的担保或条件。请参阅管理许可证下的权限和限制的特定语言的许可证。 * */ /* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * <p> *  版权所有(c)2005,2013,Oracle和/或其附属公司。版权所有。 * */ /* * $Id$ * <p> *  $ Id $ * */ package com.sun.org.apache.xml.internal.security.signature.reference; import java.util.Iterator; import org.w3c.dom.Node; /** * An abstract representation of a <code>ReferenceData</code> type containing a node-set. * <p> *  包含节点集的<code> ReferenceData </code>类型的抽象表示。 * */ public interface ReferenceNodeSetData extends ReferenceData { /** * Returns a read-only iterator over the nodes contained in this * <code>NodeSetData</code> in * <a href="http://www.w3.org/TR/1999/REC-xpath-19991116#dt-document-order"> * document order</a>. Attempts to modify the returned iterator * via the <code>remove</code> method throw * <code>UnsupportedOperationException</code>. * * <p> *  在<code> NodeSetData </code>中包含的节点上返回只读迭代器 * <a href="http://www.w3.org/TR/1999/REC-xpath-19991116#dt-document-order"> * * @return an <code>Iterator</code> over the nodes in this * <code>NodeSetData</code> in document order */ Iterator<Node> iterator(); }
d315547ecc1ea8db12087dca93f339dfa9caba6f
62b7683dc011f43062ba92bafbfa1daea06b2f20
/src/test/java/inheritancemethods/bankaccount/DebitAccountTest.java
622959b0d6b0d4e5acfd36d0f2e5ca39bc6bade1
[]
no_license
ibrone/training-solutions
cf44150388437ab6173331d26e1521fde1cd9d9f
60b5be73bc24b911e2ac0c6eebf8c6c4c60bcbcc
refs/heads/master
2023-03-11T03:11:15.928962
2021-02-26T18:25:40
2021-02-26T18:25:40
308,020,478
0
0
null
null
null
null
UTF-8
Java
false
false
1,606
java
package inheritancemethods.bankaccount; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class DebitAccountTest { @Test public void constructorTest() { //Given DebitAccount debitAccount = new DebitAccount("111111-2222222", 50000); //Then assertThat(debitAccount.getAccountNumber(), equalTo("111111-2222222")); assertThat(debitAccount.getBalance(), equalTo(50000L)); } @Test public void costOfTransaction() { //Given DebitAccount debitAccount = new DebitAccount("111111-2222222", 50000); //Then assertThat(debitAccount.costOfTransaction(15027), equalTo(450L)); } @Test public void costOfTransactionLow() { //Given DebitAccount debitAccount = new DebitAccount("111111-2222222", 50000); //Then assertThat(debitAccount.costOfTransaction(6000), equalTo(200L)); } @Test public void transactionSuccess() { //Given DebitAccount debitAccount = new DebitAccount("111111-2222222", 50000); //Then assertThat(debitAccount.transaction(40000), is(true)); assertThat(debitAccount.getBalance(), equalTo(8800L)); } @Test public void transactionFail() { //Given DebitAccount debitAccount = new DebitAccount("111111-2222222", 50000); //Then assertThat(debitAccount.transaction(60000), is(false)); assertThat(debitAccount.getBalance(), equalTo(50000L)); } }
6f08cecc52fda4d498e37920088f8122ea9c381e
ae6486a7c370951995d7116491653fef27ab0345
/BasicJava/BasicJavatest.java
0603f360cac8ebf0a1a3530bbccbfe717b551147
[]
no_license
EddiePulido/java_spring_assignments
2278920dd89c162c5213dbe1c0228beac9284334
706148359b1ba8c01ce9546447e7be984bda4661
refs/heads/master
2020-06-14T22:49:24.690438
2019-07-04T01:24:07
2019-07-04T01:24:07
195,148,079
0
0
null
null
null
null
UTF-8
Java
false
false
925
java
import java.util.ArrayList; import java.util.Arrays; public class BasicJavaTest{ public static void main(String[] args){ BasicJava jav = new BasicJava(); // jav.print(); int[] arr = {1,3,5,7,9,13}; ArrayList<Integer> nums = new ArrayList<Integer>(); nums.add(1); nums.add(4); nums.add(-4); nums.add(5); nums.add(-6); nums.add(43); // jav.printEach(arr); // System.out.println(jav.findMax(arr)); // System.out.println(jav.average(arr)); // System.out.println(jav.arrayOdd()); // System.out.println(jav.greater(arr,6)); // System.out.println(Arrays.toString(jav.squareValues(arr))); // System.out.println(Arrays.toString(jav.minMaxAvg(arr))); // System.out.println(jav.removeNeg(nums)); // System.out.println(Arrays.toString(jav.shift(arr))); } }
976cb8aa05f659c1eab2e9e959501c7f1d0848ba
dd2f8bb977a5f950006e7df39a78a80830acfb14
/i4-data-cloud-clickhouse/src/main/java/cn/i4/data/cloud/clickhouse/config/ClickHouseConfig.java
6dcc095dbf45fbcfb1977ceeaeede3bd5c8948ba
[]
no_license
994625905/i4-data-cloud
98371770fe1a7d441c80fa2a1b2241e736fc391e
dabccaceb451799caf5c92a52cb83ebc4cf1f3ed
refs/heads/master
2023-03-01T07:43:08.033611
2021-02-05T10:18:03
2021-02-05T10:18:03
306,818,916
3
1
null
null
null
null
UTF-8
Java
false
false
2,621
java
package cn.i4.data.cloud.clickhouse.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PropertiesLoaderUtils; import ru.yandex.clickhouse.BalancedClickhouseDataSource; import ru.yandex.clickhouse.ClickHouseDataSource; import ru.yandex.clickhouse.settings.ClickHouseProperties; import javax.sql.DataSource; import java.util.Properties; /** * clickhouse的配置项,主要提供数据源和连接 * @author wangjc * @title: ClickHouseConfig * @projectName i4-data-cloud * @description: TODO * @date 2020/9/1720:28 */ public class ClickHouseConfig { private final static Logger logger = LoggerFactory.getLogger(ClickHouseConfig.class); private static ClickHouseProperties clickHouseProperties; private static DataSource dataSource; /** 初始化 */ static{ try { /** 加载配置文件 */ Resource resource = new ClassPathResource("application.properties"); Properties properties = PropertiesLoaderUtils.loadProperties(resource); /** 设置clickHouse连接属性 */ clickHouseProperties = new ClickHouseProperties(); clickHouseProperties.setUser(properties.getProperty("clickhouse.user")); clickHouseProperties.setPassword(properties.getProperty("clickhouse.password")); clickHouseProperties.setDatabase(properties.getProperty("clickhouse.database")); //集群地址,以逗号隔开;"jdbc:clickhouse://127.0.0.1:8121,127.0.0.1:8122,127.0.0.1:8121,127.0.0.1:8122"; String address = properties.getProperty("clickhouse.address"); logger.debug("clickHouse初始化数据源地址[{}]",address); if(address.indexOf(",") > 0){ dataSource = new BalancedClickhouseDataSource(address,clickHouseProperties);//集群 }else{ dataSource = new ClickHouseDataSource(address,clickHouseProperties);//单机 } if(dataSource != null){ logger.debug("clickHouse数据源初始化成功"); } }catch (Exception e){ e.printStackTrace(); } } /** * 获取数据源 * @return */ public static DataSource getDataSource(){ if(dataSource == null){ logger.error("获取数据源失败,dataSource:[{null}]"); throw new RuntimeException(" clickHouseDataSource is null "); } return dataSource; } }
976c58ed040e75a0a62c0e6d6316e481de9c4c22
c8fe2613dbe808e5157dec996e7d57b6a8a37167
/OrderPrint/src/main/java/com/picsdream/picsdreamsdk/activity/ReviewOrderActivity.java
000cc6c78e3cfb495dd23105bc4cca6f62ecc1d0
[]
no_license
picsdream/nowprint
d0d3566bae33f086f2f6c15ae782ab04c561b71f
5f433c3ffe1f22bf60d8a3174eb9844017c63327
refs/heads/master
2021-09-12T11:52:05.156495
2017-12-21T11:52:01
2017-12-21T11:52:01
104,210,327
0
1
null
null
null
null
UTF-8
Java
false
false
11,495
java
package com.picsdream.picsdreamsdk.activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.BottomSheetDialog; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.picsdream.picsdreamsdk.R; import com.picsdream.picsdreamsdk.application.ContextProvider; import com.picsdream.picsdreamsdk.model.Country; import com.picsdream.picsdreamsdk.model.Coupon; import com.picsdream.picsdreamsdk.model.Item; import com.picsdream.picsdreamsdk.model.Order; import com.picsdream.picsdreamsdk.model.Region; import com.picsdream.picsdreamsdk.model.ShippingText; import com.picsdream.picsdreamsdk.model.network.CouponsResponse; import com.picsdream.picsdreamsdk.model.network.InitialAppDataResponse; import com.picsdream.picsdreamsdk.util.Constants; import com.picsdream.picsdreamsdk.util.NavigationUtil; import com.picsdream.picsdreamsdk.util.SaneToast; import com.picsdream.picsdreamsdk.util.SharedPrefsUtil; import com.picsdream.picsdreamsdk.util.Utils; import com.squareup.picasso.Picasso; import java.util.List; /** * Authored by vipulkumar on 29/08/17. */ public class ReviewOrderActivity extends BaseActivity implements View.OnClickListener { private Toolbar toolbar; private ViewGroup proceedLayout; private TextView tvChangeDiscount; private ImageView ivProductImage; private TextView tvProductType, tvProductPrice, tvInitialPrice, tvDiscount, tvTax, tvPayableAmount, tvProductSize, tvDeliveryDate, tvShipping, tvShippingLabel; private String orderType, size, deliveryString; private float costBeforeTax, totalCost, discount, tax, finalCost, shipping; private InitialAppDataResponse initialAppDataResponse; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_review_order); initialAppDataResponse = SharedPrefsUtil.getInitialDataResponse(); setupUi(); } private void setupUi() { toolbar = findViewById(R.id.toolbar); ivProductImage = findViewById(R.id.ivProductImage); tvProductType = findViewById(R.id.tvProductType); tvProductPrice = findViewById(R.id.tvProductPrice); tvInitialPrice = findViewById(R.id.tvInitialPrice); tvDiscount = findViewById(R.id.tvDiscount); tvTax = findViewById(R.id.tvTax); tvPayableAmount = findViewById(R.id.tvPayableAmount); tvProductSize = findViewById(R.id.tvProductSize); tvChangeDiscount = findViewById(R.id.tvChangeDiscount); tvDeliveryDate = findViewById(R.id.tvDeliveryDate); tvShipping = findViewById(R.id.tvShipping); tvShippingLabel = findViewById(R.id.tvShippingLabel); setupToolbar(toolbar); proceedLayout = findViewById(R.id.proceedLayout); proceedLayout.setOnClickListener(this); setOrderProperties(0f); manageDiscount(); } private void manageDiscount() { tvChangeDiscount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ContextProvider.trackEvent(APP_KEY, "Change Promo", ""); final BottomSheetDialog dialog = new BottomSheetDialog(ReviewOrderActivity.this); dialog.setContentView(R.layout.view_bottomsheet); dialog.show(); final EditText etPromoCode = dialog.findViewById(R.id.etPromoCode); LinearLayout applyPromoLayout = dialog.findViewById(R.id.applyPromoLayout); final TextView tvPromoError = dialog.findViewById(R.id.tvPromoError); tvPromoError.setVisibility(View.GONE); applyPromoLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean validPromo = false; tvPromoError.setVisibility(View.GONE); String promoCode = etPromoCode.getText().toString(); CouponsResponse couponsResponse = SharedPrefsUtil.getCouponResponse(); if (couponsResponse != null && couponsResponse.getCoupons() != null && couponsResponse.getCoupons().size() > 0) { List<Coupon> coupons = SharedPrefsUtil.getCouponResponse().getCoupons(); for (Coupon coupon : coupons) { if (coupon.getCouponCode().equalsIgnoreCase(promoCode)) { validPromo = true; applyPromo(coupon); SaneToast.getToast("Promo applied").show(); ContextProvider.trackEvent(APP_KEY, "Promo Applied", promoCode); dialog.dismiss(); } } } else { ContextProvider.trackEvent(APP_KEY, "Promo Error", promoCode); validPromo = false; } if (!validPromo) { tvPromoError.setVisibility(View.VISIBLE); } } }); } }); } private void applyPromo(Coupon coupon) { setOrderProperties((float) (coupon.getNumValue() * SharedPrefsUtil.getRegion().getConversion())); } private void setOrderProperties(float discountPer) { Order order = SharedPrefsUtil.getOrder(); Region region = SharedPrefsUtil.getRegion(); if (discount == 0) { discountPer = initialAppDataResponse.getDis(); } shipping = Utils.getConvertedPrice(getShipping()); totalCost = order.getTotalCost(); discount = getDiscount(totalCost, discountPer); costBeforeTax = Utils.getDiscountedPrice(totalCost, (int) discountPer); orderType = getProductType(initialAppDataResponse, order); size = order.getSize(); tax = (costBeforeTax * region.getNum()) / 100; finalCost = getPayablePrice(costBeforeTax, tax, shipping); deliveryString = getFormattedDeliveryDate(initialAppDataResponse.getDelivery()); order.setSize(String.valueOf(size)); order.setCurrency(region.getCurrency()); order.setFinalCost(String.valueOf(finalCost)); order.setDiscount(String.valueOf(discount)); order.setTax(String.valueOf(tax)); order.setTotalCost(totalCost); order.setShipping(String.valueOf(shipping)); SharedPrefsUtil.saveOrder(order); setValues(); ContextProvider.trackEvent(SharedPrefsUtil.getAppKey(), "Order Review Screen", order.getType() + " - " + order.getMedium() + " - " + order.getSize()); } private int getShipping() { Country currentCountry = SharedPrefsUtil.getCountry(); for (Country country : initialAppDataResponse.getCountries()) { if (currentCountry.getCountry().equalsIgnoreCase(country.getCountry())) { return country.getShipping(); } } return 0; } private String getShippingLabel() { Country currentCountry = SharedPrefsUtil.getCountry(); for (ShippingText shippingText : initialAppDataResponse.getShippingTexts()) { if (currentCountry.getCountry().equalsIgnoreCase(shippingText.getName())) { return shippingText.getText(); } } for (ShippingText shippingText : initialAppDataResponse.getShippingTexts()) { if (shippingText.getName().equalsIgnoreCase("default")) { return shippingText.getText(); } } return "shipping"; } private void setValues() { Picasso.with(this) .load(SharedPrefsUtil.getImageUriString()) .into(ivProductImage); tvProductType.setText(orderType); tvInitialPrice.setText(Utils.getFormattedPrice(totalCost)); tvDiscount.setText(" - " + Utils.getFormattedPrice(discount)); tvTax.setText(Utils.getFormattedPrice(tax)); tvShipping.setText(Utils.getFormattedPrice(shipping)); tvShippingLabel.setText(getShippingLabel()); tvProductPrice.setText(Utils.getFormattedPrice(costBeforeTax)); tvPayableAmount.setText(Utils.getFormattedPrice(finalCost)); tvProductSize.setText(size); tvDeliveryDate.setText(deliveryString); } private String getProductType(InitialAppDataResponse initialAppDataResponse, Order order) { return Utils.capitalizeFirstCharacterOfEveryWord( getItemNameFromType(initialAppDataResponse, order.getType()) + " " + order.getMediumText()); } private String getItemNameFromType(InitialAppDataResponse initialAppDataResponse, String type) { for (Item item : initialAppDataResponse.getItems()) { if (item.getType().equalsIgnoreCase(type)) { return item.getName(); } } return ""; } private float getPayablePrice(float finalPrice, float tax, float shipping) { return Utils.roundOffFloat(finalPrice + tax + shipping); } private String getFormattedDeliveryDate(String delivery) { return Utils.formatDeliveryDateString(delivery); } private float getDiscount(float initialPrice, float discount) { return Utils.roundOffFloat((initialPrice * discount) / 100); } @Override public void onClick(View view) { if (view.getId() == R.id.proceedLayout) { NavigationUtil.startActivity(ReviewOrderActivity.this, AddressActivity.class); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_help, menu); final MenuItem menuItem = menu.findItem(R.id.menu_notification); View actionView = menuItem.getActionView(); TextView count = (TextView) actionView.findViewById(R.id.notification_pill); int size = Utils.notificationCount(); count.setText(String.valueOf(size)); if(size == 0) count.setVisibility(View.GONE); actionView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onOptionsItemSelected(menuItem); } }); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Utils.onHelpItemsClicked(item, this, "Review Order Screen"); return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); ContextProvider.trackScreenView("Review Order"); } }
dea09489674c9cdeb99d3f59d07afb1b6543e868
5b64082c97895bd41c9bb7913bcaa69165165c57
/src/main/java/designPattern/prototypePattern/Square.java
5206f654e047f58da37369f6f562d7364d7af511
[]
no_license
pmk2429/java_ocean
8481c9f1b32f0eaca8d5530b1d693337a3a9fddf
2607c7f8417a7fc41de2e74ab5e67812ce5bd3ee
refs/heads/master
2023-08-22T05:16:18.451077
2023-08-20T21:33:32
2023-08-20T21:33:32
29,897,133
2
1
null
2023-07-30T17:20:32
2015-01-27T04:23:55
Java
UTF-8
Java
false
false
212
java
package designPattern.prototypePattern; public class Square extends Shape { public Square() { type = "Square"; } @Override public void draw() { System.out.println("Inside Square::draw() method."); } }
fd10e81984915bd009ed1b181439130bda0c2dfb
32d109f6d62f6c821219a7ea960daf9ae034a326
/src/br/com/gof/estruturais/composite/seguro/Main.java
d16cbe70da0cf85be76a26de946a43d2a9e57511
[]
no_license
fabioroseno/padroes_de_projeto
99c0a1229908fff8e12678a09dacb79a8c52c94a
e69fa1f6130ded1826e69c2d4a7839a19acf140f
refs/heads/master
2023-05-15T00:41:07.180199
2021-06-04T14:19:54
2021-06-04T14:19:54
27,848,843
0
0
null
null
null
null
UTF-8
Java
false
false
997
java
package br.com.gof.estruturais.composite.seguro; public class Main { /** * @param args */ public static void main(String[] args) { // O cliente precisa conhecer a implementa��o das classes concretas, // pois a interface de um ArquivoVideo � diferente de um // ArquivoComposite ArquivoComponent meuVideo = new ArquivoVideo("meu video.rmvb"); ArquivoComponent meuOutroVideo = new ArquivoVideo("novo video.rmvb"); // No entanto previne que o usu�rio possa fazer esse tipo de chamada: // meuVideo.adicionar(meuOutroVideo); ArquivoComponent minhaPasta = new ArquivoComposite("minha pasta/"); // Para utilizar os m�todos espec�ficos de um composite � necess�rio // realizar um cast. Mas � preciso ter certeza que o objeto pode ser // convertido, caso contr�rio uma exce��o ser� disparada ((ArquivoComposite) minhaPasta).adicionar(meuVideo); ((ArquivoComposite) minhaPasta).adicionar(meuOutroVideo); minhaPasta.printNomeDoArquivo(); } }
10eccf78f8721af4a13cec8a67543adfd3b798e5
e41c4cae18b75536432cc5ad862ee179a47e6b0f
/src/BankApp/challenge9/Challenge9.java
bacf9c7f1c6978324b63a80b653bf71fdac8fdbc
[]
no_license
LukaszDusza/treads
b4162efb1f3afc0f1be87c78359aa2e694757078
8efe96d383ae8552341d8ed0d208b57331b53936
refs/heads/master
2020-03-12T01:15:17.801132
2018-04-20T14:13:36
2018-04-20T14:13:36
130,371,295
0
0
null
null
null
null
UTF-8
Java
false
false
1,953
java
package BankApp.challenge9; /** * Created by timbuchalka on 16/08/2016. */ public class Challenge9 { public static void main(String[] args) { final NewTutor tutor = new NewTutor(); final NewStudent student = new NewStudent(tutor); tutor.setStudent(student); Thread tutorThread = new Thread(new Runnable() { @Override public void run() { tutor.studyTime(); } }); Thread studentThread = new Thread(new Runnable() { @Override public void run() { student.handInAssignment(); } }); tutorThread.start(); studentThread.start(); } } class NewTutor { private NewStudent student; public void setStudent(NewStudent student) { this.student = student; } public void studyTime() { synchronized (this) { System.out.println("Tutor has arrived"); synchronized (student) { try { // wait for student to arrive this.wait(); } catch (InterruptedException e) { } student.startStudy(); System.out.println("Tutor is studying with student"); } } } public void getProgressReport() { // get progress report System.out.println("Tutor gave progress report"); } } class NewStudent { private NewTutor tutor; NewStudent(NewTutor tutor) { this.tutor = tutor; } public void startStudy() { // study System.out.println("Student is studying"); } public void handInAssignment() { synchronized (tutor) { tutor.getProgressReport(); synchronized (this) { System.out.println("Student handed in assignment"); tutor.notifyAll(); } } } }
342527eef58449b26f6d5ed723729daacbcad826
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_ff415eee6729d3f0faced953d7f7133e44ee347d/DisplayImpl/2_ff415eee6729d3f0faced953d7f7133e44ee347d_DisplayImpl_s.java
16579605b1a3c99cafaefccdb6eb87640f98f9f6
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
42,311
java
// // DisplayImpl.java // /* VisAD system for interactive analysis and visualization of numerical data. Copyright (C) 1996 - 1999 Bill Hibbard, Curtis Rueden, Tom Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and Tommy Jasmin. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ package visad; import java.util.*; import java.rmi.*; import java.io.*; import java.awt.*; import java.awt.image.*; import java.net.*; /** DisplayImpl is the abstract VisAD superclass for display implementations. It is runnable.<P> DisplayImpl is not Serializable and should not be copied between JVMs.<P> */ public abstract class DisplayImpl extends ActionImpl implements Display { /** instance variables */ /** a Vector of ScalarMap objects; does not include ConstantMap objects */ private Vector MapVector = new Vector(); /** a Vector of ConstantMap objects */ private Vector ConstantMapVector = new Vector(); /** a Vector of RealType (and TextType) objects occuring in MapVector */ private Vector RealTypeVector = new Vector(); /** a Vector of DisplayRealType objects occuring in MapVector */ private Vector DisplayRealTypeVector = new Vector(); /** list of Control objects linked to ScalarMap objects in MapVector; the Control objects may be linked to UI widgets, or just computed */ private Vector ControlVector = new Vector(); /** ordered list of DataRenderer objects that render Data objects */ private Vector RendererVector = new Vector(); /** DisplayRenderer object for background and metadata rendering */ private DisplayRenderer displayRenderer; /** Component where data depictions are rendered; must be set by concrete subclass constructor */ Component component; /** set to indicate need to compute ranges of RealType-s and sampling for Animation */ private boolean initialize = true; /** set to indicate that ranges should be auto-scaled every time data are displayed */ private boolean always_initialize = false; /** set to re-display all linked Data */ private boolean redisplay_all = false; /** length of ValueArray of distinct DisplayRealType values; one per Single DisplayRealType that occurs in a ScalarMap, plus one per ScalarMap per non-Single DisplayRealType; ScalarMap.valueIndex is an index into ValueArray */ private int valueArrayLength; /** mapping from ValueArray to DisplayScalar */ private int[] valueToScalar; /** mapping from ValueArray to MapVector */ private int[] valueToMap; /** Vector of DisplayListeners */ private transient Vector ListenerVector = new Vector(); private Object mapslock = new Object(); // WLH 16 March 99 private MouseBehavior mouse = null; /** constructor with non-default DisplayRenderer */ public DisplayImpl(String name, DisplayRenderer renderer) throws VisADException, RemoteException { super(name); // put system intrinsic DisplayRealType-s in DisplayRealTypeVector for (int i=0; i<DisplayRealArray.length; i++) { DisplayRealTypeVector.addElement(DisplayRealArray[i]); } if (renderer != null) { displayRenderer = renderer; } else { displayRenderer = getDefaultDisplayRenderer(); } displayRenderer.setDisplay(this); // initialize ScalarMap's, ShadowDisplayReal's and Control's clearMaps(); } /** construct DisplayImpl from RemoteDisplay */ public DisplayImpl(RemoteDisplay rmtDpy, DisplayRenderer renderer) throws VisADException, RemoteException { super(rmtDpy.getName()); // put system intrinsic DisplayRealType-s in DisplayRealTypeVector for (int i=0; i<DisplayRealArray.length; i++) { DisplayRealTypeVector.addElement(DisplayRealArray[i]); } if (renderer != null) { displayRenderer = renderer; } else { try { String name = rmtDpy.getDisplayRendererClassName(); Object obj = Class.forName(name).newInstance(); displayRenderer = (DisplayRenderer )obj; } catch (Exception e) { renderer = getDefaultDisplayRenderer(); } } displayRenderer.setDisplay(this); // initialize ScalarMap's, ShadowDisplayReal's and Control's clearMaps(); } // suck in any remote ScalarMaps void copyScalarMaps(RemoteDisplay rmtDpy) { Vector m; try { m = rmtDpy.getMapVector(); } catch (Exception e) { System.err.println("Couldn't copy ScalarMaps"); return; } Enumeration me = m.elements(); while (me.hasMoreElements()) { ScalarMap sm = (ScalarMap )me.nextElement(); try { addMap(sm); } catch (DisplayException de) { try { addMap(new ScalarMap(sm.getScalar(), sm.getDisplayScalar())); } catch (Exception e) { System.err.println("Couldn't copy remote ScalarMap " + sm); } } catch (Exception e) { e.printStackTrace(); } } } // suck in any remote ConstantMaps void copyConstantMaps(RemoteDisplay rmtDpy) { Vector c; try { c = rmtDpy.getConstantMapVector(); } catch (Exception e) { System.err.println("Couldn't copy ConstantMaps"); return; } Enumeration ce = c.elements(); while (ce.hasMoreElements()) { ConstantMap cm = (ConstantMap )ce.nextElement(); try { addMap(cm); } catch (DisplayException de) { try { addMap(new ConstantMap(cm.getConstant(), cm.getDisplayScalar())); } catch (Exception e) { System.err.println("Couldn't copy remote ConstantMap " + cm); } } catch (Exception e) { e.printStackTrace(); } } } // suck in remote GraphicsModeControl settings void copyGraphicsModeControl(RemoteDisplay rmtDpy) { RemoteGraphicsModeControl rc; try { rc = rmtDpy.getGraphicsModeControl(); } catch (UnmarshalException ue) { System.err.println("Couldn't copy remote GraphicsModeControl"); return; } catch (Exception e) { e.printStackTrace(); return; } GraphicsModeControl gmc = getGraphicsModeControl(); try { gmc.setLineWidth(rc.getLineWidth()); } catch (Exception e) { System.err.println("Couldn't copy remote GraphicsModeControl line width"); } try { gmc.setPointSize(rc.getPointSize()); } catch (Exception e) { System.err.println("Couldn't copy remote GraphicsModeControl point size"); } try { gmc.setPointMode(rc.getPointMode()); } catch (Exception e) { System.err.println("Couldn't copy remote GraphicsModeControl point mode"); } try { gmc.setTextureEnable(rc.getTextureEnable()); } catch (Exception e) { System.err.println("Couldn't copy remote GraphicsModeControl texture enable"); } try { gmc.setScaleEnable(rc.getScaleEnable()); } catch (Exception e) { System.err.println("Couldn't copy remote GraphicsModeControl scale enable"); } try { gmc.setTransparencyMode(rc.getTransparencyMode()); } catch (Exception e) { System.err.println("Couldn't copy remote GraphicsModeControl transparency mode"); } try { gmc.setProjectionPolicy(rc.getProjectionPolicy()); } catch (Exception e) { System.err.println("Couldn't copy remote GraphicsModeControl projection policy"); } } // suck in any remote DataReferences void copyRefLinks(RemoteDisplay rmtDpy) { Vector ml; try { ml = rmtDpy.getReferenceLinks(); } catch (UnmarshalException ue) { System.err.println("Couldn't copy remote DataReferences"); return; } catch (Exception e) { e.printStackTrace(); return; } Enumeration mle = ml.elements(); if (mle.hasMoreElements()) { DataRenderer dr = displayRenderer.makeDefaultRenderer(); String defaultClass = dr.getClass().getName(); while (mle.hasMoreElements()) { RemoteReferenceLink link = (RemoteReferenceLink )mle.nextElement(); // build array of ConstantMap values ConstantMap[] cm = null; try { Vector v = link.getConstantMapVector(); int len = v.size(); if (len > 0) { cm = new ConstantMap[len]; for (int i = 0; i < len; i++) { cm[i] = (ConstantMap )v.elementAt(i); } } } catch (Exception e) { System.err.println("Couldn't copy ConstantMaps" + " for remote DataReference"); } // get reference to Data object RemoteDataReference ref; try { ref = link.getReference(); } catch (Exception e) { System.err.println("Couldn't copy remote DataReference"); ref = null; } if (ref != null) { // get proper DataRenderer DataRenderer renderer; try { String newClass = link.getRendererClassName(); if (newClass == defaultClass) { renderer = null; } else { Object obj = Class.forName(newClass).newInstance(); renderer = (DataRenderer )obj; } } catch (Exception e) { System.err.println("Couldn't copy remote DataRenderer name" + "; using " + defaultClass); renderer = null; } // build RemoteDisplayImpl to which reference is attached try { RemoteDisplayImpl rd = new RemoteDisplayImpl(this); // if this reference uses the default renderer... if (renderer == null) { rd.addReference(ref, cm); } else { rd.addReferences(renderer, ref, cm); } } catch (Exception e) { System.err.println("Couldn't add remote DataReference " + ref); } } } } } // suck in any remote data associated with this Display protected void syncRemoteData(RemoteDisplay rmtDpy) { copyScalarMaps(rmtDpy); copyConstantMaps(rmtDpy); copyGraphicsModeControl(rmtDpy); copyRefLinks(rmtDpy); } /** RemoteDisplayImpl to this for use with Remote DisplayListeners */ private RemoteDisplayImpl rd = null; public void notifyListeners(int id) throws VisADException, RemoteException { if (ListenerVector != null) { synchronized (ListenerVector) { Enumeration listeners = ListenerVector.elements(); while (listeners.hasMoreElements()) { DisplayListener listener = (DisplayListener) listeners.nextElement(); if (listener instanceof Remote) { if (rd == null) { rd = new RemoteDisplayImpl(this); } listener.displayChanged(new DisplayEvent(rd, id)); } else { listener.displayChanged(new DisplayEvent(this, id)); } } } } } /** add a DisplayListener */ public void addDisplayListener(DisplayListener listener) { ListenerVector.addElement(listener); } /** remove a DisplayListener */ public void removeDisplayListener(DisplayListener listener) { if (listener != null) { ListenerVector.removeElement(listener); } } /** return the java.awt.Component (e.g., JPanel or AppletPanel) this DisplayImpl uses; returns null for an offscreen DisplayImpl */ public Component getComponent() { return component; } public void setComponent(Component c) { component = c; } /** re-apply auto-scaling of ScalarMap ranges next time Display is triggered */ public void reAutoScale() { initialize = true; // printStack("reAutoScale"); } /** if auto is true, re-apply auto-scaling of ScalarMap ranges every time Display is triggered */ public void setAlwaysAutoScale(boolean a) { always_initialize = a; } public void reDisplayAll() { redisplay_all = true; // printStack("reDisplayAll"); notifyAction(); } /** link ref to this Display; this method may only be invoked after all links to ScalarMaps have been made */ public void addReference(ThingReference ref) throws VisADException, RemoteException { if (!(ref instanceof DataReference)) { throw new ReferenceException("DisplayImpl.addReference: ref " + "must be DataReference"); } addReference((DataReference) ref, null); } /** link ref to this Display; must be local DataReferenceImpl; this method may only be invoked after all links to ScalarMaps have been made; the ConstantMap array applies only to rendering ref */ public void addReference(DataReference ref, ConstantMap[] constant_maps) throws VisADException, RemoteException { if (!(ref instanceof DataReferenceImpl)) { throw new RemoteVisADException("DisplayImpl.addReference: requires " + "DataReferenceImpl"); } if (findReference(ref) != null) { throw new TypeException("DisplayImpl.addReference: link already exists"); } DataRenderer renderer = displayRenderer.makeDefaultRenderer(); DataDisplayLink[] links = {new DataDisplayLink(ref, this, this, constant_maps, renderer, getLinkId())}; addLink(links[0]); renderer.setLinks(links, this); synchronized (mapslock) { RendererVector.addElement(renderer); } initialize = true; // printStack("addReference"); notifyAction(); } /** method for use by RemoteActionImpl.addReference that adapts this ActionImpl */ void adaptedAddReference(RemoteDataReference ref, RemoteDisplay display, ConstantMap[] constant_maps) throws VisADException, RemoteException { if (findReference(ref) != null) { throw new TypeException("DisplayImpl.adaptedAddReference: " + "link already exists"); } DataRenderer renderer = displayRenderer.makeDefaultRenderer(); DataDisplayLink[] links = {new DataDisplayLink(ref, this, display, constant_maps, renderer, getLinkId())}; addLink(links[0]); renderer.setLinks(links, this); synchronized (mapslock) { RendererVector.addElement(renderer); } initialize = true; // printStack("adaptedAddReference"); notifyAction(); } /** link ref to this Display using the non-default renderer; must be local DataRendererImpls; this method may only be invoked after all links to ScalarMaps have been made; this is a method of DisplayImpl and RemoteDisplayImpl rather than Display - see Section 6.1 of the Developer's Guide for more information */ public void addReferences(DataRenderer renderer, DataReference ref) throws VisADException, RemoteException { addReferences(renderer, new DataReference[] {ref}, null); } /** link ref to this Display using the non-default renderer; must be local DataRendererImpls; this method may only be invoked after all links to ScalarMaps have been made; the maps array applies only to rendering ref; this is a method of DisplayImpl and RemoteDisplayImpl rather than Display - see Section 6.1 of the Developer's Guide for more information */ public void addReferences(DataRenderer renderer, DataReference ref, ConstantMap[] constant_maps) throws VisADException, RemoteException { addReferences(renderer, new DataReference[] {ref}, new ConstantMap[][] {constant_maps}); } /** link refs to this Display using the non-default renderer; must be local DataRendererImpls; this method may only be invoked after all links to ScalarMaps have been made; this is a method of DisplayImpl and RemoteDisplayImpl rather than Display - see Section 6.1 of the Developer's Guide for more information */ public void addReferences(DataRenderer renderer, DataReference[] refs) throws VisADException, RemoteException { addReferences(renderer, refs, null); } /** link refs to this Display using the non-default renderer; must be local DataRendererImpls; this method may only be invoked after all links to ScalarMaps have been made; the maps[i] array applies only to rendering refs[i]; this is a method of DisplayImpl and RemoteDisplayImpl rather than Display - see Section 6.1 of the Developer's Guide for more information */ public void addReferences(DataRenderer renderer, DataReference[] refs, ConstantMap[][] constant_maps) throws VisADException, RemoteException { if (refs.length < 1) { throw new DisplayException("DisplayImpl.addReferences: must have at " + "least one DataReference"); } if (constant_maps != null && refs.length != constant_maps.length) { throw new DisplayException("DisplayImpl.addReferences: constant_maps " + "length must match refs length"); } if (!displayRenderer.legalDataRenderer(renderer)) { throw new DisplayException("DisplayImpl.addReferences: illegal " + "DataRenderer class"); } DataDisplayLink[] links = new DataDisplayLink[refs.length]; for (int i=0; i< refs.length; i++) { if (!(refs[i] instanceof DataReferenceImpl)) { throw new RemoteVisADException("DisplayImpl.addReferences: requires " + "DataReferenceImpl"); } if (findReference(refs[i]) != null) { throw new TypeException("DisplayImpl.addReferences: link already exists"); } if (constant_maps == null) { links[i] = new DataDisplayLink(refs[i], this, this, null, renderer, getLinkId()); } else { links[i] = new DataDisplayLink(refs[i], this, this, constant_maps[i], renderer, getLinkId()); } addLink(links[i]); } renderer.setLinks(links, this); synchronized (mapslock) { RendererVector.addElement(renderer); } initialize = true; // printStack("addReferences"); notifyAction(); } /** method for use by RemoteActionImpl.addReferences that adapts this ActionImpl; this allows a mix of local and remote refs */ void adaptedAddReferences(DataRenderer renderer, DataReference[] refs, RemoteDisplay display, ConstantMap[][] constant_maps) throws VisADException, RemoteException { if (refs.length < 1) { throw new DisplayException("DisplayImpl.addReferences: must have at " + "least one DataReference"); } if (constant_maps != null && refs.length != constant_maps.length) { throw new DisplayException("DisplayImpl.addReferences: constant_maps " + "length must match refs length"); } if (!displayRenderer.legalDataRenderer(renderer)) { throw new DisplayException("DisplayImpl.addReferences: illegal " + "DataRenderer class"); } DataDisplayLink[] links = new DataDisplayLink[refs.length]; for (int i=0; i< refs.length; i++) { if (findReference(refs[i]) != null) { throw new TypeException("DisplayImpl.addReferences: link already exists"); } if (refs[i] instanceof DataReferenceImpl) { // refs[i] is local if (constant_maps == null) { links[i] = new DataDisplayLink(refs[i], this, this, null, renderer, getLinkId()); } else { links[i] = new DataDisplayLink(refs[i], this, this, constant_maps[i], renderer, getLinkId()); } } else { // refs[i] is remote if (constant_maps == null) { links[i] = new DataDisplayLink(refs[i], this, display, null, renderer, getLinkId()); } else { links[i] = new DataDisplayLink(refs[i], this, display, constant_maps[i], renderer, getLinkId()); } } addLink(links[i]); } renderer.setLinks(links, this); synchronized (mapslock) { RendererVector.addElement(renderer); } initialize = true; // printStack("adaptedAddReferences"); notifyAction(); } /** remove link to ref; must be local DataReferenceImpl; if ref was added as part of a DataReference array passed to addReferences, remove links to all of them */ public void removeReference(ThingReference ref) throws VisADException, RemoteException { if (!(ref instanceof DataReferenceImpl)) { throw new RemoteVisADException("ActionImpl.removeReference: requires " + "DataReferenceImpl"); } adaptedDisplayRemoveReference((DataReference) ref); } /** remove link to a DataReference; method for use by RemoteActionImpl.removeReference that adapts this ActionImpl; because DataReference array input to adaptedAddReferences may be a mix of local and remote, we tolerate either here */ void adaptedDisplayRemoveReference(DataReference ref) throws VisADException, RemoteException { DataDisplayLink link = (DataDisplayLink) findReference(ref); // don't throw an Exception if link is null: users may try to // remove all DataReferences added by a call to addReferences if (link == null) return; DataRenderer renderer = link.getRenderer(); DataDisplayLink[] links = renderer.getLinks(); synchronized (mapslock) { renderer.clearScene(); RendererVector.removeElement(renderer); } removeLinks(links); /* WLH 22 April 99 initialize = true; */ } /** remove all DataReference links */ public void removeAllReferences() throws VisADException, RemoteException { synchronized (mapslock) { synchronized (RendererVector) { Iterator renderers = RendererVector.iterator(); while (renderers.hasNext()) { DataRenderer renderer = (DataRenderer) renderers.next(); renderer.clearScene(); DataDisplayLink[] links = renderer.getLinks(); renderers.remove(); removeLinks(links); } } initialize = true; // printStack("removeAllReferences"); } } /** return a Vector containing all DataReferences */ /** used by Control-s to notify this DisplayImpl that they have changed */ public void controlChanged() { notifyAction(); /* WLH 29 Aug 98 synchronized (this) { notify(); } */ } /** DisplayImpl always runs doAction to find out if there is work to do */ public boolean checkTicks() { return true; } /** a Display is runnable; doAction is invoked by any event that requires a re-transform */ public void doAction() throws VisADException, RemoteException { if (mapslock == null) return; synchronized (mapslock) { if (RendererVector == null || displayRenderer == null) { return; } displayRenderer.setWaitFlag(true); // set tickFlag-s in changed Control-s // clone MapVector to avoid need for synchronized access Vector tmap = (Vector) MapVector.clone(); Enumeration maps = tmap.elements(); while (maps.hasMoreElements()) { ScalarMap map = (ScalarMap) maps.nextElement(); map.setTicks(); } // set ScalarMap.valueIndex-s and valueArrayLength int n = getDisplayScalarCount(); int[] scalarToValue = new int[n]; for (int i=0; i<n; i++) scalarToValue[i] = -1; valueArrayLength = 0; maps = tmap.elements(); while (maps.hasMoreElements()) { ScalarMap map = ((ScalarMap) maps.nextElement()); DisplayRealType dreal = map.getDisplayScalar(); if (dreal.isSingle()) { int j = getDisplayScalarIndex(dreal); if (scalarToValue[j] < 0) { scalarToValue[j] = valueArrayLength; valueArrayLength++; } map.setValueIndex(scalarToValue[j]); } else { map.setValueIndex(valueArrayLength); valueArrayLength++; } } // set valueToScalar and valueToMap arrays valueToScalar = new int[valueArrayLength]; valueToMap = new int[valueArrayLength]; maps = tmap.elements(); while (maps.hasMoreElements()) { ScalarMap map = ((ScalarMap) maps.nextElement()); DisplayRealType dreal = map.getDisplayScalar(); valueToScalar[map.getValueIndex()] = getDisplayScalarIndex(dreal); valueToMap[map.getValueIndex()] = tmap.indexOf(map); } DataShadow shadow = null; // invoke each DataRenderer (to prepare associated Data objects // for transformation) // clone RendererVector to avoid need for synchronized access Vector temp = ((Vector) RendererVector.clone()); Enumeration renderers; boolean go = false; if (initialize) { renderers = temp.elements(); while (!go && renderers.hasMoreElements()) { DataRenderer renderer = (DataRenderer) renderers.nextElement(); go |= renderer.checkAction(); } // System.out.println("initialize = " + initialize + " go = " + go); } if (redisplay_all) { go = true; // System.out.println("redisplay_all = " + redisplay_all + " go = " + go); redisplay_all = false; } if (!initialize || go) { renderers = temp.elements(); while (renderers.hasMoreElements()) { DataRenderer renderer = (DataRenderer) renderers.nextElement(); shadow = renderer.prepareAction(go, initialize, shadow); } if (shadow != null) { // apply RealType ranges and animationSampling maps = tmap.elements(); while(maps.hasMoreElements()) { ScalarMap map = ((ScalarMap) maps.nextElement()); map.setRange(shadow); } } ScalarMap.equalizeFlow(tmap, Display.DisplayFlow1Tuple); ScalarMap.equalizeFlow(tmap, Display.DisplayFlow2Tuple); renderers = temp.elements(); boolean badScale = false; while (renderers.hasMoreElements()) { DataRenderer renderer = (DataRenderer) renderers.nextElement(); badScale |= renderer.getBadScale(); } initialize = badScale; if (always_initialize) initialize = true; /* if (initialize) { System.out.println("badScale = " + badScale + " always_initialize = " + always_initialize); } */ boolean transform_done = false; renderers = temp.elements(); while (renderers.hasMoreElements()) { DataRenderer renderer = (DataRenderer) renderers.nextElement(); transform_done |= renderer.doAction(); } if (transform_done) { AnimationControl control = (AnimationControl) getControl(AnimationControl.class); if (control != null) { control.init(); } synchronized (ControlVector) { Enumeration controls = ControlVector.elements(); while(controls.hasMoreElements()) { Control cont = (Control) controls.nextElement(); if (ValueControl.class.isInstance(cont)) { ((ValueControl) cont).init(); } } } notifyListeners(DisplayEvent.TRANSFORM_DONE); } } // clear tickFlag-s in Control-s maps = tmap.elements(); while(maps.hasMoreElements()) { ScalarMap map = (ScalarMap) maps.nextElement(); map.resetTicks(); } displayRenderer.setWaitFlag(false); } // end synchronized (mapslock) } /** return the default DisplayRenderer for this DisplayImpl */ protected abstract DisplayRenderer getDefaultDisplayRenderer(); /** return the DisplayRenderer associated with this DisplayImpl */ public DisplayRenderer getDisplayRenderer() { return displayRenderer; } /** get a clone of RendererVector to avoid concurrent access by Display thread */ public Vector getRendererVector() { return (Vector) RendererVector.clone(); } public int getDisplayScalarCount() { return DisplayRealTypeVector.size(); } public DisplayRealType getDisplayScalar(int index) { return (DisplayRealType) DisplayRealTypeVector.elementAt(index); } public int getDisplayScalarIndex(DisplayRealType dreal) { int dindex; synchronized (DisplayRealTypeVector) { DisplayTupleType tuple = dreal.getTuple(); if (tuple != null) { int n = tuple.getDimension(); for (int i=0; i<n; i++) { try { DisplayRealType ereal = (DisplayRealType) tuple.getComponent(i); int eindex = DisplayRealTypeVector.indexOf(ereal); if (eindex < 0) { DisplayRealTypeVector.addElement(ereal); } } catch (VisADException e) { } } } dindex = DisplayRealTypeVector.indexOf(dreal); if (dindex < 0) { DisplayRealTypeVector.addElement(dreal); dindex = DisplayRealTypeVector.indexOf(dreal); } } return dindex; } public int getScalarCount() { return RealTypeVector.size(); } public ScalarType getScalar(int index) { return (ScalarType) RealTypeVector.elementAt(index); } public int getScalarIndex(ScalarType real) throws RemoteException { return RealTypeVector.indexOf(real); } /** add a ScalarMap to this Display; can only be invoked when no DataReference-s are linked to this Display */ public void addMap(ScalarMap map) throws VisADException, RemoteException { synchronized (mapslock) { int index; if (!RendererVector.isEmpty()) { throw new DisplayException("DisplayImpl.addMap: RendererVector " + "must be empty"); } DisplayRealType type = map.getDisplayScalar(); if (!displayRenderer.legalDisplayScalar(type)) { throw new BadMappingException("DisplayImpl.addMap: " + map.getDisplayScalar() + " illegal for this DisplayRenderer"); } if ((Display.LineWidth.equals(type) || Display.PointSize.equals(type)) && !(map instanceof ConstantMap)) { throw new BadMappingException("DisplayImpl.addMap: " + map.getDisplayScalar() + " for ConstantMap only"); } map.setDisplay(this); if (map instanceof ConstantMap) { synchronized (ConstantMapVector) { Enumeration maps = ConstantMapVector.elements(); while(maps.hasMoreElements()) { ConstantMap map2 = (ConstantMap) maps.nextElement(); if (map2.getDisplayScalar().equals(map.getDisplayScalar())) { throw new BadMappingException("Display.addMap: two ConstantMaps " + "have the same DisplayScalar"); } } ConstantMapVector.addElement(map); } } else { // !(map instanceof ConstantMap) // add to RealTypeVector and set ScalarIndex ScalarType real = map.getScalar(); DisplayRealType dreal = map.getDisplayScalar(); synchronized (MapVector) { Enumeration maps = MapVector.elements(); while(maps.hasMoreElements()) { ScalarMap map2 = (ScalarMap) maps.nextElement(); if (real.equals(map2.getScalar()) && dreal.equals(map2.getDisplayScalar()) && !dreal.equals(Display.Shape)) { throw new BadMappingException("Display.addMap: two ScalarMaps " + "with the same RealType & DisplayRealType"); } if (dreal.equals(Display.Animation) && map2.getDisplayScalar().equals(Display.Animation)) { throw new BadMappingException("Display.addMap: two RealTypes " + "are mapped to Animation"); } } MapVector.addElement(map); } synchronized (RealTypeVector) { index = RealTypeVector.indexOf(real); if (index < 0) { RealTypeVector.addElement(real); index = RealTypeVector.indexOf(real); } } map.setScalarIndex(index); map.setControl(); } // end !(map instanceof ConstantMap) addDisplayScalar(map); } } void addDisplayScalar(ScalarMap map) { int index; DisplayRealType dreal = map.getDisplayScalar(); synchronized (DisplayRealTypeVector) { DisplayTupleType tuple = dreal.getTuple(); if (tuple != null) { int n = tuple.getDimension(); for (int i=0; i<n; i++) { try { DisplayRealType ereal = (DisplayRealType) tuple.getComponent(i); int eindex = DisplayRealTypeVector.indexOf(ereal); if (eindex < 0) { DisplayRealTypeVector.addElement(ereal); } } catch (VisADException e) { } } } index = DisplayRealTypeVector.indexOf(dreal); if (index < 0) { DisplayRealTypeVector.addElement(dreal); index = DisplayRealTypeVector.indexOf(dreal); } } map.setDisplayScalarIndex(index); } /** clear set of ScalarMap-s associated with this display; can only be invoked when no DataReference-s are linked to this Display */ public void clearMaps() throws VisADException, RemoteException { synchronized (mapslock) { if (!RendererVector.isEmpty()) { throw new DisplayException("DisplayImpl.clearMaps: RendererVector " + "must be empty"); } Enumeration maps; synchronized (MapVector) { maps = MapVector.elements(); while(maps.hasMoreElements()) { ScalarMap map = (ScalarMap) maps.nextElement(); map.nullDisplay(); } MapVector.removeAllElements(); } synchronized (ConstantMapVector) { maps = ConstantMapVector.elements(); while(maps.hasMoreElements()) { ConstantMap map = (ConstantMap) maps.nextElement(); map.nullDisplay(); } ConstantMapVector.removeAllElements(); } synchronized (ControlVector) { // clear Control-s associated with this Display ControlVector.removeAllElements(); // one each GraphicsModeControl and ProjectionControl always exists Control control = (Control) getGraphicsModeControl(); if (control != null) addControl(control); control = (Control) getProjectionControl(); if (control != null) addControl(control); } // clear RealType-s from RealTypeVector // removeAllElements is synchronized RealTypeVector.removeAllElements(); synchronized (DisplayRealTypeVector) { // clear DisplayRealType-s from DisplayRealTypeVector DisplayRealTypeVector.removeAllElements(); // put system intrinsic DisplayRealType-s in DisplayRealTypeVector for (int i=0; i<DisplayRealArray.length; i++) { DisplayRealTypeVector.addElement(DisplayRealArray[i]); } } displayRenderer.clearAxisOrdinals(); displayRenderer.setAnimationString(new String[] {null, null}); } } public Vector getMapVector() { return (Vector) MapVector.clone(); } public Vector getConstantMapVector() { return (Vector) ConstantMapVector.clone(); } public void addControl(Control control) { if (control != null && !ControlVector.contains(control)) { ControlVector.addElement(control); control.setIndex(ControlVector.indexOf(control)); } } /** only called for Control objects associated with 'single' DisplayRealType-s */ public Control getControl(Class c) { synchronized (ControlVector) { Enumeration controls = ControlVector.elements(); while(controls.hasMoreElements()) { Control control = (Control) controls.nextElement(); /* WLH 19 March 99 if (c.equals(control.getClass())) return control; */ if (c.isInstance(control)) return control; } } return null; } public Vector getControlVector() { return (Vector) ControlVector.clone(); } public int getValueArrayLength() { return valueArrayLength; } public int[] getValueToScalar() { return valueToScalar; } public int[] getValueToMap() { return valueToMap; } /** return the ProjectionControl associated with this DisplayImpl */ public abstract ProjectionControl getProjectionControl(); /** return the GraphicsModeControl associated with this DisplayImpl */ public abstract GraphicsModeControl getGraphicsModeControl(); /** wait for millis milliseconds * @deprecated Use <CODE>new visad.util.Delay(millis)</CODE> instead. */ public static void delay(int millis) { new visad.util.Delay(millis); } /** print a stack dump */ public static void printStack(String message) { try { throw new DisplayException("printStack: " + message); } catch (DisplayException e) { e.printStackTrace(); } } /** given their complexity, its reasonable that DisplayImpl objects are only equal to themselves */ public boolean equals(Object obj) { return (obj == this); } public Vector getRenderers() { return (Vector )RendererVector.clone(); } public int getAPI() throws VisADException { throw new VisADException("No API specified"); } public void setMouseBehavior(MouseBehavior m) { mouse = m; } public double[] make_matrix(double rotx, double roty, double rotz, double scale, double transx, double transy, double transz) { if (mouse != null) { return mouse.make_matrix(rotx, roty, rotz, scale, transx, transy, transz); } else { return null; } } public double[] multiply_matrix(double[] a, double[] b) { if (mouse != null && a != null && b != null) { return mouse.multiply_matrix(a, b); } else { return null; } } /** return a captured image of the display */ public BufferedImage getImage() { return displayRenderer.getImage(); } /** return a captured image of the display; synchronize if sync */ public BufferedImage getImage(boolean sync) { if (sync) new Syncher(this); return displayRenderer.getImage(); } public String toString() { return toString(""); } public String toString(String pre) { String s = pre + "Display\n"; Enumeration maps = MapVector.elements(); while(maps.hasMoreElements()) { ScalarMap map = (ScalarMap) maps.nextElement(); s = s + map.toString(pre + " "); } maps = ConstantMapVector.elements(); while(maps.hasMoreElements()) { ConstantMap map = (ConstantMap) maps.nextElement(); s = s + map.toString(pre + " "); } return s; } private class Syncher extends Object implements DisplayListener { private ProjectionControl control; int count; Syncher(DisplayImpl display) { control = display.getProjectionControl(); count = -1; display.disableAction(); display.addDisplayListener(this); display.reDisplayAll(); display.enableAction(); try { synchronized (this) { wait(); } } catch(InterruptedException e) { } display.removeDisplayListener(this); } public void displayChanged(DisplayEvent e) throws VisADException, RemoteException { if (e.getId() == DisplayEvent.TRANSFORM_DONE) { count = 2; control.setMatrix(control.getMatrix()); } else if (e.getId() == DisplayEvent.FRAME_DONE) { if (count > 0) { control.setMatrix(control.getMatrix()); count--; } else if (count == 0) { synchronized (this) { notify(); } count--; } } } } }
e5ae952274c2484ba1eeeae30b9fe14ff2705ab9
931ae35cd1ac2fa338defbc373fdf4478da607b8
/src/main/java/it/hqsolutions/lastminute/exercise/persistence/entity/package-info.java
0747e6b7f4deccddf1684d95f7620402d3c2b5b5
[]
no_license
HQSoftware-J/lastminute-exercise-prj
b459f0c5ebec970bc617fff2b2cea7d439d51408
e3cbbfcba6a51554d3fd4ec1ad112118574060f9
refs/heads/master
2021-01-20T20:35:59.541287
2016-06-21T06:46:50
2016-06-21T06:46:50
61,149,952
0
0
null
null
null
null
UTF-8
Java
false
false
104
java
/** * */ /** * @author giorgio * */ package it.hqsolutions.lastminute.exercise.persistence.entity;
b5c870fea945702650d41ef74277f3e252086e77
933da9e44be32496f14d8fb806ca703e57fb2e1c
/Andrian/27April18/MathOperations.java
33076f860719dd9e973fca3e938b5ed95f4896f3
[]
no_license
Padepokan79/BootCampG7
de16a04512e5ee906b137bc4c358d257aee9bd64
4143c068b8a393b680bdc0394b9db6d73361de0e
refs/heads/master
2020-03-14T09:21:16.175053
2018-06-29T10:18:49
2018-06-29T10:18:49
131,543,216
0
0
null
2018-06-29T10:18:50
2018-04-30T01:07:31
Java
UTF-8
Java
false
false
844
java
/* Date : 27/4/2018 Time : 11:05:39 Create by : Muhamad Rifan Adrian Edited by : */ public class MathOperations { public static void main(String[] args) { int a, b, c, d, e, f, g; double x, y, z; String one, two, both; a = 10; b = 27; System.out.println( "a is " + a + ", b is "+ b ); c = a + b; System.out.println( "a+b is " + c ); d = a - b; System.out.println( "a-b is " + d ); e = a+b*3; System.out.println( "a+b*3 is " + e ); f = b/2; System.out.println( "b/2 is " + f ); g = b % 10; System.out.println( "b%10 is " + g ); x = 1.1; System.out.println( "\nx is " + x); y = x*x; System.out.println( "x*x is " + y); z = b/2; System.out.println( "b/2 is " + z ); System.out.println(); one = "dog"; two = "house"; both = one + two; System.out.println( both ); } }
a260328538de9d5e4b0d996cd67a6c1ba5ae9898
217b26b0e93d9ccb2fa07985bbd24e9347065d6a
/src/test/java/com/bafl/webdriver/logInTest.java
26879ce0a680f2e045878d0d8304bbd57776c34b
[]
no_license
bafl/selenium2WebDriverWithJava
09de658b24e1fb397a3031512132d469deb6af29
f97f76ed2995b7aa15cc6333947c9d8488792d33
refs/heads/master
2021-01-10T14:04:03.445657
2016-03-13T21:48:38
2016-03-13T21:48:38
47,895,386
0
0
null
null
null
null
UTF-8
Java
false
false
2,810
java
package com.bafl.webdriver; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; /** * selenium2WebDriverWithJava * Created by Bartek on 12.12.2015. */ public class logInTest { private static WebDriver driver; private static String baseUrl; private static StringBuffer verificationErrors = new StringBuffer(); private static WebElement emailInput; private String expectedTitle = "Share Book Recommendations With Your Friends, Join Book Clubs, Answer Trivia"; @BeforeClass public static void setUp() throws Exception { driver = new FirefoxDriver(); baseUrl = "https://www.goodreads.com/"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void tryToLogInWithEmptyCredentials() throws Exception { driver.navigate().to(baseUrl); assertThat(driver.getTitle(), is(equalTo(expectedTitle))); driver.findElement(By.cssSelector("input.button")).click(); assertThat(driver.getTitle(), is("Sign Up")); try { assertEquals("Sorry, you must enter a name to sign up for Goodreads.", driver.findElement(By.cssSelector("p.flash.error")).getText()); } catch (Error e) { verificationErrors.append(e.toString()); } driver.navigate().back(); } @Test public void tryToLogInUsingIncorrectEmail() throws Exception { emailInput = driver.findElement(By.id("user_email")); emailInput.clear(); assertThat(emailInput.getAttribute("placeholder"),is("[email protected]")); emailInput.sendKeys("asd"); driver.findElement(By.name("next")).click(); //driver.findElement(By.cssSelector("input.button")).click(); //assertThat(driver.getTitle(), is("Sign in")); //try { // assertEquals("Sorry, we didn’t recognize that email/password combination. Please try again.", driver.findElement(By.cssSelector("p.flash.error")).getText()); //} catch (Error e) { // verificationErrors.append(e.toString()); //} } @AfterClass public static void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } }
83d866e43f049435d2387b086f3a0effcef32f7b
1802bd693b8506a0f3eace15ce6c3cbc8dbf1b9d
/manager-service/src/main/java/com/neusoft/managerservice/serviceimpl/SkuServiceImpl.java
f7b45922b126a35351cf8428410a8a1acc1a45c4
[]
no_license
872499002/guli201904
512ebc1705be6d221ca084543624c7bb6fb2c909
b5ca05560a8baef0b93d26f04d02390dd5d2a310
refs/heads/master
2020-05-24T05:48:09.707300
2019-05-17T01:21:20
2019-05-17T01:21:20
187,124,348
0
0
null
null
null
null
UTF-8
Java
false
false
12,422
java
package com.neusoft.managerservice.serviceimpl; import com.alibaba.dubbo.config.annotation.Service; import com.alibaba.fastjson.JSON; import com.neusoft.interfaces.SkuService; import com.neusoft.javabean.po.*; import com.neusoft.managerservice.dao.SkuAttrValueMapper; import com.neusoft.managerservice.dao.SkuImageMapper; import com.neusoft.managerservice.dao.SkuInfoMapper; import com.neusoft.managerservice.dao.SkuSaleAttrValueMapper; import com.neusoft.util.RedisUtil; import io.searchbox.client.JestClient; import io.searchbox.core.Delete; import io.searchbox.core.Index; import io.searchbox.core.Search; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import redis.clients.jedis.Jedis; import tk.mybatis.mapper.entity.Example; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; @Transactional @Service public class SkuServiceImpl implements SkuService { @Autowired SkuInfoMapper skuInfoMapper; @Autowired SkuImageMapper skuImageMapper; @Autowired SkuAttrValueMapper skuAttrValueMapper; @Autowired SkuSaleAttrValueMapper skuSaleAttrValueMapper; @Autowired RedisUtil redisUtil; @Autowired JestClient jestClient; /** * 查询skuInfo信息 * @param spuId * @return */ @Override public List<SkuInfo> getSkuListBySpu(Long spuId) { SkuInfo skuInfo = new SkuInfo(); skuInfo.setSpuId(spuId); List<SkuInfo> skuInfos = skuInfoMapper.select(skuInfo); return skuInfos; } /** * 查询SkuInfo及相关的SkuImage、SkuAttrValue、SkuSaleAttrValue */ @Override public List<SkuInfo> selectSkuInfoBySpuId(Long spuId) { return skuInfoMapper.selectSkuInfoBySpuId(spuId); } /** * 新增skuInfo */ @Override public void saveSku(SkuInfo skuInfo) { //插入SkuInfo skuInfoMapper.insert(skuInfo); Long skuInfoId = skuInfo.getId(); //插入SkuAttrValue List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList(); if(skuAttrValueList!=null && skuAttrValueList.size()>0){ for (SkuAttrValue skuAttrValue : skuAttrValueList) { skuAttrValue.setSkuId(skuInfoId); skuAttrValueMapper.insert(skuAttrValue); } } //插入SkuSaleAttrValue List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList(); if(skuSaleAttrValueList!=null&&skuSaleAttrValueList.size()>0){ for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) { skuSaleAttrValue.setSkuId(skuInfoId); skuSaleAttrValueMapper.insert(skuSaleAttrValue); } } //插入SkuImage List<SkuImage> skuImageList = skuInfo.getSkuImageList(); for (SkuImage skuImage : skuImageList) { skuImage.setSkuId(skuInfoId); skuImageMapper.insert(skuImage); } //将每次添加的数据存到es中 //toEs(skuInfoId); } /** * 将每次添加的数据存到es中 * @param skuInfoId */ public void toEs(Long skuInfoId){ SkuInfo skuInfo1 = skuInfoMapper.selectByPrimaryKey(skuInfoId); SkuAttrValue skuAttrValue = new SkuAttrValue(); skuAttrValue.setSkuId(skuInfoId); List<SkuAttrValue> skuAttrValueList1 = skuAttrValueMapper.select(skuAttrValue); skuInfo1.setSkuAttrValueList(skuAttrValueList1); //toElastic(skuInfo1); } /** * 删除sku * @param skuId */ @Override public void deleteSkuInfo(Long skuId) { //删除SkuImage SkuImage skuImage = new SkuImage(); skuImage.setSkuId(skuId); skuImageMapper.delete(skuImage); //删除SkuAttrValue SkuAttrValue skuAttrValue = new SkuAttrValue(); skuAttrValue.setSkuId(skuId); skuAttrValueMapper.delete(skuAttrValue); //删除SkuSaleAttrValue SkuSaleAttrValue skuSaleAttrValue = new SkuSaleAttrValue(); skuSaleAttrValue.setSkuId(skuId); skuSaleAttrValueMapper.delete(skuSaleAttrValue); //删除SkuInfo skuInfoMapper.deleteByPrimaryKey(skuId); Delete build = new Delete.Builder(skuId.toString()).index("guli2019").type("SkuLsInfo").build(); try { jestClient.execute(build); } catch (IOException e) { e.printStackTrace(); } } /** * 修改SkuInfo * @param skuInfo */ @Override public void updateSkuInfo(SkuInfo skuInfo) { //修改SkuInfo skuInfoMapper.updateByPrimaryKey(skuInfo); Long skuInfoId = skuInfo.getId(); //先根据skuId删除SkuImage SkuImage skuImage = new SkuImage(); skuImage.setSkuId(skuInfoId); skuImageMapper.delete(skuImage); //先根据skuId删除SkuAttrValue SkuAttrValue skuAttrValue = new SkuAttrValue(); skuAttrValue.setSkuId(skuInfoId); skuAttrValueMapper.delete(skuAttrValue); //先根据skuId删除SkuSaleAttrValue SkuSaleAttrValue skuSaleAttrValue = new SkuSaleAttrValue(); skuSaleAttrValue.setSkuId(skuInfoId); skuSaleAttrValueMapper.delete(skuSaleAttrValue); //插入SkuAttrValue List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList(); if(skuAttrValueList!=null && skuAttrValueList.size()>0){ for (SkuAttrValue skuAttrValue1 : skuAttrValueList) { skuAttrValue1.setSkuId(skuInfoId); skuAttrValueMapper.insert(skuAttrValue1); } } //插入SkuImage List<SkuImage> skuImageList = skuInfo.getSkuImageList(); for (SkuImage skuImage1 : skuImageList) { skuImage1.setSkuId(skuInfoId); skuImageMapper.insert(skuImage1); } //插入SkuSaleAttrValue List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList(); if(skuSaleAttrValueList!=null && skuSaleAttrValueList.size()>0){ for (SkuSaleAttrValue skuSaleAttrValue1 : skuSaleAttrValueList) { skuSaleAttrValue1.setSkuId(skuInfoId); skuSaleAttrValueMapper.insert(skuSaleAttrValue1); } } //将每次修改的数据更新到es中 //toEs(skuInfoId); } //先在redis中查询,如果没有再调数据库查询 @Override public SkuInfo getSkuInfoBySkuId(Long skuId) { SkuInfo skuInfo = null; //查询redis缓存 Jedis jedis = redisUtil.getJedis(); String key = "sku:"+skuId+":info"; String val =jedis.get(key); //通过上一个缓存锁在数据库查询到的数据是否为空 if("empty".equals(val)){ System.out.println(Thread.currentThread().getName()+"发现数据库中暂时没有该商品,直接返回空对象"); return skuInfo; } //判断redis是否有查询到数据 if(StringUtils.isBlank(val)){ System.out.println(Thread.currentThread().getName()+"发现缓存中暂时没有数据,申请分布式锁"); //如果在缓存中没有查询到数据,申请缓存锁 String OK = jedis.set("sku:" + skuId + ":lock", "1", "nx", "px", 5000); //判断是否申请到缓存锁 if("OK".equals(OK)){ /* try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }*/ System.out.println(Thread.currentThread().getName()+"获得分布式锁,开始访问数据库"); //如果得到缓存锁,查询DB skuInfo = getSkuInfoBySkuIdFormDB(skuId); //判断在数据库是否查到数据 if(skuInfo!=null){ System.out.println(Thread.currentThread().getName()+"通过分布式锁,查询到数据,同步缓存,然后会还锁"); //如果数据库查到数据,同步缓存 jedis.set(key,JSON.toJSONString(skuInfo)); System.out.println(Thread.currentThread().getName()+"从数据库正常得到数据"); }else{ System.out.println(Thread.currentThread().getName()+"通过分布式锁,没有查询到数据,通知下一个在10秒之内不要访问该sku"); //设置要查询的key为empty(空),方便通知下一个查询的 jedis.setex(key,3,"empty"); } //归还缓存锁 jedis.del("sku:" + skuId + ":lock"); }else{ //没有得到缓存锁,自旋 System.out.println(Thread.currentThread().getName()+"分布式锁被占用,开始自旋"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } getSkuInfoBySkuId(skuId); } }else{ //正常转换数据 System.out.println(Thread.currentThread().getName()+"从缓存正常得到数据"); skuInfo = JSON.parseObject(val, SkuInfo.class); } return skuInfo; } //在数据库中根据skuId查询skuInfo相关的spuImage、spuAttrValue、spuSaleAttrValue private SkuInfo getSkuInfoBySkuIdFormDB(Long skuId) { //查询skuInfo SkuInfo skuInfo = new SkuInfo(); skuInfo.setId(skuId); SkuInfo skuInfo1 = skuInfoMapper.selectOne(skuInfo); if(skuInfo1!=null){ //查询skuImage并存入skuInfo SkuImage skuImage = new SkuImage(); skuImage.setSkuId(skuId); List<SkuImage> skuImages = skuImageMapper.select(skuImage); skuInfo1.setSkuImageList(skuImages); } return skuInfo1; } /** * 通过spuId查询SaleAttrValue集合 * @param spuId * @return */ @Override public List<SkuInfo> selectSkuSaleAttrValueListBySpuId(Long spuId) { return skuInfoMapper.selectSkuSaleAttrValueListBySpuId(spuId); } /** * 通过三级分类id查询SkuIn * @param catalog3Id * @return */ @Override public List<SkuInfo> getSkuListByCatalog3Id(Long catalog3Id) { SkuInfo skuInfo = new SkuInfo(); skuInfo.setCatalog3Id(catalog3Id); List<SkuInfo> skuInfoList = skuInfoMapper.select(skuInfo); for (SkuInfo info : skuInfoList) { Long infoId = info.getId(); SkuAttrValue skuAttrValue = new SkuAttrValue(); skuAttrValue.setSkuId(infoId); List<SkuAttrValue> skuAttrValueList = skuAttrValueMapper.select(skuAttrValue); info.setSkuAttrValueList(skuAttrValueList); } return skuInfoList; } /** * 根据键盘输入模糊查询 * @param keyword * @return */ @Override public List<SkuInfo> getSkuListBykeyWord(String keyword) { Example example = new Example(SkuInfo.class); Example.Criteria criteria = example.createCriteria(); criteria.andLike("skuName",keyword); List<SkuInfo> skuInfos = skuInfoMapper.selectByExample(example); return skuInfos; } /** * 将sql中的数据存放到elastic中 */ public void toElastic(SkuInfo skuInfo) { // 转化es中的sku信息 SkuLsInfo skuLsInfo = new SkuLsInfo(); try { BeanUtils.copyProperties(skuLsInfo,skuInfo); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } String id = skuLsInfo.getId(); Index build = new Index.Builder(skuLsInfo).index("guli2019").type("SkuLsInfo").id(id).build(); try { jestClient.execute(build); } catch (IOException e) { e.printStackTrace(); } } }
a0bc5cbf44e617225ac5b1b062c8dd7784585d0a
fec763217095ed9e4dac86be33cc8da14ac88f83
/src/main/java/Common/utility.java
3f42e03ca47b5fae4c83ca0f51c1840c47bc1032
[]
no_license
s-manzoor/NewServiceApp
f708479f3b639c1f1e4f6db8cfe5f7a7c7b55276
6f742dff00eb9d712c16e4fc89f9afa0e96af51a
refs/heads/master
2022-12-29T06:46:49.208289
2020-09-29T12:23:53
2020-09-29T12:23:53
297,628,246
0
0
null
null
null
null
UTF-8
Java
false
false
1,639
java
package Common; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.testng.ITestResult; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class utility { private static final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd SSS"); public static String captureScreenshot(WebDriver driver, String screenshotname) { File sourceFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); String encodedBase64 = null; FileInputStream fileInputStreamReader = null; try { fileInputStreamReader = new FileInputStream(sourceFile); byte[] bytes = new byte[(int) sourceFile.length()]; fileInputStreamReader.read(bytes); encodedBase64 = new String(Base64.encodeBase64(bytes)); String dest = System.getProperty("user.dir") + "//Test-ScreenShots//" + screenshotname.trim() + ".png"; File destination = new File(dest); FileUtils.copyFile(sourceFile, destination); } catch (IOException e) { e.printStackTrace(); } return "data:image/png;base64," + encodedBase64; } public static String generateFileName(ITestResult result){ Date date = new Date(); String fileName = result.getName()+ "_" + dateFormat.format(date); return fileName; } }
2236ad682d613a5cc9d12425eeb6b59ee89b03ca
7cbad29007b65b81adadbea6a53e74e842537c35
/GestioneVideo Fattadame 1/src/EntityClass/Sport.java
e71d0552f636efcb69286cf1e10aab6cb8649610
[]
no_license
miky98/ProgettoIS
d45dbec93d4f653258e80032393a575af6abd335
ade5bf07347e82acc3126f7e37da7071fabfc428
refs/heads/master
2020-11-23T21:56:56.963886
2019-12-13T13:24:12
2019-12-13T13:24:12
227,837,959
0
0
null
null
null
null
UTF-8
Java
false
false
79
java
package EntityClass; public enum Sport { CALCIO, FORMULA1, MOTOGP }
[ "micha@DESKTOP-O38G8CV" ]
micha@DESKTOP-O38G8CV
cec82b512394381a275e3896111b6f62a3970de1
6c14485bfd5d37aa07e7b2f2640a5c0d6ce3de39
/motor-insurance/src/main/java/org/propertyinsurance/motor/infrastructure/Translator.java
a9a0367fdeee1c61e88b6aa5474eecd55492d20a
[]
no_license
zhuzhenguang/ebusiness
2a5669e68cd1d61359bb77ed788ce264efeb5eef
3c472255745d9907f7917df1a32ef5930d63a361
refs/heads/master
2021-01-10T21:06:30.397542
2013-06-16T18:19:05
2013-06-16T18:19:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
320
java
package org.propertyinsurance.motor.infrastructure; import org.propertyinsurance.motor.BusinessException; /** * 翻译器,用于核心系统和网销系统之间转换数据 * <p/> * User: zhu * Date: 13-2-14 * Time: 下午5:13 */ public interface Translator { void translate() throws BusinessException; }
71acfd1222a6070703dabd855fbe0e22ceefc831
99c19b9fc03978d950d3352528aaf17ac5ea861a
/beijing-cms-empty/src/main/java/com/wrj/cms/domain/Category.java
d069184339987f9e5e52f3a7d520a769f05ea57f
[]
no_license
kingdiedie/wrj
a2d1bf21adab5d293881b4f15ce9af9a496f0747
fdea9291fb546f90956531ca767483b6904ddb5b
refs/heads/master
2022-12-26T19:02:56.804657
2019-07-18T06:09:11
2019-07-18T06:45:16
197,528,151
0
0
null
2022-12-16T11:53:59
2019-07-18T06:44:34
CSS
UTF-8
Java
false
false
1,820
java
/** * */ package com.wrj.cms.domain; import java.io.Serializable; /** * 说明:分类表(cms_category) * * @author howsun ->[[email protected]] * @version 1.0 * * 2019年3月16日 下午8:35:45 */ public class Category implements Serializable{ private static final long serialVersionUID = 1L; /**主键**/ private Integer id; /**分类名称**/ private String name; /**排序**/ private Integer sorted; /**所属频道**/ private Channel channel; //------------------------------------------------------ public Category() { super(); } public Category(Integer id) { super(); this.id = id; } //------------------------------------------------------ public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSorted() { return sorted; } public void setSorted(Integer sorted) { this.sorted = sorted; } public Channel getChannel() { return channel; } public void setChannel(Channel channel) { this.channel = channel; } //------------------------------------------------------ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Category other = (Category) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
6567c24135f7276cfec3b53f18553d751409615e
c01b681f03a7f580d65425da1dfe03c302e29ba3
/src/main/java/ru/alex/testsort/bubble/BubbleSort.java
31277c1e258171a682bc2ec3013c20d9ff628251
[]
no_license
AlexeyVasenin/ru.alex.sortmethod
a90e515aad4af1cb621c07abdd5e3cb4913fd8d1
d1a0bf8fbf4862d88a4f6d697539831e9dbe05da
refs/heads/master
2023-04-17T19:54:21.427078
2021-04-05T11:42:59
2021-04-05T11:42:59
353,990,949
0
0
null
null
null
null
UTF-8
Java
false
false
783
java
package ru.alex.testsort.bubble; import ru.alex.testsort.Swap; import java.util.Arrays; /** * Пример алгоритма сортировки методом пузырьков(Bubble Sort) */ public class BubbleSort { public static void bubbleSort() { Integer[] numArr = {12, 10, 5, 1, 6, 8, 4, 7}; System.out.println(Arrays.toString(numArr)); boolean needIteration = true; while (needIteration) { needIteration = false; for (int i = 1; i < numArr.length; i++) { if (numArr[i] < numArr[i - 1]) { Swap.swap(numArr, i, i - 1); needIteration = true; } } } System.out.println(Arrays.toString(numArr)); } }
a50076c40d4d25d982f9733ef3f319cafd10e9f0
cf3eff91f555f8c412ed61e2463fb586e1154ea3
/src/core/com/googlecode/simplegwt/initialization/client/Initializable.java
c5a8138ff181eb159e94453fdb5fa1983333a323
[]
no_license
rlakoud/simple-gwt
4e1cd8af86a246f2c39f96bc8abda7362bbe5df0
11732198969fab3724cfcc73cefb3f3c0a7da634
refs/heads/master
2021-01-13T01:27:13.777919
2009-09-13T01:34:55
2009-09-13T01:34:55
39,090,898
0
0
null
null
null
null
UTF-8
Java
false
false
1,461
java
/* * Copyright 2008 Isaac Truett. * * 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.googlecode.simplegwt.initialization.client; import com.google.gwt.event.shared.HandlerRegistration; import com.googlecode.simplegwt.initialization.client.event.InitializationEvent; import com.googlecode.simplegwt.initialization.client.event.InitializationEventHandler; /** * Interface for objects that can be lazily initialized. * * @since 1.0 */ public interface Initializable { /** * @return true if this object has been initialized. */ boolean isInitialized(); /** * Initializes this object. */ void initialize(); /** * Adds a {@link InitializationEvent} handler. * * @param handler the initialization event handler * @return {@link HandlerRegistration} used to remove this handler */ HandlerRegistration addIntializationEventHandler(InitializationEventHandler handler); }
[ "itruett@1d095b2c-cabc-11dd-87b6-9d1a99559f42" ]
itruett@1d095b2c-cabc-11dd-87b6-9d1a99559f42
e4a64d15a1c11a56fcef2d548294b848e18eab34
d9d11f47b1e26daebec4cda90888bde95b31caab
/src/main/java/com/tfowler/utils/BeanTable.java
755e1301743e0e54862e19dad7b0e09bc0cf738b
[]
no_license
trentfowler/tf-utils
ff07f3bf7f7d5039b4d859633bfeb407741cf92f
1b41afb7c02a567cb424c6aa220187a6601ae7ac
refs/heads/master
2020-08-03T14:05:33.114385
2019-10-27T17:50:35
2019-10-27T17:50:35
211,779,185
0
0
null
null
null
null
UTF-8
Java
false
false
5,045
java
package com.tfowler.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.vandermeer.asciitable.AsciiTable; import de.vandermeer.asciitable.CWC_LongestWord; import de.vandermeer.asciitable.CWC_LongestWordMin; import de.vandermeer.asciithemes.u8.U8_Grids; /** * @see <a href="https://github.com/vdmeer/asciitable"></a> * @see <a href="http://www.vandermeer.de/projects/skb/java/asciitable/"></a> */ public class BeanTable { private static final Logger LOGGER = LoggerFactory.getLogger(BeanTable.class); // Defines the minimum number of characters each column in the rendered ASCII table can have. The // column width will only be set to this value and padded with blank spaces at the end of the // column when the longest word in column has fewer characters than this minimum value. private static final int MIN_CHARS_PER_COLUMN = 8; private BeanTable() {} // prevent instantiation public static <T> AsciiTable asciiTable(T bean) { return BeanTable.asciiTable(Collections.singletonList(bean)); } public static <T> String asciiRender(T bean) { return String.format("\n%s", BeanTable.asciiTable(Collections.singletonList(bean)).render()); } public static <T> String asciiRender(List<T> beans) { return String.format("\n%s", BeanTable.asciiTable(beans).render()); } public static <T> AsciiTable asciiTable(List<T> beans) { final AsciiTable table = new AsciiTable(); table.addRule(); if (beans == null || beans.isEmpty()) { table.addRow(String.format("Table: %s", (beans == null) ? "null" : "empty")); // set a one-character padding between the text and the outside border when returning a // single-cell ascii table to make it easier to see in prints table.setPadding(1); table.getRenderer().setCWC(new CWC_LongestWord()); table.getContext().setGrid(U8_Grids.borderDoubleLight()); table.addRule(); return table; } final Field[] fields = beans.get(0).getClass().getDeclaredFields(); table.addRow(Stream.of(fields).map(Field::getName).map(BeanTable::getNamePretty) .collect(Collectors.toList())); table.addRule(); for (T row : beans) { final List<String> cols = new ArrayList<>(); for (Field field : fields) { field.setAccessible(true); try { final String getterMethodName = String.format("get%s%s", field.getName().substring(0, 1).toUpperCase(), field.getName().substring(1)); final Method method = row.getClass().getMethod(getterMethodName); final String val = String.valueOf(method.invoke(row)); cols.add(val); } catch (Exception e) { LOGGER.warn( "Could not get ASCII representation of field \"{}\" with type \"{}\" in class \"{}\". ({}). Is \"{}\" a well-formed bean?", field.getName(), field.getType().getSimpleName(), row.getClass().getName(), e.getCause(), row.getClass().getSimpleName()); cols.add("Err"); } } table.addRow(cols); table.addRule(); } // take the longest word in each column and set the column width to it, or set the width to the // minimum if the longest word has fewer chars than than the minimum table.getRenderer().setCWC(new CWC_LongestWordMin(MIN_CHARS_PER_COLUMN)); table.getContext().setGrid(U8_Grids.borderDoubleLight()); return table; } private static String getNamePretty(final String name) { if (name == null) { return "null"; } if (name.isEmpty()) { return StringUtils.EMPTY; } // always capitalize the first character if (name.length() == 1) { return name.toUpperCase(); } final StringBuilder stringBuilder = new StringBuilder(name.length()); stringBuilder.append(name.substring(0, 1).toUpperCase()); // add a space before any uppercase character that is not the first character and that is // preceded by either a lowercase character or a digit for (int i = 1; i < name.length(); i++) { final boolean charIsUpperCase = Character.isUpperCase(name.charAt(i)); final boolean charIsDigit = Character.isDigit(name.charAt(i)); final boolean precedingCharIsLowerCase = Character.isLowerCase(name.charAt(i - 1)); final boolean precedingCharIsDigit = Character.isDigit(name.charAt(i - 1)); if (charIsUpperCase) { if (precedingCharIsLowerCase || precedingCharIsDigit) { stringBuilder.append(StringUtils.SPACE); } } else if (charIsDigit) { if (!precedingCharIsDigit && precedingCharIsLowerCase) { stringBuilder.append(StringUtils.SPACE); } } stringBuilder.append(name.charAt(i)); } return stringBuilder.toString(); } }
cd35aeced12bbd13024fb72659c74607cf7bf3a3
ca778c83807705135c4cd963a1a1dee9f514b416
/src/main/java/com/company/config/ApplicationConfig.java
dab4216f13a7cadc6487f674c371f8ff481bfefa
[]
no_license
andrii-ashomok/BulkDataFeeder
84d5c77b5308e136fbade3524475b47500cac2fc
6d6e169690bb476da2bdd913ab49f03e4f6e4620
refs/heads/main
2023-03-12T11:17:46.748139
2021-03-01T12:13:54
2021-03-01T12:13:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
226
java
package com.company.config; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; @EnableScheduling @Configuration public class ApplicationConfig { }
a10286fbed72894ec7609d04e95e29b937ca3747
1a622fd9f16b7320ea037726bfa7137ad85a6c66
/Generic/src/main/java/base/MobileAPI.java
80de91153e734bca0daecfc51d39a1872d794e5f
[]
no_license
aartipathania/AartiMobile
25d6f974a1b9d6c87ae93d80a545ad482c6e43d6
9104e0080d5943bd17641573de041a2158798d3e
refs/heads/master
2021-05-09T12:20:00.153429
2018-01-26T05:21:32
2018-01-26T05:21:32
119,008,988
0
0
null
null
null
null
UTF-8
Java
false
false
19,975
java
package base; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.LogStatus; import io.appium.java_client.*; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.remote.MobilePlatform; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.openqa.selenium.*; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.annotations.*; import org.testng.annotations.Optional; import reporting.ExtentManager; import reporting.ExtentTestManager; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Method; import java.net.URL; import java.security.Key; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.function.Function; public class MobileAPI { public static ExtentReports extent; @BeforeSuite public void extentSetup(ITestContext context) { ExtentManager.setOutputDirectory(context); extent = ExtentManager.getInstance(); } @BeforeMethod public void startExtent(Method method) { String className = convertCamelCase(method.getDeclaringClass().getSimpleName()); String methodName = convertCamelCase(method.getName()).toLowerCase(); ExtentTestManager.startTest( methodName ); ExtentTestManager.getTest().assignCategory(className); } protected String getStackTrace(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); return sw.toString(); } @Parameters({"appName"}) @AfterMethod public void afterEachTestMethod(@Optional("") String appName, ITestResult result) { ExtentTestManager.getTest().getTest().setStartedTime(getTime(result.getStartMillis())); ExtentTestManager.getTest().getTest().setEndedTime(getTime(result.getEndMillis())); for (String group : result.getMethod().getGroups()) { ExtentTestManager.getTest().assignCategory(group); } if (result.getStatus() == 1) { ExtentTestManager.getTest().log(LogStatus.PASS, "Test Passed"); } else if (result.getStatus() == 2) { ExtentTestManager.getTest().log(LogStatus.FAIL, getStackTrace(result.getThrowable())); } else if (result.getStatus() == 3) { ExtentTestManager.getTest().log(LogStatus.SKIP, "Test Skipped"); } ExtentTestManager.endTest(); extent.flush(); if (result.getStatus() == ITestResult.FAILURE) { captureScreenShot(result.getName(),ad); } ad.removeApp(appName); ad.quit(); } @AfterSuite public void generateReport() { extent.close(); } private Date getTime(long millis) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(millis); return calendar.getTime(); } public static AppiumDriver ad = null; private static WebDriverWait driverWait; public File appDirectory = null; public File findApp = null; @Parameters({"OS","appType","deviceType", "deviceName","version", "moduleName","appName"}) @BeforeMethod public void setUp(@Optional("android")String OS,@Optional("mobile") String appType,@Optional("real device") String deviceType, @Optional("") String deviceName, @Optional("") String version,@Optional("") String moduleName, @Optional("") String appName)throws IOException,InterruptedException{ if(OS.equalsIgnoreCase("ios")){ if(appType.contains("iPhone")){ appDirectory = new File("src/app"); findApp = new File(appDirectory,appName); if(deviceType.equalsIgnoreCase("RealDevice")){ ad = setUpiOsEnv(deviceName,version); }else if (deviceType.equalsIgnoreCase("Simulator")){ ad = setUpiOsEnv(deviceName,version); } }else if(appType.equalsIgnoreCase("iPad 2")){ appDirectory = new File("src/app"); findApp = new File(appDirectory,appName); if(deviceType.contains("RealDevice")){ ad = setUpiOsEnv(deviceName,version); }else if (deviceType.equalsIgnoreCase("Simulator")){ ad = setUpiOsEnv(deviceName,version); } } }else if(OS.equalsIgnoreCase("Android")){ if(appType.contains("Phone")){ appDirectory = new File("src/app"); findApp = new File(appDirectory,appName); if(deviceType.equalsIgnoreCase("RealDevice")){ ad = setUpAndroidEnv(deviceName,version); }else if (deviceType.equalsIgnoreCase("Emulator")){ ad =setUpAndroidEnv(deviceName,version); } }else if(OS.equalsIgnoreCase("Tablets")){ if(deviceType.equalsIgnoreCase("RealDevice")){ ad = setUpAndroidEnv(deviceName,version); }else if (deviceType.equalsIgnoreCase("Emulator")){ ad = setUpAndroidEnv(deviceName,version); } } } } public AppiumDriver setUpiOsEnv(String deviceName,String version)throws IOException,InterruptedException{ DesiredCapabilities cap = new DesiredCapabilities(); cap.setCapability(MobileCapabilityType.DEVICE_NAME, deviceName); cap.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.IOS); cap.setCapability(MobileCapabilityType.PLATFORM_VERSION, version); cap.setCapability(MobileCapabilityType.APP, findApp.getAbsolutePath()); ad = new IOSDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap); ad.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); return ad; } public AppiumDriver setUpAndroidEnv(String deviceName,String version)throws IOException,InterruptedException{ DesiredCapabilities cap = new DesiredCapabilities(); cap.setCapability(MobileCapabilityType.DEVICE_NAME, deviceName); cap.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID); cap.setCapability(MobileCapabilityType.PLATFORM_VERSION, version); cap.setCapability(MobileCapabilityType.APP, findApp.getAbsolutePath()); ad = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap); ad.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); return ad; } protected static void skip() throws SkipException { throw new SkipException("Skipping this test"); } private String convertCamelCase(String words){ return StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(words), ' '); } private static final List<Function<String, By>> resolvers = Arrays.asList(By::id, By::className, By::xpath); public WebElement locateElement(AppiumDriver ad, String locator) { WebElement el = null; for (Function<String, By> resolver : resolvers) { try { el = ad.findElement(resolver.apply(locator)); if (el != null) { break; } } catch (Exception e) { if (locator == null) { System.out.println("Ensure getResource() is fetching a valid resource in the locator resource file"); } System.out.println(e + "Locator: " + locator); } } return el; } public void clickOnElement(AppiumDriver ad, String locator) { locateElement(ad, locator).click(); } public void enterValueOnElement(AppiumDriver ad, String locator, String value) { locateElement(ad, locator).sendKeys(value); } public void swipeOnElement(AppiumDriver ad, String locator) { locateElement(ad, locator); } public void waitUntilPresence(AppiumDriver ad, String locator) { WebDriverWait wait = new WebDriverWait(ad, 45); wait.until(ExpectedConditions.presenceOfElementLocated(By.id(locator))); } public boolean validateClickable(AppiumDriver ad, WebElement element) { try { WebDriverWait wait = new WebDriverWait(ad, 10); wait.until(ExpectedConditions.elementToBeClickable(element)); } catch (Error e) { return false; } return true; } public void waitUntilClickable(AppiumDriver ad, String locator) { WebDriverWait wait = new WebDriverWait(ad, 45); //wait.until(ExpectedConditions.elementToBeClickable(By.id(locator))); } public void clickWhenClickable(AppiumDriver ad, String locator) { WebDriverWait wait = new WebDriverWait(ad, 45); wait.until(ExpectedConditions.elementToBeClickable(By.id(locator))).click(); } public void clickOnElementWithText(List<WebElement> elementList, String targetText) { for (WebElement element : elementList) { if (element.getText().contains(targetText)) { try { element.click(); break; } catch (Exception ignore) { } } } } public void clearField(AppiumDriver ad, String locator) { locateElement(ad, locator).clear(); } public void clickByXpathOnIOS(AppiumDriver ad, String locator) { //new TouchAction((MobileDriver) ad).tap(By.xpath(locator)).perform(); ad.tap(1, ad.findElement(MobileBy.xpath(locator)), 200); } public void sleep(int sec) { try { Thread.sleep(1000 * sec); } catch (InterruptedException e) { } } public void type(AppiumDriver ad, String locator, String value) { locateElement(ad, locator).sendKeys(value); } public List<String> getTexts(List<WebElement> elements) { List<String> text = new ArrayList<String>(); for (WebElement element : elements) { text.add(element.getText()); } return text; } public void touch(AppiumDriver ad, WebElement locator) { TouchAction touchAction = new TouchAction(ad); touchAction.moveTo(locator); } private Dimension getDemensions(AppiumDriver ad) { Dimension size = ad.manage().window().getSize(); return size; } private HashMap<String, Integer> setXandY(AppiumDriver ad, Double startX, Double endX, Double startY, Double endY) { HashMap<String, Integer> dimensions = new HashMap<String, Integer>(); Dimension size = getDemensions(ad); dimensions.put("startX", (int) (size.width * startX)); // 0.8); dimensions.put("startY", (int) (size.width * endX)); // 0.20 dimensions.put("endX", (int) (size.height / startY)); // 2 dimensions.put("endY", (int) (size.height / endY)); // 2 return dimensions; } public void swipeRightToLeft(AppiumDriver ad, Double startX, Double endX, Double startY, Double endY) { HashMap<String, Integer> d = setXandY(ad, startX, endX, startY, endY); ad.swipe(d.get("startX"), d.get("startY"), d.get("endX"), d.get("startY"), 3000); } public void swipeLeftToRight(AppiumDriver ad, Double startX, Double endX, Double startY, Double endY) { HashMap<String, Integer> d = setXandY(ad, startX, endX, startY, endY); ad.swipe(d.get("endX"), d.get("startY"), d.get("startX"), d.get("startY"), 3000); } public void swipeUp(AppiumDriver ad, Double startX, Double endX, Double startY, Double endY) { HashMap<String, Integer> d = setXandY(ad, startX, endX, startY, endY); ad.swipe(d.get("startX"), d.get("startY"), d.get("endX"), d.get("endT"), 3000); } public void swipeDown(AppiumDriver ad, Double startX, Double endX, Double startY, Double endY) { //Get the size of screen. HashMap<String, Integer> d = setXandY(ad, startX, endX, startY, endY); ad.swipe(d.get("startX"), d.get("startY"), d.get("endX"), d.get("endT"), 3000); } public String getText(AppiumDriver ad, String locator) { return locateElement(ad, locator).getText(); } public void sleepFor(int time) { try { Thread.sleep(1000 * time); } catch (Exception e) { e.printStackTrace(); } } public void tapOn(AppiumDriver ad, String element) { new TouchAction((MobileDriver) ad.findElement(By.xpath(element))); } public void captureScreenShot(String className, AppiumDriver ad) { String destDir = ""; File scrFile = ((TakesScreenshot) ad).getScreenshotAs(OutputType.FILE); DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa"); destDir = "screenshots/BaseLine"; new File(destDir).mkdirs(); String destFile = className + ".png"; try { FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile)); } catch (IOException e) { e.printStackTrace(); } } public void captureScreenShot(ITestResult result, String status) { String destDir = ""; String passfailMethod = result.getMethod().getRealClass().getSimpleName() + "." + result.getMethod().getMethodName(); File scrFile = ((TakesScreenshot) ad).getScreenshotAs(OutputType.FILE); DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa"); if (status.equalsIgnoreCase("fail")) { destDir = "screenshots/Failures"; } else if (status.equalsIgnoreCase("pass")) { destDir = "screenshots/Success"; } new File(destDir).mkdirs(); String destFile = passfailMethod + " - " + dateFormat.format(new Date()) + ".png"; try { FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile)); } catch (IOException e) { e.printStackTrace(); } } public void swipeUpNDown(AppiumDriver ad) { //Get the size of screen. Dimension size = ad.manage().window().getSize(); //Find swipe start and end point from screen's with and height. //Find starty point which is at bottom side of screen. int startx = (int) (size.width / 2); //Find vertical point where you wants to swipe. It is in middle of screen height. int starty = (int) (size.height * 0.80); //Find endx point which is at left side of screen. int endx = (int) (size.width * 0.30); //Find endy point which is at top side of screen. int endy = (int) (size.height * 0.20); //ad.swipe(startx, endy, startx, starty, 3000); ad.swipe(startx, endy, startx, starty, 3000); } public void scrollAndClickByName(String locator){ ad.scrollTo(locator).click(); } public void clickByXpath(String locator){ ad.findElement(By.xpath(locator)).click(); } public void clickByXpathWebElement(WebElement locator){ locator.click(); } public void typeByXpath(String locator, String value, Key key){ ad.findElement(By.xpath(locator)).sendKeys(value); } public void typeByXpath(String locator, String value){ ad.findElementByXPath(locator).sendKeys(value); } public static void scrollKeys(AppiumDriver driver, String[] list, String parent) { System.out.println("Starting the process"); for (int i = 0; i < list.length; i++) { MobileElement we = (MobileElement) driver.findElementByXPath(parent+"/UIAPickerWheel["+(i+1)+"]"); we.sendKeys(list[i]); } System.out.println("Ending Process"); } public void scrollToElement(AppiumDriver driver, String text){ MobileElement we = (MobileElement) driver.findElementByXPath(text); driver.scrollTo(we.getText()); } public void scrollToElementByWebElement(AppiumDriver driver, WebElement element){ MobileElement we = (MobileElement) element; driver.scrollTo(we.getText()); } /////-----*****-----/////-----*****-----/////-----*****-----/////-----*****-----/////-----*****-----///// // Set implicit wait in seconds public static void setWait(int seconds) { ad.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS); } // Return an element by locator public static WebElement element(By locator) { return ad.findElement(locator); } // Return a list of elements by locator public static List<WebElement> elements(By locator) { return ad.findElements(locator); } // Press the back button public static void back() { ad.navigate().back(); } // Return a list of elements by tag name public static List<WebElement> tags(String tagName) { return elements(for_tags(tagName)); } // Return a tag name locator public static By for_tags(String tagName) { return By.className(tagName); } // Return a static text element by xpath index public static WebElement s_text(int xpathIndex) { return element(for_text(xpathIndex)); } // Return a static text locator by xpath index public static By for_text(int xpathIndex) { return By.xpath("//android.widget.TextView[" + xpathIndex + "]"); } // Return a static text element that contains text public static WebElement text(String text) { return element(for_text(text)); } // Return a static text locator that contains text public static By for_text(String text) { return By.xpath("//android.widget.TextView[contains(@text, '" + text + "')]"); } // Return a static text element by exact text public static WebElement text_exact(String text) { return element(for_text_exact(text)); } // Return a static text locator by exact text public static By for_text_exact(String text) { return By.xpath("//android.widget.TextView[@text='" + text + "']"); } public static By for_find(String value) { return By.xpath("//*[@content-desc=\"" + value + "\" or @resource-id=\"" + value + "\" or @text=\"" + value + "\"] | //*[contains(translate(@content-desc,\"" + value + "\",\"" + value + "\"), \"" + value + "\") or contains(translate(@text,\"" + value + "\",\"" + value + "\"), \"" + value + "\") or @resource-id=\"" + value + "\"]"); } public static WebElement find(String value) { return element(for_find(value)); } // Wait 30 seconds for locator to find an element public static WebElement wait(By locator) { return driverWait.until(ExpectedConditions.visibilityOfElementLocated(locator)); } // Wait 60 seconds for locator to find all elements public static List<WebElement> waitAll(By locator) { return driverWait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator)); } // Wait 60 seconds for locator to not find a visible element public static boolean waitInvisible(By locator) { return driverWait.until(ExpectedConditions.invisibilityOfElementLocated(locator)); } // Return an element that contains name or text public static WebElement scroll_to(String value) { return ad.scrollTo(value); } // Return an element that exactly matches name or text public static WebElement scroll_to_exact(String value) { return ad.scrollToExact(value); } }
f4e09c118f17c6a87a08ee2f5e0d1c1d0c1bce8a
d89954550d9f78e1c2232041c3f160e7cfbdc27d
/branch/lidl/app/src/main/java/me/hekr/sthome/model/newstyle/ValveNewActivity.java
9912c530c4499b691d3314733974d32c17169b54
[]
no_license
Skons/familywell-lidl-android
4d9fbf844a065727e9d5ebbee00bf515257647b6
6218fdd314a031c4745e71f101061065cc27bbfc
refs/heads/master
2023-06-25T20:01:25.918742
2020-12-18T02:45:26
2020-12-18T02:45:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,650
java
package me.hekr.sthome.model.newstyle; import android.content.Intent; import android.text.TextUtils; import android.util.Log; import android.view.View; import java.util.ArrayList; import me.hekr.sthome.R; import me.hekr.sthome.common.TopbarSuperActivity; import me.hekr.sthome.model.modeladapter.OptionAdapter; import me.hekr.sthome.model.modelbean.EquipmentBean; import me.hekr.sthome.tools.NameSolve; import me.hekr.sthome.wheelwidget.view.WheelView; /** * Created by jishu0001 on 2016/10/15. */ public class ValveNewActivity extends TopbarSuperActivity { private EquipmentBean device; private String a; private ModelConditionPojo mcp = ModelConditionPojo.getInstance(); private ArrayList<String> itemslist = new ArrayList<String>(); private WheelView wheelView; @Override protected void onCreateInit() { try { initData(); wheelView = (WheelView)findViewById(R.id.item); wheelView.setAdapter(new OptionAdapter(itemslist,30)); wheelView.addChangingListener(new WheelView.OnWheelChangedListener() { @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { switch (newValue){ case 0: device.setState("01010000");//设置为开 break; case 1: device.setState("01000000");//设置为关 break; case 2: device.setState("0100ff00");//设置为切换 break; default:break; } } }); a = device.getState(); if( a != null){ if("01010000".equals(a)){ wheelView.setCurrentItem(0); }else if("01000000".equals(a)){ wheelView.setCurrentItem(1); }else if("0100ff00".equals(a) || "0100FF00".equals(a)){ wheelView.setCurrentItem(2); } } initViewGuider(); }catch (Exception e){ Log.i("ceshi","data is null"); } } @Override protected int getLayoutId() { return R.layout.activity_new_socket; } private void initViewGuider() { String name = ""; if(TextUtils.isEmpty(device.getEquipmentName())){ name = NameSolve.getDefaultName(this,device.getEquipmentDesc(),device.getEqid()); }else{ name = device.getEquipmentName(); } getTopBarView().setTopBarStatus(1, 2, name, getResources().getString(R.string.ok), new View.OnClickListener() { @Override public void onClick(View v) { if(mcp.position==-1){ Intent i = new Intent(ValveNewActivity.this, ModelCellListActivity.class); startActivity(i); }else { mcp.position=-1; Intent i = new Intent(ValveNewActivity.this, NewGroup2Activity.class); startActivity(i); } finish(); } }, new View.OnClickListener() { @Override public void onClick(View v) { if(mcp.position==-1){ if("input".equals(mcp.condition)){ mcp.input.add(device); } else if("output".equals(mcp.condition)){ mcp.output.add(device); } }else { if("input".equals(mcp.condition)){ mcp.input.set(mcp.position,device); } else if("output".equals(mcp.condition)){ mcp.output.set(mcp.position,device); } mcp.position=-1; } Intent i = new Intent(ValveNewActivity.this, NewGroup2Activity.class); startActivity(i); finish(); } }); } private void initData() { String[] strs = getResources().getStringArray(R.array.socket_actions); for(String ds:strs){ itemslist.add(ds); } if(mcp.position!=-1){ if("input".equals(mcp.condition)){ device = mcp.input.get(mcp.position); } else if("output".equals(mcp.condition)){ device = mcp.output.get(mcp.position); } }else { device = mcp.device; device.setState("01010000");//设置为开 } } }
04bec7e853e24e8e6fee1d147d30f61c21d6c3a0
26af96749dd96608a6f8afa720077842aa193d8a
/src/main/java/com/lhjl/tzzs/proxy/dto/SearchLimitDto.java
3cf64d17c6d4453260e1634fcedbf4b0499345c5
[]
no_license
SyuuTou/wlspacecraft
f2030f7ab70c09818c979cffa7613cd28150baf1
78a78861cb4e95e1a468f1d0a1f5682dc0e0b99f
refs/heads/master
2020-03-23T13:58:08.788678
2018-08-22T02:41:33
2018-08-22T02:41:33
141,648,032
1
0
null
null
null
null
UTF-8
Java
false
false
398
java
package com.lhjl.tzzs.proxy.dto; public class SearchLimitDto { String user_id; Integer limits; public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public Integer getLimits() { return limits; } public void setLimits(Integer limits) { this.limits = limits; } }