blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author_id
stringlengths
0
313
ef425b1d08aa2992f74c9392d959c0e9f62fef5b
a6e854b7dffbaa2300bd6e01f1b24f21a752baba
/MANREM_V5_0/src/main/java/wholesalemarket_LMP/results/WholesaleShowResults.java
6d1e01699da79fb213f66b49235b1470cff6c60e
[]
no_license
FMSilv/MANREMv5.0
b2b70145d53ed7f0cceca58e64b2ae9481039c31
967f20f07f652618abbcd0399d1341d178490b41
refs/heads/master
2021-06-29T03:54:12.416415
2019-02-10T19:21:14
2019-02-10T19:21:14
170,015,866
0
0
null
2020-10-13T11:57:09
2019-02-10T19:14:55
Java
UTF-8
Java
false
false
55,135
java
package wholesalemarket_LMP.results; import wholesalemarket_LMP.simul.GridData; import wholesalemarket_LMP.simul.WholesaleMarket; import wholesalemarket_LMP.simul.SupplierData; import wholesalemarket_LMP.simul.ProducerData; import java.util.ArrayList; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTabbedPane; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class WholesaleShowResults extends javax.swing.JFrame { private WholesaleMarket mainMarket; private ArrayList<GridData> grid_list; private ArrayList<ProducerData> producer_list; private ArrayList<SupplierData> supplier_list; private ArrayList<double[][]> commitment_list; private ArrayList<double[][]> LMP_list; private ArrayList<double[][]> priceSensitiveDemand; private ArrayList<double[][]> branchPowerFlow_list; private int totalBranches; private int totalBuses; private int totalProducers; private int totalSuppliers; private boolean isInputData; DefaultTableModel tableInput = null; DefaultTableModel tableOutput = null; private int indexHour; // Print Output private final int TABLE_COMMITMENT = 1; private final int TABLE_LMP = 2; private final int TABLE_PSDEMAND = 3; private final int TABLE_PROFITS = 5; private final int SUPPLY_DEMAND_PRODUCER = 0; private final int SUPPLY_DEMAND_SUPPLIER = 1; private final int BRANCH_DATA_SIZE = 6; private final int SUPPLIER_DATA_SIZE = 8; private final int HOUR_PER_DAY = WholesaleMarket.HOUR_PER_DAY; private final int START_HOUR = WholesaleMarket.START_HOUR; private Object[] comboBoxHour; private Object[][] busData; private Object[][] branchData; private Object[][] busLMPData_Day; private Object[][][] busLMPData_Hour; private Object[][][] producerData_Hour; private Object[][] producerData_Day; private Object[][][] producerCommitmentData_Hour; private Object[][] producerCommitmentData_Day; private Object[][][] producerProfitData_Hour; private Object[][] producerProfitData_Day; private Object[][][] supplierData_Hour; private Object[][] supplierData_Day; private Object[][][] supplierPriceSensitiveData_Hour; private Object[][] supplierPriceSensitiveData_Day; private double[] powerPerHour; private double[] pricePerHour; private double[][] producerProfits; private double[][] branchPowerFlow_abs; private Object[][] marketPrice; private Object[][][] branchPowerFlowData_Hour; private Object[][] branchPowerFlowData_Day; private final String[] outputComboBox = {"Select market results", "Generation Commitments", "Generator revenues", "LMP per bus", "Retailer results", "Market price", "Branches power flow"}; private final String[] busLMP_Title = {"Name", "Hour", "LMP(€/MWh)"}; private final String[] producerDataTitle = {"Name", "ID", "atBus", "Hour", "Start Price(€/MWh)", "Slope Price", "Min. Gen. Power(MW)", "Max. Gen. Power(MW)"}; private final String[] producerCommitmentTitle = {"Name", "Hour", "Power(MW)", "Min. Gen. Power(MW)", "Max. Gen. Power(MW)"}; private final String[] producerProfitTitle = {"Name", "Hour", "Power Commitment[MW]", "Marginal Cost[€/MWh]", "Sales Price[€/MWh]", "Revenue[€/h]", "Profit[€/h]"}; private final String[] supplierPriceSensitiveDataTitle = {"Name", "Hour", "Fixed Load(MW)", "Price-Sensitive Demand(MW)", "Total Load Demand [MW]"}; private final String[] marketPriceDataTitle = {"Hour", "Power(Mw)", "Price(€/MWh)"}; private final String[] branchPowerFlowTitle = {"Name", "Start Bus", "End Bus", "Reactance[ohms]", "Max. Capacity[MW]", "Power Flow[MW]"}; public WholesaleShowResults(WholesaleMarket _mainMarket) { initComponents(); mainMarket = _mainMarket; grid_list = mainMarket.getGridData(); totalBranches = grid_list.size(); totalBuses = (int) grid_list.get(0).getBusNr(); producer_list = mainMarket.getProducersData(); totalProducers = producer_list.size(); supplier_list = mainMarket.getSupplierData(); totalSuppliers = supplier_list.size(); createProducerDataMatrix(); createBranchDataMatrix(); createSupplierDataMatrix(); createBranchPowerFlowMatrix(); createProducerCommitmentDataMatrix(); createBranchLMPMatrix(); creatPriceSensitiveDemandMatrix(); defineWindow(); updateOutputNameList(0); initComboBox(); } /** * ComboBox initialization */ private void initComboBox() { comboBoxHour = new Object[HOUR_PER_DAY + 1]; int indexHour = START_HOUR; for (int h = 0; h < HOUR_PER_DAY + 1; h++) { if (h == 0) { comboBoxHour[h] = "All Day"; } else { comboBoxHour[h] = indexHour; indexHour++; } } // ComboBox for the output data jComboBox_OutputType.setModel(new DefaultComboBoxModel(outputComboBox)); jComboBoxOutputHour.setModel(new DefaultComboBoxModel(comboBoxHour)); jComboBox_OutputType.setSelectedIndex(0); jComboBoxOutputHour.setSelectedIndex(0); } private void defineWindow() { this.setTitle("Wholesale Simulation Results"); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.setAlwaysOnTop(false); this.setLocationRelativeTo(null); tableOutput = (DefaultTableModel) jTable_OutputData.getModel(); jTable_OutputData.setAutoscrolls(true); jTable_OutputData.setShowGrid(true); jTable_OutputData.setEnabled(false); int hour = jComboBoxOutputHour.getSelectedIndex(); jTabbedPaneOutput.add("Graphical [Output Chart Information]", ChartGenerator.drawLineGraph_SupplyVsDemand(producer_SupplyCurve(hour), supplier_DemandCurve(hour), "Supply and Demand [h =" + hour + "]", "Power [MW]", "Price per hour [€/MWh]")); jTabbedPaneOutput.setSelectedIndex(1); } private void createBranchDataMatrix() { branchData = new Object[totalBranches][BRANCH_DATA_SIZE]; busData = new Object[totalBranches][2]; for (int i = 0; i < grid_list.size(); i++) { branchData[i][0] = grid_list.get(i).getName(); branchData[i][1] = (int) grid_list.get(i).getBranchID(); branchData[i][2] = (int) grid_list.get(i).getStartBus(); branchData[i][3] = (int) grid_list.get(i).getEndBus(); busData[i][0] = (int) grid_list.get(i).getStartBus(); busData[i][1] = (int) grid_list.get(i).getEndBus(); branchData[i][4] = grid_list.get(i).getMaxCapacity(); branchData[i][5] = grid_list.get(i).getLosses(); } } private void createBranchLMPMatrix() { LMP_list = mainMarket.getLMPWithTrueCost(); //Size: 1 double[][] lmp_Matrix = LMP_list.get(0); // [24h][total Bus] int columnSize = busLMP_Title.length; busLMPData_Hour = new Object[HOUR_PER_DAY][totalBuses][columnSize]; //[24h][total Bus][Name;Hour;LMP] busLMPData_Day = new Object[HOUR_PER_DAY * totalBuses][columnSize]; //[24h * total Bus][Name;Hour;LMP] int index; int nameIndex; for (int h = 0; h < HOUR_PER_DAY; h++) { for (int i = 0; i < totalBuses; i++) { nameIndex = i + 1; indexHour = h + START_HOUR; busLMPData_Hour[h][i][0] = "Bus" + nameIndex; busLMPData_Hour[h][i][1] = String.format(indexHour + ".00"); busLMPData_Hour[h][i][2] = String.format("%.2f", lmp_Matrix[h][i]); } } for (int i = 0; i < HOUR_PER_DAY; i++) { for (int j = 0; j < totalBuses; j++) { index = i * totalBuses; nameIndex = j + 1; indexHour = i + START_HOUR; busLMPData_Day[index + j][0] = "Bus" + nameIndex; busLMPData_Day[index + j][1] = String.format(indexHour + ".00"); busLMPData_Day[index + j][2] = String.format("%.2f", lmp_Matrix[i][j]); } } } private void createProducerDataMatrix() { producerData_Hour = new Object[HOUR_PER_DAY][totalProducers][producerDataTitle.length]; producerData_Day = new Object[HOUR_PER_DAY * totalProducers][producerDataTitle.length]; int index; for (int h = 0; h < HOUR_PER_DAY; h++) { for (int i = 0; i < producer_list.size(); i++) { indexHour = h + START_HOUR; producerData_Hour[h][i][0] = producer_list.get(i).getName(); producerData_Hour[h][i][1] = (int) producer_list.get(i).getProducerID(); producerData_Hour[h][i][2] = (int) producer_list.get(i).getAtBus(); producerData_Hour[h][i][3] = String.format(indexHour + ".00"); producerData_Hour[h][i][4] = producer_list.get(i).getStartCost(h); producerData_Hour[h][i][5] = producer_list.get(i).getSlopeCost(h); producerData_Hour[h][i][6] = producer_list.get(i).getMinPot(h); producerData_Hour[h][i][7] = producer_list.get(i).getMaxPot(h); } } for (int h = 0; h < HOUR_PER_DAY; h++) { for (int j = 0; j < totalProducers; j++) { index = h * producer_list.size(); indexHour = h + START_HOUR; producerData_Day[index + j][0] = producer_list.get(j).getName(); producerData_Day[index + j][1] = (int) producer_list.get(j).getProducerID(); producerData_Day[index + j][2] = (int) producer_list.get(j).getAtBus(); producerData_Day[index + j][3] = String.format(indexHour + ".00"); producerData_Day[index + j][4] = producer_list.get(j).getStartCost(h); producerData_Day[index + j][5] = producer_list.get(j).getSlopeCost(h); producerData_Day[index + j][6] = producer_list.get(j).getMinPot(h); producerData_Day[index + j][7] = producer_list.get(j).getMaxPot(h); } } } private void createProducerCommitmentDataMatrix() { commitment_list = mainMarket.getProducerAgent_CommitmentWithTrueCost(); double[][] commitmentMatrix = commitment_list.get(0); // [24h][total Producers] producerCommitmentData_Hour = new Object[HOUR_PER_DAY][totalProducers][producerCommitmentTitle.length]; producerCommitmentData_Day = new Object[HOUR_PER_DAY * totalProducers][producerCommitmentTitle.length]; producerProfitData_Hour = new Object[HOUR_PER_DAY][totalProducers][producerProfitTitle.length]; producerProfitData_Day = new Object[HOUR_PER_DAY * totalProducers][producerProfitTitle.length]; powerPerHour = new double[HOUR_PER_DAY]; pricePerHour = new double[HOUR_PER_DAY]; double[][] demandPercentage = new double[HOUR_PER_DAY][commitmentMatrix[0].length]; double[][] pricePerProducer = new double[HOUR_PER_DAY][commitmentMatrix[0].length]; marketPrice = new Object[HOUR_PER_DAY][marketPriceDataTitle.length]; int index; int index_AgentBus; double startCost; double slopeCost; double powerCommitment; double marginalCost; double priceCommitment; for (int h = 0; h < HOUR_PER_DAY; h++) { for (int i = 0; i < commitmentMatrix[0].length; i++) { indexHour = h + START_HOUR; powerCommitment = Math.abs(commitmentMatrix[h][i]); producerCommitmentData_Hour[h][i][0] = producer_list.get(i).getName(); producerCommitmentData_Hour[h][i][1] = String.format(indexHour + ".00"); producerCommitmentData_Hour[h][i][2] = String.format("%.2f", powerCommitment); producerCommitmentData_Hour[h][i][3] = producer_list.get(i).getMinPot(h); producerCommitmentData_Hour[h][i][4] = producer_list.get(i).getMaxPot(h); //producerProfit = {"Name", "Hour", "Power Commitment[MW]", "Marginal Cost[€/MWh]", "Sales Price[€/MWh]", "Gross Revenue[€]", "Profit[€]"}; startCost = producer_list.get(i).getStartCost(h); slopeCost = producer_list.get(i).getSlopeCost(h); index_AgentBus = (int) producer_list.get(i).getAtBus() - 1; marginalCost = startCost + powerCommitment * slopeCost; priceCommitment = mainMarket.getLMPWithTrueCost().get(0)[h][index_AgentBus]; producerProfitData_Hour[h][i][0] = producer_list.get(i).getName(); producerProfitData_Hour[h][i][1] = String.format(indexHour + ".00"); producerProfitData_Hour[h][i][2] = String.format("%.2f", powerCommitment); producerProfitData_Hour[h][i][3] = String.format("%.2f", marginalCost); producerProfitData_Hour[h][i][4] = String.format("%.2f", priceCommitment); producerProfitData_Hour[h][i][5] = String.format("%.2f", priceCommitment * powerCommitment); producerProfitData_Hour[h][i][6] = String.format("%.2f", (priceCommitment - marginalCost) * powerCommitment); } for (int i = 0; i < commitmentMatrix[0].length; i++) { powerPerHour[h] += commitmentMatrix[h][i]; } for (int i = 0; i < commitmentMatrix[0].length; i++) { demandPercentage[h][i] = commitmentMatrix[h][i] / powerPerHour[h]; pricePerProducer[h][i] = commitmentMatrix[h][i] * producer_list.get(i).getSlopeCost(h) + producer_list.get(i).getStartCost(h); } for (int i = 0; i < commitmentMatrix[0].length; i++) { pricePerHour[h] += demandPercentage[h][i] * pricePerProducer[h][i]; } indexHour = h + START_HOUR; marketPrice[h][0] = String.format(indexHour + ".00"); marketPrice[h][1] = String.format("%.2f", powerPerHour[h]); marketPrice[h][2] = String.format("%.2f", pricePerHour[h]); } for (int i = 0; i < HOUR_PER_DAY; i++) { for (int j = 0; j < totalProducers; j++) { index = i * totalProducers; indexHour = i + START_HOUR; powerCommitment = Math.abs(commitmentMatrix[i][j]); producerCommitmentData_Day[index + j][0] = producer_list.get(j).getName(); producerCommitmentData_Day[index + j][1] = String.format(indexHour + ".00"); producerCommitmentData_Day[index + j][2] = String.format("%.2f", powerCommitment); producerCommitmentData_Day[index + j][3] = producer_list.get(j).getMinPot(i); producerCommitmentData_Day[index + j][4] = producer_list.get(j).getMaxPot(i); //producerProfit = {"Name", "Hour", "Power Commitment[MW]", "Marginal Cost[€/MWh]", "Sales Price[€/MWh]", "Gross Revenue[€]", "Profit[€]"}; startCost = producer_list.get(j).getStartCost(i); slopeCost = producer_list.get(j).getSlopeCost(i); index_AgentBus = (int) producer_list.get(j).getAtBus() - 1; marginalCost = startCost + powerCommitment * slopeCost; priceCommitment = mainMarket.getLMPWithTrueCost().get(0)[i][index_AgentBus]; producerProfitData_Day[index + j][0] = producer_list.get(j).getName(); producerProfitData_Day[index + j][1] = String.format(indexHour + ".00"); producerProfitData_Day[index + j][2] = String.format("%.2f", powerCommitment); producerProfitData_Day[index + j][3] = String.format("%.2f", marginalCost); producerProfitData_Day[index + j][4] = String.format("%.2f", priceCommitment); producerProfitData_Day[index + j][5] = String.format("%.2f", priceCommitment * powerCommitment); producerProfitData_Day[index + j][6] = String.format("%.2f", (priceCommitment - marginalCost) * powerCommitment); } } } private void createBranchPowerFlowMatrix() { branchPowerFlow_list = mainMarket.getGridBranchPowerFlow(); double[][] powerFlowMatrix = branchPowerFlow_list.get(0); int index; // branchPowerFlowTitle = {"Name", "Start Bus", "End Bus", "Reactance[ohms]", "Máx Capacity[MW]", "Power Flow[MW]"}; branchPowerFlowData_Hour = new Object[HOUR_PER_DAY][totalBranches][branchPowerFlowTitle.length]; branchPowerFlowData_Day = new Object[HOUR_PER_DAY * totalBranches][branchPowerFlowTitle.length]; branchPowerFlow_abs = new double[HOUR_PER_DAY][totalBranches]; for (int h = 0; h < HOUR_PER_DAY; h++) { for (int i = 0; i < totalBranches; i++) { branchPowerFlow_abs[h][i] = Math.abs(powerFlowMatrix[h][i]); branchPowerFlowData_Hour[h][i][0] = grid_list.get(i).getName(); branchPowerFlowData_Hour[h][i][1] = grid_list.get(i).getStartBus(); branchPowerFlowData_Hour[h][i][2] = grid_list.get(i).getEndBus(); branchPowerFlowData_Hour[h][i][3] = grid_list.get(i).getLosses(); branchPowerFlowData_Hour[h][i][4] = grid_list.get(i).getMaxCapacity(); branchPowerFlowData_Hour[h][i][5] = String.format("%.3f", powerFlowMatrix[h][i]); } } for (int h = 0; h < HOUR_PER_DAY; h++) { for (int j = 0; j < totalBranches; j++) { index = h * totalBranches; branchPowerFlowData_Day[index + j][0] = grid_list.get(j).getName(); branchPowerFlowData_Day[index + j][1] = grid_list.get(j).getStartBus(); branchPowerFlowData_Day[index + j][2] = grid_list.get(j).getEndBus(); branchPowerFlowData_Day[index + j][3] = grid_list.get(j).getLosses(); branchPowerFlowData_Day[index + j][4] = grid_list.get(j).getMaxCapacity(); branchPowerFlowData_Day[index + j][5] = String.format("%.3f", powerFlowMatrix[h][j]); } } } private void createSupplierDataMatrix() { supplierData_Hour = new Object[HOUR_PER_DAY][totalSuppliers][SUPPLIER_DATA_SIZE]; supplierData_Day = new Object[HOUR_PER_DAY * totalSuppliers][SUPPLIER_DATA_SIZE]; for (int h = 0; h < HOUR_PER_DAY; h++) { for (int i = 0; i < totalSuppliers; i++) { indexHour = h + START_HOUR; supplierData_Hour[h][i][0] = supplier_list.get(i).getName(); supplierData_Hour[h][i][1] = (int) supplier_list.get(i).getSupplierID(); supplierData_Hour[h][i][2] = (int) supplier_list.get(i).getAtBus(); supplierData_Hour[h][i][3] = String.format(indexHour + ".00"); supplierData_Hour[h][i][4] = supplier_list.get(i).getStartCost(h); supplierData_Hour[h][i][5] = supplier_list.get(i).getSlopeCost(h); supplierData_Hour[h][i][6] = supplier_list.get(i).getLoadFixedDemand(h); supplierData_Hour[h][i][7] = supplier_list.get(i).getMaxDemand(h); } } int index; for (int i = 0; i < HOUR_PER_DAY; i++) { for (int j = 0; j < totalSuppliers; j++) { index = i * totalSuppliers; indexHour = i + START_HOUR; supplierData_Day[index + j][0] = supplier_list.get(j).getName(); supplierData_Day[index + j][1] = (int) supplier_list.get(j).getSupplierID(); supplierData_Day[index + j][2] = (int) supplier_list.get(j).getAtBus(); supplierData_Day[index + j][3] = String.format(indexHour + ".00"); supplierData_Day[index + j][4] = supplier_list.get(j).getStartCost(i); supplierData_Day[index + j][5] = supplier_list.get(j).getSlopeCost(i); supplierData_Day[index + j][6] = supplier_list.get(j).getLoadFixedDemand(i); supplierData_Day[index + j][7] = supplier_list.get(j).getMaxDemand(i); } } } private void creatPriceSensitiveDemandMatrix() { priceSensitiveDemand = mainMarket.getSupplierAgent_PriceSensitiveDemandWithTrueCost(); int columnSize = supplierPriceSensitiveDataTitle.length; double[][] priceSensitiveMatrix = priceSensitiveDemand.get(0); // [24h][total Suppliers] supplierPriceSensitiveData_Hour = new Object[HOUR_PER_DAY][totalSuppliers][columnSize]; supplierPriceSensitiveData_Day = new Object[HOUR_PER_DAY * totalSuppliers][columnSize]; int index; for (int h = 0; h < HOUR_PER_DAY; h++) { for (int i = 0; i < priceSensitiveMatrix[0].length; i++) { indexHour = h + START_HOUR; supplierPriceSensitiveData_Hour[h][i][0] = supplier_list.get(i).getName(); supplierPriceSensitiveData_Hour[h][i][1] = String.format(indexHour + ".00"); supplierPriceSensitiveData_Hour[h][i][2] = supplier_list.get(i).getLoadFixedDemand(h); supplierPriceSensitiveData_Hour[h][i][3] = String.format("%.3f", Math.abs(priceSensitiveMatrix[h][i])); supplierPriceSensitiveData_Hour[h][i][4] = String.format("%.3f", supplier_list.get(i).getLoadFixedDemand(h) + Math.abs(priceSensitiveMatrix[h][i])); } } for (int h = 0; h < HOUR_PER_DAY; h++) { for (int i = 0; i < totalSuppliers; i++) { index = h * totalSuppliers; indexHour = h + START_HOUR; supplierPriceSensitiveData_Day[index + i][0] = supplier_list.get(i).getName(); supplierPriceSensitiveData_Day[index + i][1] = String.format(indexHour + ".00"); supplierPriceSensitiveData_Day[index + i][2] = supplier_list.get(i).getLoadFixedDemand(h); supplierPriceSensitiveData_Day[index + i][3] = String.format("%.3f", Math.abs(priceSensitiveMatrix[h][i])); supplierPriceSensitiveData_Day[index + i][4] = String.format("%.3f", supplier_list.get(i).getLoadFixedDemand(h) + Math.abs(priceSensitiveMatrix[h][i])); } } } public void printOutputTable(Object[][] insertData, String[] columnSize) { DefaultTableModel table = new DefaultTableModel(insertData, columnSize); jTable_OutputData.setModel(table); configOutputTable(columnSize.length); } private void configOutputTable(int _size) { for (int i = 0; i < _size; i++) { if (i == 0) { jTable_OutputData.getColumnModel().getColumn(i).setMinWidth(100); } else { jTable_OutputData.getColumnModel().getColumn(i).setMinWidth(70); } } DefaultTableCellRenderer render = new DefaultTableCellRenderer(); render.setHorizontalAlignment(JLabel.CENTER); jTable_OutputData.setDefaultRenderer(Object.class, render); } private void updateOutputNameList(int index) { DefaultListModel listModel = new DefaultListModel(); listModel.removeAllElements(); listModel.addElement("All Data"); jLabel2.setVisible(true); jComboBoxOutputHour.setVisible(true); switch (index) { case 0: printOutputTable(null, marketPriceDataTitle); break; case 1: // Info is equal for the case 2 case 2: for (Object[] producerData_Hour1 : producerData_Hour[0]) { listModel.addElement(producerData_Hour1[0].toString()); } printOutputTable(null, producerCommitmentTitle); break; case 3: for (int i = 1; i < totalBuses + 1; i++) { listModel.addElement("Bus" + i); } printOutputTable(null, busLMP_Title); break; case 4: for (int i = 0; i < totalSuppliers; i++) { listModel.addElement(supplierData_Hour[0][i][0].toString()); } printOutputTable(null, supplierPriceSensitiveDataTitle); break; case 6: for (Object[] branchPowerFlowData1 : branchPowerFlowData_Hour[0]) { listModel.addElement(branchPowerFlowData1[0].toString()); } printOutputTable(null, branchPowerFlowTitle); break; default: printOutputTable(null, marketPriceDataTitle); break; } jList_DataAgentOutput.setModel(listModel); jList_DataAgentOutput.setSelectedIndex(0); } private void printDetailedInfo(int[] selectIndex, int hour, int tableType, String[] tableTitle, Object[][] tableData2D, Object[][][] tableData3D, boolean isInputData) { int TotalselectData = selectIndex.length; Object[][] selectMatrix; int columnSize = tableTitle.length; jTabbedPaneOutput.setSelectedIndex(0); if (TotalselectData < 1 || selectIndex[0] == 0) { if (hour == -1) { printOutputTable(tableData2D, tableTitle); } else { printOutputTable(tableData3D[hour], tableTitle); } } else { if (hour == -1) { int index = 0; selectMatrix = new Object[HOUR_PER_DAY * TotalselectData][columnSize]; while (index < HOUR_PER_DAY * TotalselectData - 1) { for (int h = 0; h < HOUR_PER_DAY; h++) { for (int j = 0; j < TotalselectData; j++) { for (int i = 0; i < columnSize; i++) { selectMatrix[index][i] = tableData3D[h][selectIndex[j] - 1][i]; } index++; } } } } else { selectMatrix = new Object[TotalselectData][columnSize]; for (int i = 0; i < TotalselectData; i++) { for (int j = 0; j < columnSize; j++) { selectMatrix[i][j] = tableData3D[hour][selectIndex[i] - 1][j]; } } } printOutputTable(selectMatrix, tableTitle); } } private void createLineChartOutput(JTabbedPane _tabPane, Object[][] _agentData, double[][] _outputData, int[] _selectIndex, String _title, String _axisX, String _axisY) { String[] legend; double[][] showData; if (_tabPane.getTabCount() != 1) { _tabPane.remove(1); } if (_selectIndex[0] == 0) { int totalAgents = _outputData[0].length; // Número total de agentes com resultados gerados legend = new String[totalAgents]; // Número de legendas = número total de agentes for (int i = 0; i < totalAgents; i++) { legend[i] = _agentData[i][0].toString(); } _tabPane.add("Graphical [Output Chart Information]", ChartGenerator.drawLineGraph(legend, _outputData, _title, _axisX, _axisY)); } else { int totalAgents = _selectIndex.length; // Número total de agentes seleccionados legend = new String[totalAgents]; // Número de legendas = número de agentes showData = new double[_outputData.length][totalAgents]; for (int i = 0; i < totalAgents; i++) { legend[i] = _agentData[_selectIndex[i] - 1][0].toString(); // Cria legenda com os nomes dos agentes seleccionados for (int j = 0; j < _outputData.length; j++) { showData[j][i] = _outputData[j][_selectIndex[i] - 1]; } } _tabPane.add("Graphical [Output Chart Information]", ChartGenerator.drawLineGraph(legend, showData, _title, _axisX, _axisY)); } _tabPane.setSelectedIndex(1); } private void createLineChartOutput_Supplier(int[] selectIndex, String title, String axisX, String axisY) { String legend; int hour = jComboBoxOutputHour.getSelectedIndex() - 1; if (selectIndex[0] != 0 && selectIndex.length == 1 && hour != -1) { double maxDemand = Double.parseDouble(supplierData_Hour[hour][selectIndex[0] - 1][7].toString()); double minDemand = Double.parseDouble(supplierData_Hour[hour][selectIndex[0] - 1][6].toString()); double slopeValue = Double.parseDouble(supplierData_Hour[hour][selectIndex[0] - 1][5].toString()); // Slope Price double[] chartData = new double[6]; // Min Demand, Start Price, Max Demand, Last Price, Real Demand, Real Price legend = supplierData_Hour[hour][selectIndex[0] - 1][0].toString(); chartData[0] = 0; chartData[1] = Double.parseDouble(supplierData_Hour[hour][selectIndex[0] - 1][4].toString()); // Start Price chartData[2] = maxDemand - minDemand; // Máx Price Sensitive Demand chartData[3] = chartData[1] - chartData[2] * slopeValue; chartData[4] = mainMarket.getSupplierAgent_PriceSensitiveDemandWithTrueCost().get(0)[hour][selectIndex[0] - 1]; // Price Sensitive Commitment chartData[5] = chartData[1] - chartData[4] * slopeValue; jTabbedPaneOutput.add("Graphical [Output Chart Information]", ChartGenerator.drawLineGraph_MarginalCostVsRealPrice(legend, chartData, title+"[Hour:" + hour + "]", axisX, axisY)); jTabbedPaneOutput.setSelectedIndex(1); } else { double[][] priceSensitiveChartData = new double[HOUR_PER_DAY][supplierPriceSensitiveData_Hour[0].length]; axisX = "Hour"; axisY = "Power [MW]"; for(int i = 0; i < HOUR_PER_DAY; i++) { for(int j = 0; j < supplierPriceSensitiveData_Hour[0].length; j++) { priceSensitiveChartData[i][j] = Double.parseDouble(supplierPriceSensitiveData_Hour[i][j][4].toString()); } } createLineChartOutput(jTabbedPaneOutput, supplierData_Hour[0], priceSensitiveChartData, selectIndex, title+" (Fixed + Price Sensitive)", axisX, axisY); } } private void creatChartOutput_ProducerCommitment(int[] selectIndex, String title, String axisX, String axisY) { if (selectIndex.length > 1) { JOptionPane.showMessageDialog(null, "Please select only one Agent option!", "Error", JOptionPane.ERROR_MESSAGE); } else { int hour = jComboBoxOutputHour.getSelectedIndex() - 1; if (hour == -1) { this.setAlwaysOnTop(false); JOptionPane.showMessageDialog(null, "Please select only one hour!", "Error", JOptionPane.ERROR_MESSAGE); } else { String legend; int agentIndex = selectIndex[0] - 1; int agentBus = Integer.parseInt(producerData_Hour[hour][agentIndex][2].toString()) - 1; double slopeCost = Double.parseDouble(producerData_Hour[hour][agentIndex][5].toString()); double[] chartData = new double[6]; // Min Power Capacity, Start Price, Max Power Capacity, Last Price, Power Commitment, LMP_k legend = producerData_Hour[hour][agentIndex][0].toString(); chartData[0] = Double.parseDouble(producerData_Hour[hour][agentIndex][6].toString()); // Min Power Capacity chartData[1] = Double.parseDouble(producerData_Hour[hour][agentIndex][4].toString()); // Start Cost chartData[2] = Double.parseDouble(producerData_Hour[hour][agentIndex][7].toString()); // Máx Power Capacity chartData[3] = chartData[1] + slopeCost * chartData[2]; chartData[4] = Double.parseDouble(producerCommitmentData_Hour[hour][agentIndex][2].toString()); chartData[5] = Double.parseDouble(busLMPData_Hour[hour][agentBus][2].toString()); jTabbedPaneOutput.add("Graphical [Output Chart Information]", ChartGenerator.drawLineGraph_MarginalCostVsRealPrice(legend, chartData, title, axisX, axisY)); jTabbedPaneOutput.setSelectedIndex(1); } } } private double[][] producer_SupplyCurve(int _hour) { double[][] producerAuxData = new double[totalProducers][6]; // start Price, slope Price, minCap, maxCap, Current Power, Current Price double[] producerPrices = new double[totalProducers * 2]; // Price for (int i = 0; i < totalProducers; i++) { producerAuxData[i][0] = Double.parseDouble(producerData_Hour[_hour][i][4].toString()); // Producer Start Cost producerAuxData[i][1] = Double.parseDouble(producerData_Hour[_hour][i][5].toString()); // Producer Slope Price producerAuxData[i][2] = Double.parseDouble(producerData_Hour[_hour][i][6].toString()); // Producer Min Generation Cap producerPrices[2 * i] = producerAuxData[i][0] + 2 * producerAuxData[i][1] * producerAuxData[i][2]; // Min Capacity Producer Price producerAuxData[i][3] = Double.parseDouble(producerData_Hour[_hour][i][7].toString()); // Producer Max Generation Cap producerPrices[2 * i + 1] = producerAuxData[i][0] + 2 * producerAuxData[i][1] * producerAuxData[i][3]; // Máx Capacity Producer Price producerAuxData[i][4] = producerAuxData[i][2]; producerAuxData[i][5] = producerPrices[2 * i]; } double[][] producerChartPoints = createSupplyVsDemand(SUPPLY_DEMAND_PRODUCER, totalProducers, producerAuxData, producerPrices); return producerChartPoints; } private double[][] supplier_DemandCurve(int _hour) { double[][] supplierAuxData = new double[totalSuppliers][6]; // Fixed Demand, Start Price, Slope Price, PS Demand, Current Power, Current Price double[] supplierPrices = new double[totalSuppliers * 2]; // Price's Matrix double fixedDemand; double startPrice; double slopePrice; double ps_Demand; for (int i = 0; i < totalSuppliers; i++) { startPrice = Double.parseDouble(supplierData_Hour[_hour][i][4].toString()); slopePrice = Double.parseDouble(supplierData_Hour[_hour][i][5].toString()); fixedDemand = Double.parseDouble(supplierData_Hour[_hour][i][6].toString()); ps_Demand = Double.parseDouble(supplierData_Hour[_hour][i][7].toString()) - fixedDemand; supplierAuxData[i][0] = fixedDemand; supplierAuxData[i][1] = startPrice; supplierAuxData[i][2] = slopePrice; supplierAuxData[i][3] = ps_Demand; supplierAuxData[i][4] = 0.0; supplierAuxData[i][5] = startPrice; supplierPrices[2 * i] = startPrice; supplierPrices[2 * i + 1] = startPrice - 2 * slopePrice * ps_Demand; } double[][] supplierChartPoints = createSupplyVsDemand(SUPPLY_DEMAND_SUPPLIER, totalSuppliers, supplierAuxData, supplierPrices); return supplierChartPoints; } public double[][] createSupplyVsDemand(int _agentType, int agentsNumber, double[][] _agentData, double[] _agentsPrice) { double[][] chartPoints = new double[2 * agentsNumber - 1][4]; // leftPoint(power, price), rightPoint(power, price double auxValue; double firstPrice; double lastPrice; double auxPower; for (int i = 0; i < 2 * agentsNumber; i++) { for (int j = i + 1; j < 2 * agentsNumber; j++) { if (_agentType == 0) { // Agent Producer if (_agentsPrice[i] > _agentsPrice[j]) { auxValue = _agentsPrice[i]; _agentsPrice[i] = _agentsPrice[j]; _agentsPrice[j] = auxValue; } } else { if (_agentsPrice[i] < _agentsPrice[j]) { auxValue = _agentsPrice[i]; _agentsPrice[i] = _agentsPrice[j]; _agentsPrice[j] = auxValue; } } } } firstPrice = _agentsPrice[0]; for (int i = 0; i < agentsNumber; i++) { if (_agentType == 0) { // Agent Producer if (firstPrice >= _agentData[i][5]) { chartPoints[0][0] += _agentData[i][4]; } } else { // Agent Supplier chartPoints[0][0] += _agentData[i][0]; if (firstPrice <= _agentData[i][5]) { chartPoints[0][0] += _agentData[i][4]; } } } for (int i = 0; i < 2 * agentsNumber - 1; i++) { chartPoints[i][1] = _agentsPrice[i]; chartPoints[i][3] = _agentsPrice[i + 1]; if (i > 0) { chartPoints[i][0] = chartPoints[i - 1][2]; } chartPoints[i][2] = chartPoints[i][0]; lastPrice = _agentsPrice[i + 1]; if (_agentType == 0) { // Agent Producer for (int j = 0; j < agentsNumber; j++) { if (lastPrice > _agentData[j][5]) { if (Math.abs(_agentData[j][4] - _agentData[j][3]) > 0.000001) { // It is not the same value auxPower = (lastPrice - _agentData[j][0]) / (2 * _agentData[j][1]); chartPoints[i][2] += auxPower - _agentData[j][4]; _agentData[j][4] = auxPower; _agentData[j][5] = lastPrice; } } } } else { // Agent Supplier for (int j = 0; j < agentsNumber; j++) { if (lastPrice < _agentData[j][5]) { if (Math.abs(_agentData[j][4] - _agentData[j][3]) > 0.000001) { // It is not the same value auxPower = (_agentData[j][1] - lastPrice) / (2 * _agentData[j][2]); chartPoints[i][2] += auxPower - _agentData[j][4]; _agentData[j][4] = auxPower; _agentData[j][5] = lastPrice; } } } } } return chartPoints; } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jComboBox_OutputType = new javax.swing.JComboBox(); jScrollPane3 = new javax.swing.JScrollPane(); jList_DataAgentOutput = new javax.swing.JList(); jLabel2 = new javax.swing.JLabel(); jComboBoxOutputHour = new javax.swing.JComboBox(); jButton_showOutputData = new javax.swing.JButton(); jTabbedPaneOutput = new javax.swing.JTabbedPane(); jScrollPane4 = new javax.swing.JScrollPane(); jTable_OutputData = new javax.swing.JTable(); jButtonChartOutput = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jComboBox_OutputType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jComboBox_OutputType.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox_OutputTypeActionPerformed(evt); } }); jList_DataAgentOutput.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jScrollPane3.setViewportView(jList_DataAgentOutput); jLabel2.setText("Select Hour:"); jComboBoxOutputHour.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jButton_showOutputData.setText("Display OutputData"); jButton_showOutputData.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_showOutputDataActionPerformed(evt); } }); jTable_OutputData.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane4.setViewportView(jTable_OutputData); jTabbedPaneOutput.addTab("Show Output Data [Table]", jScrollPane4); jButtonChartOutput.setText("Display Chart"); jButtonChartOutput.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonChartOutputActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane3) .addComponent(jButtonChartOutput, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(jComboBox_OutputType, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jButton_showOutputData, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jComboBoxOutputHour, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTabbedPaneOutput, javax.swing.GroupLayout.DEFAULT_SIZE, 659, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPaneOutput, javax.swing.GroupLayout.DEFAULT_SIZE, 472, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jComboBox_OutputType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 298, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBoxOutputHour, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addComponent(jButton_showOutputData) .addGap(18, 18, 18) .addComponent(jButtonChartOutput))) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jComboBox_OutputTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_OutputTypeActionPerformed // TODO add your handling code here: if (jComboBox_OutputType.getSelectedIndex() != 0) { jLabel2.setEnabled(true); jComboBoxOutputHour.setEnabled(true); jComboBoxOutputHour.setModel(new DefaultComboBoxModel(comboBoxHour)); if (jComboBox_OutputType.getSelectedIndex() != 5) { jButton_showOutputData.setEnabled(true); jButtonChartOutput.setEnabled(true); jTable_OutputData.setEnabled(true); jList_DataAgentOutput.setEnabled(true); updateOutputNameList(jComboBox_OutputType.getSelectedIndex()); } else { jComboBoxOutputHour.removeItemAt(0); jButton_showOutputData.setEnabled(false); jTable_OutputData.setEnabled(false); jList_DataAgentOutput.setEnabled(false); jButtonChartOutput.setEnabled(true); updateOutputNameList(jComboBox_OutputType.getSelectedIndex()); } } else { jButton_showOutputData.setEnabled(false); jButtonChartOutput.setEnabled(false); jList_DataAgentOutput.setEnabled(false); jLabel2.setEnabled(false); jComboBoxOutputHour.setEnabled(false); } }//GEN-LAST:event_jComboBox_OutputTypeActionPerformed private void jButton_showOutputDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_showOutputDataActionPerformed // TODO add your handling code here: isInputData = false; int[] selectIndex = jList_DataAgentOutput.getSelectedIndices(); int comboBoxIndex = jComboBox_OutputType.getSelectedIndex(); int hour = jComboBoxOutputHour.getSelectedIndex() - 1; switch (comboBoxIndex) { case 1: printDetailedInfo(selectIndex, hour, TABLE_COMMITMENT, producerCommitmentTitle, producerCommitmentData_Day, producerCommitmentData_Hour, isInputData); break; case 2: printDetailedInfo(selectIndex, hour, TABLE_PROFITS, producerProfitTitle, producerProfitData_Day, producerProfitData_Hour, isInputData); break; case 3: printDetailedInfo(selectIndex, hour, TABLE_LMP, busLMP_Title, busLMPData_Day, busLMPData_Hour, isInputData); break; case 4: printDetailedInfo(selectIndex, hour, TABLE_PSDEMAND, supplierPriceSensitiveDataTitle, supplierPriceSensitiveData_Day, supplierPriceSensitiveData_Hour, isInputData); break; case 5: if (hour == -1) { printOutputTable(marketPrice, marketPriceDataTitle); } else { Object[][] auxMatrix = new Object[1][marketPriceDataTitle.length]; auxMatrix[0] = marketPrice[hour]; printOutputTable(auxMatrix, marketPriceDataTitle); } break; case 6: printDetailedInfo(selectIndex, hour, TABLE_PSDEMAND, branchPowerFlowTitle, branchPowerFlowData_Day, branchPowerFlowData_Hour, isInputData); break; default: hour = -1; printDetailedInfo(selectIndex, hour, TABLE_COMMITMENT, producerCommitmentTitle, null, null, isInputData); break; } }//GEN-LAST:event_jButton_showOutputDataActionPerformed private void jButtonChartOutputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonChartOutputActionPerformed // TODO add your handling code here: int[] selectIndex = jList_DataAgentOutput.getSelectedIndices(); int comboBoxIndex = jComboBox_OutputType.getSelectedIndex(); int hour = jComboBoxOutputHour.getSelectedIndex() - 1; int printHour = hour + START_HOUR; Object[][] auxData; String title; String axisX; String axisY; if (jTabbedPaneOutput.getTabCount() != 1) { jTabbedPaneOutput.remove(1); } switch (comboBoxIndex) { case 1: title = "Generator Commitment"; axisX = "Hour"; axisY = "Quantity [MWh]"; createLineChartOutput(jTabbedPaneOutput, producerData_Hour[0], mainMarket.getProducerAgent_CommitmentWithTrueCost().get(0), selectIndex, title, axisX, axisY); break; case 2: if (hour == -1) { producerProfits = new double[HOUR_PER_DAY][producerData_Hour[0].length]; title = "Generators' Profits"; axisX = "Hour"; axisY = "Profits [€/hour]"; for (int h = 0; h < HOUR_PER_DAY; h++) { for (int i = 0; i < producerData_Hour[0].length; i++) { producerProfits[h][i] = Double.parseDouble(producerProfitData_Hour[h][i][6].toString()); } } createLineChartOutput(jTabbedPaneOutput, producerData_Hour[0], producerProfits, selectIndex, title, axisX, axisY); } else { if (selectIndex.length == 1 && selectIndex[0] != 0) { title = "Price/Power Commitment [Hour:" + printHour + "]"; axisX = "Quantity [MWh]"; axisY = "Price [€/MWh]"; creatChartOutput_ProducerCommitment(selectIndex, title, axisX, axisY); } } break; case 3: title = "Grid LMP"; axisX = "Hour"; axisY = "Quantity [MWh]"; auxData = new Object[busLMPData_Hour[0].length][1]; for (int i = 0; i < busLMPData_Hour[0].length; i++) { auxData[i][0] = busLMPData_Hour[0][i][0]; } createLineChartOutput(jTabbedPaneOutput, auxData, mainMarket.getLMPWithTrueCost().get(0), selectIndex, title, axisX, axisY); break; case 4: title = "Price-Sensitive Demand"; axisX = "Quantity [MWh]"; axisY = "Price [€/MWh]"; createLineChartOutput_Supplier(selectIndex, title, axisX, axisY); break; case 5: printHour += 1; hour = jComboBoxOutputHour.getSelectedIndex(); title = "Supply and Demand [h =" + printHour + "]"; axisX = "Power [MW]"; axisY = "Price per hour [€/MWh]"; jTabbedPaneOutput.add("Graphical [Output Chart Information]", ChartGenerator.drawLineGraph_SupplyVsDemand(producer_SupplyCurve(hour), supplier_DemandCurve(hour), title, axisX, axisY)); jTabbedPaneOutput.setSelectedIndex(1); break; case 6: title = "Branch Power Flow"; axisX = "Hour"; axisY = "abs(Power[MW])"; createLineChartOutput(jTabbedPaneOutput, branchData, branchPowerFlow_abs, selectIndex, title, axisX, axisY); break; default: printHour += 1; hour = jComboBoxOutputHour.getSelectedIndex(); title = "Supply and Demand [h =" + printHour + "]"; axisX = "Power [MW]"; axisY = "Price per hour [€/MWh]"; jTabbedPaneOutput.add("Graphical [Output Chart Information]", ChartGenerator.drawLineGraph_SupplyVsDemand(producer_SupplyCurve(hour), supplier_DemandCurve(hour), title, axisX, axisY)); jTabbedPaneOutput.setSelectedIndex(1); break; } }//GEN-LAST:event_jButtonChartOutputActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonChartOutput; private javax.swing.JButton jButton_showOutputData; private javax.swing.JComboBox jComboBoxOutputHour; private javax.swing.JComboBox jComboBox_OutputType; private javax.swing.JLabel jLabel2; private javax.swing.JList jList_DataAgentOutput; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JTabbedPane jTabbedPaneOutput; private javax.swing.JTable jTable_OutputData; // End of variables declaration//GEN-END:variables }
8dd0d035e642b28ca85fa28479670bbdbf6380b1
c7c73ddb24289e60f4d0d0c9c4e5853ed117856b
/cyberstonbackendJWTtest/src/main/java/lk/cyberston/v1/cyberston/models/VerificationToken.java
2abe4d74ac09a1b7f1ae24aa53a04efca9475e25
[]
no_license
RavinduDON/JWT_test-Angular-Spring
731b61c9a538ffad32fa25e6b98b5c3501528168
25ed62e003542590fa00699a92d56236c44b4b03
refs/heads/master
2022-10-01T15:38:03.537042
2020-06-06T19:42:07
2020-06-06T19:42:07
262,002,073
1
0
null
null
null
null
UTF-8
Java
false
false
2,057
java
package lk.cyberston.v1.cyberston.models; import javax.persistence.*; import java.time.LocalDateTime; import java.util.UUID; @Entity public class VerificationToken { public static final String STATUS_PENDING = "PENDING"; public static final String STATUS_VERIFIED = "VERIFIED"; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String token; private String status; private LocalDateTime expiredDateTime; private LocalDateTime issuedDateTime; private LocalDateTime confirmedDateTime; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "user_id") private User user; public VerificationToken(){ this.token = UUID.randomUUID().toString(); this.issuedDateTime = LocalDateTime.now(); this.expiredDateTime = this.issuedDateTime.plusDays(1); this.status = STATUS_PENDING; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public LocalDateTime getExpiredDateTime() { return expiredDateTime; } public void setExpiredDateTime(LocalDateTime expiredDateTime) { this.expiredDateTime = expiredDateTime; } public LocalDateTime getIssuedDateTime() { return issuedDateTime; } public void setIssuedDateTime(LocalDateTime issuedDateTime) { this.issuedDateTime = issuedDateTime; } public LocalDateTime getConfirmedDateTime() { return confirmedDateTime; } public void setConfirmedDateTime(LocalDateTime confirmedDateTime) { this.confirmedDateTime = confirmedDateTime; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
38dcd1e63cb2bb66c08282b503583d9165ede280
aea4c4fae61b415e3244c5f79fee4c7562a5b4cd
/JavaFXGame/Logic/src/Logic/Player.java
3bd4b8c16f3c5ab8e1c4270a9aedb88eb742db07
[]
no_license
alexreal1314/Java
27190604ae37376837767588d7b6b11172b8bf67
31e0d4dd391c404b7a01dcc51eb7e604ff3efa7f
refs/heads/master
2021-01-18T16:40:27.980775
2017-04-01T10:41:21
2017-04-01T10:41:21
86,755,180
0
0
null
null
null
null
UTF-8
Java
false
false
2,907
java
package Logic; import java.math.BigInteger; import java.util.Comparator; /** * Created by alex on 19/11/2016. */ public class Player implements Cloneable{ //private final String compName = "Computer"; private String m_PlayerName; private int m_SumOfPoints = 0; private boolean m_IsPlayerComputer; private int m_PlayerID; //private Cell.Color m_Color; private int m_Color; private javafx.scene.paint.Color actualColor; private boolean isQuit; public static final Comparator<Player> scoreComparator = new MyComparator(); public int getScore(){return m_SumOfPoints;} @Override public Player clone() throws CloneNotSupportedException { return (Player)super.clone(); } static class MyComparator implements Comparator<Player>{ @Override public int compare(Player p1, Player p2) { if(p1.getScore() <= p2.getScore()){ return 1; } else { return -1; } } } public Player(int i_PlayerId, String i_PlayerName, String i_PlayerType, int i_Color/*Cell.Color i_Color*/) { m_PlayerID = i_PlayerId; m_PlayerName = i_PlayerName; String strComp = i_PlayerType.substring(0, 5); if (strComp.equals("Human")){ m_IsPlayerComputer = false; } else { m_IsPlayerComputer = true; } m_Color = i_Color; actualColor = Cell.getStatus(m_Color); isQuit = false; } public void setScore(int score){ m_SumOfPoints = 0; } public boolean getIsQuit(){ return isQuit; } public void setIsQuit(boolean value ){ isQuit = value; } public javafx.scene.paint.Color getActualColor(){return actualColor;} public Player() {} public void AddPoints(String num){ int newNum = Integer.parseInt(num); m_SumOfPoints += newNum; } public void AddPoints(int num){ m_SumOfPoints += num; } public void subtractPoints(int num){ m_SumOfPoints = m_SumOfPoints - num; } public int getID() { return m_PlayerID;} public boolean GetIsComputer() { return m_IsPlayerComputer; } public int GetNumOfPoints(){ return m_SumOfPoints; } public String GetPlayerName(){ return m_PlayerName; } public int /*Cell.Color*/ GetColor(){ return m_Color; } public String getColorName(){ switch (m_Color) { case 1: return "Blue"; case 2: return "Red"; case 3: return "Green"; case 4: return "White"; case 5: return "Black"; case 6: return "Purple"; default: return null; } } }
f338ffe28054c142feca0cf69f226711fc67d6eb
5a457df22c67668e6e95e513f5da49963af9ee7f
/main.java
cd106d0c0601edf6a52571e2d9f60b9e636d1148
[]
no_license
jack123abc4/nurikabe
b136d9cf48d99ea9927851258c64e8fd7a4865ee
64af993722bbc10385fa455c3889c837a6c9af86
refs/heads/main
2023-01-23T15:31:04.394576
2020-12-02T15:18:56
2020-12-02T15:18:56
317,902,531
0
0
null
null
null
null
UTF-8
Java
false
false
13,290
java
import java.util.ArrayList; class Main { public static void main(String[] args) { int SIZE = 5; int[][] numGrid = new int[SIZE][SIZE]; char[][] dotGrid = new char[SIZE][SIZE]; numGrid[1][0] = 2; numGrid[3][0] = 2; for (int r = 0; r < SIZE; r++) { for (int c = 0; c < SIZE; c++) { int n = numGrid[r][c]; if (n != 0) { n--; for (int roamY = 0 - n; roamY <= n; roamY++) { for (int roamX = 0 - (n - Math.abs(roamY)); roamX <= n - Math.abs(roamY); roamX++) { if (r + roamY >= 0 && r + roamY < SIZE && c + roamX >= 0 && c + roamX < SIZE) { boolean dotCheck = true; for (int dotCheckY = -1; dotCheckY <= 1; dotCheckY++) { for (int dotCheckX = -1; dotCheckX <= 1; dotCheckX++) { try { if (numGrid[r + roamY + dotCheckY][c + roamX + dotCheckX] != 0 || dotGrid[r + roamY + dotCheckY][c + roamX + dotCheckX] == '*') { dotCheck = false; } } catch (Exception e) { continue; } } } if (dotCheck = true) { dotGrid[r + roamY][c + roamX] = '*'; } } } } } } } int[][] numGridOne = {{ 0 , 0 , 0 , 0 , 0 }, { 2 , 0 , 1 , 0 , 0 }, { 0 , 2 , 0 , 4 , 0 }, { 0 , 0 , 0 , 0 , 0 }, { 0 , 0 , 0 , 0 , 7 }}; char[][] dotGridOne = {{'*', 0 , 0 , 0 ,'*'}, {'*', 0 ,'*', 0 ,'*'}, { 0 , 0 , 0 ,'*','*'}, {'*','*', 0 , 0 , 0 }, {'*','*','*','*','*'}}; //System.out.println(printGrid(numGridOne, dotGridOne)); //checkGrid(numGridOne, dotGridOne); Board b = new Board(5); b.intGrid[2][2] = 5; int[] newCoords = {2, 2}; Node n = new Node(null, newCoords); //System.out.println(b); ArrayList<Board> bList = searchTile(n, 5, b); for (int i = 0; i < bList.size(); i++) { System.out.println(bList.get(i)); } } public static String printGrid(int[][] iGrid, char[][] cGrid) { String s = " "; for (int i = 0; i < iGrid.length; i++) { if (i < 10) { s += " "; } s += Integer.toString(i); s += " "; } s += "\n"; for (int r = 0; r < iGrid.length; r++) { s += Integer.toString(r); if (r < 10) { s += " "; } for (int c = 0; c < iGrid.length; c++) { s += "["; if (cGrid[r][c] == 0) { s += " "; } else if (iGrid[r][c] != 0) { s += Integer.toString(iGrid[r][c]); } else { s += cGrid[r][c]; } s += "]"; } s += "\n"; } return s; } public static boolean checkGrid(int[][] iGrid, char[][] cGrid) { boolean valid = true; // check for 2x2s for (int r = 0; r < iGrid.length - 1; r++) { for (int c = 0; c < iGrid.length - 1; c++) { if (cGrid[r][c] == 0 && cGrid[r + 1][c] == 0 && cGrid[r][c + 1] == 0 && cGrid[r + 1][c + 1] == 0) { valid = false; System.out.println("2x2 Error - found at " + Integer.toString(c) + ", " + Integer.toString(r)); } } } // check for contiguity ArrayList<int[]> borderCoords = new ArrayList<int[]>(); for (int r = 0; r < iGrid.length; r++) { for (int c = 0; c < iGrid.length; c++) { if (cGrid[r][c] == 0) { int[] coords = { r, c }; borderCoords.add(coords); } } } Node root = new Node(null, borderCoords.get(1)); root.addToNodeList(root); search(root, cGrid); /* for (int i = 0; i < root.nodeList.size(); i++) { System.out.print(i+1); System.out.println(": " + root.nodeList.get(i)); } */ if (root.nodeList.size() != borderCoords.size()) { valid = false; System.out.println("Contiguity error."); } // valid? if (valid == true) { System.out.println("No errors, board is valid."); } return valid; } public static Node search(Node n, char[][] cGrid) { int r = n.coords[0]; int c = n.coords[1]; // check up if (r > 0 && cGrid[r - 1][c] == 0) { boolean isNewNode = true; int[] newCoords = { r - 1, c }; for (int i = 0; i < n.root.nodeList.size(); i++) { if (n.root.nodeList.get(i).coords[0] == newCoords[0] && n.root.nodeList.get(i).coords[1] == newCoords[1]) { isNewNode = false; } } if (isNewNode == true) { Node newNode = new Node(n, newCoords); n.root.addToNodeList(newNode); n.addChild(newNode, 'u'); search(newNode, cGrid); } } // check left if (c > 0 && cGrid[r][c-1] == 0) { boolean isNewNode = true; int[] newCoords = { r, c - 1 }; for (int i = 0; i < n.root.nodeList.size(); i++) { if (n.root.nodeList.get(i).coords[0] == newCoords[0] && n.root.nodeList.get(i).coords[1] == newCoords[1]) { isNewNode = false; } } if (isNewNode == true) { Node newNode = new Node(n, newCoords); n.root.addToNodeList(newNode); n.addChild(newNode, 'l'); search(newNode, cGrid); } } // check right if (c < cGrid.length-1 && cGrid[r][c+1] == 0) { boolean isNewNode = true; int[] newCoords = { r, c + 1 }; for (int i = 0; i < n.root.nodeList.size(); i++) { if (n.root.nodeList.get(i).coords[0] == newCoords[0] && n.root.nodeList.get(i).coords[1] == newCoords[1]) { isNewNode = false; } } if (isNewNode == true) { Node newNode = new Node(n, newCoords); n.root.addToNodeList(newNode); n.addChild(newNode, 'r'); search(newNode, cGrid); } } // check down if (r < cGrid.length-1 && cGrid[r+1][c] == 0) { boolean isNewNode = true; int[] newCoords = { r + 1, c }; for (int i = 0; i < n.root.nodeList.size(); i++) { if (n.root.nodeList.get(i).coords[0] == newCoords[0] && n.root.nodeList.get(i).coords[1] == newCoords[1]) { isNewNode = false; } } if (isNewNode == true) { Node newNode = new Node(n, newCoords); n.root.addToNodeList(newNode); n.addChild(newNode, 'r'); search(newNode, cGrid); } } return n; } public static ArrayList<Board> searchTile(Node n, int num, Board b) { ArrayList<Board> bList = new ArrayList<Board>(); if (num == 1) { bList.add(b); return bList; } int r = n.coords[0]; int c = n.coords[1]; // check up if (r > 0 && b.charGrid[r - 1][c] == 0) { int[] newCoords = { r - 1, c }; boolean isNewNode = true; Node parent = n; while (parent.parent != parent) { if (parent.parent.coords[0] == newCoords[0] && parent.parent.coords[1] == newCoords[1]) { isNewNode = false; } parent = parent.parent; } System.out.println(n); if (isNewNode == true) { Node newNode = new Node(n, newCoords); n.addChild(newNode, 'u'); Board newBoard = new Board(b.size); newBoard.setBoard(b.intGrid, b.charGrid); newBoard.charGrid[newCoords[0]][newCoords[1]] = '*'; //System.out.println("Searching... " + newNode); ArrayList<Board> newBoardList = searchTile(newNode, num-1, newBoard); for (int i = 0; i < newBoardList.size(); i++) { bList.add(newBoardList.get(i)); } } } // check left if (c > 0 && b.charGrid[r][c - 1] == 0) { int[] newCoords = { r, c - 1 }; boolean isNewNode = true; Node parent = n; while (parent.parent != parent) { if (parent.parent.coords[0] == newCoords[0] && parent.parent.coords[1] == newCoords[1]) { isNewNode = false; } parent = parent.parent; } System.out.println(n); if (isNewNode == true) { Node newNode = new Node(n, newCoords); n.addChild(newNode, 'l'); Board newBoard = new Board(b.size); newBoard.setBoard(b.intGrid, b.charGrid); newBoard.charGrid[newCoords[0]][newCoords[1]] = '*'; //System.out.println("Searching... " + newNode); ArrayList<Board> newBoardList = searchTile(newNode, num-1, newBoard); for (int i = 0; i < newBoardList.size(); i++) { bList.add(newBoardList.get(i)); } } } // check right if (c < b.size-1 && b.charGrid[r][c + 1] == 0) { int[] newCoords = { r, c + 1 }; boolean isNewNode = true; Node parent = n; while (parent.parent != parent) { if (parent.parent.coords[0] == newCoords[0] && parent.parent.coords[1] == newCoords[1]) { isNewNode = false; } parent = parent.parent; } System.out.println(n); if (isNewNode == true) { Node newNode = new Node(n, newCoords); n.addChild(newNode, 'r'); Board newBoard = new Board(b.size); newBoard.setBoard(b.intGrid, b.charGrid); newBoard.charGrid[newCoords[0]][newCoords[1]] = '*'; //System.out.println("Searching... " + newNode); ArrayList<Board> newBoardList = searchTile(newNode, num-1, newBoard); for (int i = 0; i < newBoardList.size(); i++) { bList.add(newBoardList.get(i)); } } } // check down if (r < b.size - 1 && b.charGrid[r + 1][c] == 0) { int[] newCoords = { r + 1, c }; boolean isNewNode = true; Node parent = n; while (parent.parent != parent) { if (parent.parent.coords[0] == newCoords[0] && parent.parent.coords[1] == newCoords[1]) { isNewNode = false; } parent = parent.parent; } System.out.println(n); if (isNewNode == true) { Node newNode = new Node(n, newCoords); n.addChild(newNode, 'd'); Board newBoard = new Board(b.size); newBoard.setBoard(b.intGrid, b.charGrid); newBoard.charGrid[newCoords[0]][newCoords[1]] = '*'; //System.out.println("Searching... " + newNode); ArrayList<Board> newBoardList = searchTile(newNode, num-1, newBoard); for (int i = 0; i < newBoardList.size(); i++) { bList.add(newBoardList.get(i)); } } } return bList; } }
bc3236d840737b7d318b188ddabcfc32de9ef05f
31ccb3b9cb7c4ba78b8e85111d9f84a1f9692203
/src/test/java/com/thoughtworks/twars/page/ConsolePage.java
b81d1f90a076e4e9f958db9c05ffbe5d4a6600c8
[]
no_license
afaren-graduation-design/automated-test
62ad1fe6340dd47dacfe03fb6f5b583f1e3ef9e6
d369a664c05b5449a5c8592dea764bd27bacb314
refs/heads/master
2021-01-22T21:38:27.883660
2017-05-20T07:51:26
2017-05-20T07:51:26
85,457,976
1
0
null
null
null
null
UTF-8
Java
false
false
941
java
package com.thoughtworks.twars.page; import org.concordion.selenium.Browser; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; /** * Created by afaren on 12/20/16. */ public class ConsolePage extends Page { @CacheLookup @FindBy(linkText = "逻辑题") private WebElement logicPuzzle; @CacheLookup @FindBy(linkText = "编程题") private WebElement homeworkQuiz; public ConsolePage(Browser browser) { super(browser); } @Override protected By condition() { return By.className("dashboard-icon"); } public LogicPuzzlePage clickLogicPuzzle() { logicPuzzle.click(); return new LogicPuzzlePage(browser); } public HomeworkQuizPage clickHomeworkQuiz() { homeworkQuiz.click(); return new HomeworkQuizPage(browser); } }
7cfee453a369e8aad393a0d3f323d2277766cbad
f047107b3a0307251be53806de7fc0a5902a39f3
/app/src/main/java/com/messi/languagehelper/StudyFragment.java
74d920abc620bd437df49b9f5c8cd6340339684c
[]
no_license
hongsyang/languagehelper_new
23ebfff38218e23e8a1a863329d528a7a422e203
10e82f36e895fbef006805f183fbc7efb257e88a
refs/heads/master
2021-03-12T09:37:03.890399
2020-03-08T02:30:18
2020-03-08T02:30:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
15,172
java
package com.messi.languagehelper; import android.content.Context; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.avos.avoscloud.AVException; import com.avos.avoscloud.AVObject; import com.avos.avoscloud.AVQuery; import com.avos.avoscloud.FindCallback; import com.iflytek.voiceads.conn.NativeDataRef; import com.messi.languagehelper.ViewModel.XXLModel; import com.messi.languagehelper.adapter.RcStudyListAdapter; import com.messi.languagehelper.bean.ReadingCategory; import com.messi.languagehelper.box.BoxHelper; import com.messi.languagehelper.box.Reading; import com.messi.languagehelper.impl.FragmentProgressbarListener; import com.messi.languagehelper.impl.TablayoutOnSelectedListener; import com.messi.languagehelper.service.PlayerService; import com.messi.languagehelper.util.AVAnalytics; import com.messi.languagehelper.util.AVOUtil; import com.messi.languagehelper.util.DataUtil; import com.messi.languagehelper.util.LogUtil; import com.messi.languagehelper.util.Setings; import com.messi.languagehelper.util.ToastUtil; import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class StudyFragment extends BaseFragment implements TablayoutOnSelectedListener { @BindView(R.id.listview) RecyclerView listview; @BindView(R.id.tablayout) TabLayout tablayout; @BindView(R.id.search_btn) FrameLayout searchBtn; private int maxVideo = 20000; private RcStudyListAdapter mAdapter; private List<Reading> avObjects; private List<AVObject> tempList; private int skip = 0; private int maxRandom = 3000; private String category; private LinearLayoutManager mLinearLayoutManager; private List<ReadingCategory> categories; private boolean isNeedClear = true; private Reading xvideoItem; private XXLModel mXXLModel; public static StudyFragment getInstance() { return new StudyFragment(); } @Override public void onAttach(Context activity) { super.onAttach(activity); try { registerBroadcast(); mProgressbarListener = (FragmentProgressbarListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement FragmentProgressbarListener"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.study_fragment, null); ButterKnife.bind(this, view); initSwipeRefresh(view); initViews(view); loadData(); getMaxPageNumberBackground(); return view; } private void initViews(View view) { avObjects = new ArrayList<Reading>(); mAdapter = new RcStudyListAdapter(avObjects); mXXLModel = new XXLModel(getActivity()); avObjects.addAll(BoxHelper.getReadingList(0,Setings.page_size, "", "", "")); mXXLModel.setAdapter(avObjects,mAdapter); mAdapter.setItems(avObjects); mAdapter.setFooter(new Object()); hideFooterview(); skip = 0; mLinearLayoutManager = new LinearLayoutManager(getContext()); listview.setLayoutManager(mLinearLayoutManager); listview.addItemDecoration( new HorizontalDividerItemDecoration.Builder(getContext()) .colorResId(R.color.text_tint) .sizeResId(R.dimen.list_divider_size) .marginResId(R.dimen.padding_2, R.dimen.padding_2) .build()); listview.setAdapter(mAdapter); setListOnScrollListener(); categories = getTabItem(getContext()); initTablayout(); } private void initTablayout() { for (ReadingCategory item : categories) { tablayout.addTab(tablayout.newTab().setText(item.getName())); } tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { onTabSelectedListener(categories.get(tab.getPosition())); } @Override public void onTabReselected(TabLayout.Tab tab) { onTabReselectedListener(categories.get(tab.getPosition())); } @Override public void onTabUnselected(TabLayout.Tab tab) { } }); } private void random() { skip = (int) Math.round(Math.random() * maxRandom); } public void setListOnScrollListener() { listview.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int visible = mLinearLayoutManager.getChildCount(); int total = mLinearLayoutManager.getItemCount(); int firstVisibleItem = mLinearLayoutManager.findFirstCompletelyVisibleItemPosition(); isADInList(recyclerView, firstVisibleItem, visible); if (!mXXLModel.loading && mXXLModel.hasMore) { if ((visible + firstVisibleItem) >= total) { QueryTask(); } } } }); } private void isADInList(RecyclerView view, int first, int vCount) { try { if (avObjects.size() > 2) { for (int i = first; i < (first + vCount); i++) { if (i < avObjects.size() && i > 0) { Reading mAVObject = avObjects.get(i); if (mAVObject != null && mAVObject.isAd()) { if (!mAVObject.isAdShow() && mAVObject.getmNativeADDataRef() != null) { NativeDataRef mNativeADDataRef = mAVObject.getmNativeADDataRef(); boolean isExposure = mNativeADDataRef.onExposure(view.getChildAt(i % vCount)); LogUtil.DefalutLog("isExposure:" + isExposure); if(isExposure){ mAVObject.setAdShow(isExposure); } } } } } } } catch (Exception e) { e.printStackTrace(); } } @Override public void updateUI(String music_action) { if (music_action.equals(PlayerService.action_loading)) { showProgressbar(); } else if (music_action.equals(PlayerService.action_finish_loading)) { hideProgressbar(); } else { mAdapter.notifyDataSetChanged(); } } @Override public void onResume() { super.onResume(); if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } public void loadData() { skip = 0; QueryTask(); // XVideoAsyncTask(); } @Override public void onSwipeRefreshLayoutRefresh() { isNeedClear = true; random(); refresh(); } private void refresh() { hideFooterview(); QueryTask(); // XVideoAsyncTask(); } private void loadAD(){ if (mXXLModel != null) { mXXLModel.showAd(); } } private void QueryTask() { mXXLModel.loading = true; showProgressbar(); Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(ObservableEmitter<String> e) throws Exception { getNetworkData(); e.onComplete(); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<String>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(String s) { } @Override public void onError(Throwable e) { } @Override public void onComplete() { onFinishLoadData(); } }); } private void getNetworkData() { AVQuery<AVObject> query = new AVQuery<AVObject>(AVOUtil.Reading.Reading); if(!TextUtils.isEmpty(category)) { if(category.equals("video")) { query.whereEqualTo(AVOUtil.Reading.type, "video"); skip = (int) Math.round(Math.random() * maxVideo); }else { query.whereEqualTo(AVOUtil.Reading.category, category); } }else { query.whereNotEqualTo(AVOUtil.Reading.type, "video"); } query.addDescendingOrder(AVOUtil.Reading.publish_time); query.skip(skip); query.limit(Setings.page_size); try { tempList = query.find(); LogUtil.DefalutLog("skip:" + skip); } catch (Exception e) { e.printStackTrace(); } } private void onFinishLoadData() { mXXLModel.loading = false; mXXLModel.hasMore = true; hideProgressbar(); onSwipeRefreshLayoutFinish(); if (tempList != null) { if (tempList.size() == 0) { ToastUtil.diaplayMesShort(getContext(), "没有了!"); hideFooterview(); mXXLModel.hasMore = false; } else { if (avObjects != null && mAdapter != null) { if (isNeedClear || skip == 0) { isNeedClear = false; avObjects.clear(); } loadAD(); DataUtil.changeDataToReading(tempList, avObjects,false); // if(xvideoItem != null){ // if(avObjects.size() > 9){ // avObjects.add(NumberUtil.randomNumberRange(3,6),xvideoItem); // }else { // avObjects.add(0,xvideoItem); // } // xvideoItem = null; // } mAdapter.notifyDataSetChanged(); skip += Setings.page_size; showFooterview(); } } } } @Override public void onTabSelectedListener(ReadingCategory mReadingCategory) { isNeedClear = true; listview.scrollToPosition(0); category = mReadingCategory.getCategory(); skip = 0; refresh(); } @Override public void onTabReselectedListener(ReadingCategory mReadingCategory) { listview.scrollToPosition(0); onSwipeRefreshLayoutRefresh(); } private void hideFooterview() { mAdapter.hideFooter(); } private void showFooterview() { mAdapter.showFooter(); } public void onTabReselected(int index) { listview.scrollToPosition(0); onSwipeRefreshLayoutRefresh(); } public static List<ReadingCategory> getTabItem(Context context) { List<ReadingCategory> readingCategories = new ArrayList<ReadingCategory>(); readingCategories.add(new ReadingCategory(context.getString(R.string.recommend), "")); readingCategories.add(new ReadingCategory(context.getString(R.string.title_english_video), "video")); readingCategories.add(new ReadingCategory(context.getString(R.string.title_listening), "listening")); readingCategories.add(new ReadingCategory(context.getString(R.string.spoken_english_practice), "spoken_english")); readingCategories.add(new ReadingCategory(context.getString(R.string.reading), "shuangyu_reading")); readingCategories.add(new ReadingCategory(context.getString(R.string.title_word_study_vocabulary), "word")); readingCategories.add(new ReadingCategory(context.getString(R.string.title_composition), "composition")); readingCategories.add(new ReadingCategory(context.getString(R.string.examination), "examination")); readingCategories.add(new ReadingCategory(context.getString(R.string.title_english_story), "story")); readingCategories.add(new ReadingCategory(context.getString(R.string.title_english_jokes), "jokes")); return readingCategories; } @OnClick(R.id.search_btn) public void onViewClicked() { toActivity(SearchActivity.class,null); AVAnalytics.onEvent(getContext(), "tab4_to_search"); } @Override public void onDestroy() { super.onDestroy(); unregisterBroadcast(); if(mXXLModel != null){ mXXLModel.onDestroy(); } } private void XVideoAsyncTask() { // getXVideoAsyncTask(); } private void getXVideoAsyncTask(){ int random = (int) Math.round(Math.random() * 6000); AVQuery<AVObject> query = new AVQuery<AVObject>(AVOUtil.XVideo.XVideo); query.whereEqualTo(AVOUtil.XVideo.category,"english"); query.orderByDescending(AVOUtil.XVideo.play_count); query.skip(random); query.limit(6); query.findInBackground(new FindCallback<AVObject>() { @Override public void done(List<AVObject> list, AVException e) { if(list != null){ xvideoItem = new Reading(); xvideoItem.setXvideoList(list); } } }); } private void getMaxPageNumberBackground(){ new Thread(new Runnable() { @Override public void run() { try { AVQuery<AVObject> query = new AVQuery<AVObject>(AVOUtil.Reading.Reading); query.whereEqualTo(AVOUtil.Reading.type, "video"); query.addDescendingOrder(AVOUtil.Reading.publish_time); maxVideo = query.count()-300; LogUtil.DefalutLog("maxVideo:"+maxVideo); } catch (Exception e) { e.printStackTrace(); } } }).start(); } }
16b883bfa382245083da32df1ef6f925bcf7974b
4da94e36f8ab4f22051d848ebbc598efa0ae419c
/MPP/Tema3XML/src/test/java/repository/UserRepositoryTest.java
02332a2bdaba0837bcefc57bccdd59d49a7b5615
[]
no_license
lorak127/University-Courses
6ccf52e77a2ab51e43f747f0a2a124b38c81549a
79908d4142db9e4d7c2ecc1c8f807bb372ae166e
refs/heads/master
2023-04-03T20:43:14.107167
2020-12-30T10:09:31
2020-12-30T10:09:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,492
java
package repository; import model.TipUser; import model.User; import org.junit.Test; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class UserRepositoryTest { @Test public void test(){ Properties prop=new Properties(); try { prop.load(new FileReader("D:\\University-Courses\\MPP\\Laborator1\\src\\test\\resources\\bd.properties")); } catch (IOException e) { e.printStackTrace(); } IRepository<String, User> repo=new UserRepository(prop); User user=new User("ioana_l","hashhash"); //size assertEquals(2,repo.size()); //save repo.save(user); assertEquals(3,repo.size()); //find assertNull(repo.findOne("teofana")); assertEquals(user,repo.findOne("ioana_l")); //update user.setTip(TipUser.OPERATOR); repo.update("ioana_l",new User("ioana_l","hashhash", TipUser.OPERATOR)); List<User> lista= StreamSupport.stream(repo.findAll().spliterator(),false) .collect(Collectors.toList()); User lastUser=lista.get(lista.size()-1); assertEquals(user,lastUser); //delete repo.delete("ioana_l"); assertEquals(2,repo.size()); } }
c1fcd0e6d46ffca366cee3b209fd9729b756e97e
131a9eab654d21e1a9fc727aef15f1242b0e56be
/jstarcraft-ai-math/src/main/java/com/jstarcraft/ai/math/structure/vector/DenseVector.java
2794fbf9d60fcceb17712fb0887d68925b97ca29
[ "Apache-2.0" ]
permissive
lamlink/jstarcraft-ai
d13dd10b516d261ec42287ead72106e767610fd7
ac34fdfd9e20f1147280639b95e80e36a486b4ba
refs/heads/master
2020-07-28T05:29:33.055518
2019-09-18T12:37:36
2019-09-18T12:37:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,881
java
package com.jstarcraft.ai.math.structure.vector; import java.util.Iterator; import java.util.concurrent.Semaphore; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.math3.util.FastMath; import com.jstarcraft.ai.environment.EnvironmentContext; import com.jstarcraft.ai.math.structure.MathAccessor; import com.jstarcraft.ai.math.structure.MathCalculator; import com.jstarcraft.ai.math.structure.ScalarIterator; /** * 稠密向量 * * @author Birdy * */ public class DenseVector implements MathVector { /** 游标 */ private int cursor; /** 偏移量 */ private int delta; /** 大小 */ private int size; /** 数据 */ private float[] values; public DenseVector(float[] data, int cursor, int delta, int size) { this.values = data; this.cursor = cursor; this.delta = delta; this.size = size; } @Override public int getElementSize() { return size; } @Override public int getKnownSize() { return getElementSize(); } @Override public int getUnknownSize() { return 0; } @Override public ScalarIterator<VectorScalar> iterateElement(MathCalculator mode, MathAccessor<VectorScalar>... accessors) { switch (mode) { case SERIAL: { DenseVectorScalar scalar = new DenseVectorScalar(); for (int index = 0; index < size; index++) { int position = cursor + index * delta; scalar.update(position, index); for (MathAccessor<VectorScalar> accessor : accessors) { accessor.accessElement(scalar); } } return this; } default: { EnvironmentContext context = EnvironmentContext.getContext(); Semaphore semaphore = MathCalculator.getSemaphore(); for (int index = 0; index < size; index++) { int elementIndex = index; int position = cursor + index * delta; context.doStructureByAny(position, () -> { DenseVectorScalar scalar = new DenseVectorScalar(); scalar.update(position, elementIndex); for (MathAccessor<VectorScalar> accessor : accessors) { accessor.accessElement(scalar); } semaphore.release(); }); } try { semaphore.acquire(size); } catch (Exception exception) { throw new RuntimeException(exception); } return this; } } } @Override public DenseVector setValues(float value) { for (int index = 0; index < size; index++) { int position = cursor + index * delta; values[position] = value; } return this; } @Override public DenseVector scaleValues(float value) { for (int index = 0; index < size; index++) { int position = cursor + index * delta; values[position] *= value; } return this; } @Override public DenseVector shiftValues(float value) { for (int index = 0; index < size; index++) { int position = cursor + index * delta; values[position] += value; } return this; } @Override public float getSum(boolean absolute) { float sum = 0F; if (absolute) { for (int index = 0; index < size; index++) { sum += FastMath.abs(values[cursor + index * delta]); } } else { for (int index = 0; index < size; index++) { sum += values[cursor + index * delta]; } } return sum; } @Override public boolean isConstant() { return true; } @Override public int getIndex(int position) { return position; } @Override public float getValue(int position) { return values[cursor + position * delta]; } @Override public void setValue(int position, float value) { values[cursor + position * delta] = value; } @Override public void scaleValue(int position, float value) { values[cursor + position * delta] *= value; } @Override public void shiftValue(int position, float value) { values[cursor + position * delta] += value; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null) return false; if (getClass() != object.getClass()) return false; DenseVector that = (DenseVector) object; EqualsBuilder equal = new EqualsBuilder(); equal.append(this.values, that.values); return equal.isEquals(); } @Override public int hashCode() { HashCodeBuilder hash = new HashCodeBuilder(); hash.append(values); return hash.toHashCode(); } @Override public String toString() { StringBuilder buffer = new StringBuilder(); for (int index = 0; index < size; index++) { buffer.append(getValue(index)).append(", "); } buffer.append("\n"); return buffer.toString(); } @Override public Iterator<VectorScalar> iterator() { return new DenseVectorIterator(); } /** * Iterator over a sparse vector */ private class DenseVectorIterator implements Iterator<VectorScalar> { private int index; private final DenseVectorScalar term = new DenseVectorScalar(); @Override public boolean hasNext() { return index < size; } @Override public VectorScalar next() { term.update(cursor + index * delta, index++); return term; } @Override public void remove() { throw new UnsupportedOperationException(); } } private class DenseVectorScalar implements VectorScalar { private int index; private int cursor; private void update(int cursor, int index) { this.cursor = cursor; this.index = index; } @Override public int getIndex() { return index; } @Override public float getValue() { return values[cursor]; } @Override public void scaleValue(float value) { values[cursor] *= value; } @Override public void setValue(float value) { values[cursor] = value; } @Override public void shiftValue(float value) { values[cursor] += value; } } public static DenseVector copyOf(DenseVector vector) { float[] values = new float[vector.size]; for (int index = 0, size = vector.size; index < size; index++) { values[index] = vector.getValue(index); } DenseVector instance = new DenseVector(values, 0, 1, vector.size); return instance; } public static DenseVector valueOf(int size) { DenseVector instance = new DenseVector(new float[size], 0, 1, size); return instance; } public static DenseVector valueOf(int size, float[] data) { DenseVector instance = new DenseVector(data, 0, 1, size); return instance; } }
[ "Birdy@LAPTOP-QRG8T75T" ]
Birdy@LAPTOP-QRG8T75T
81d80bea2f9727c593eb0a406a7f90608c9a7813
38018953496da0c0578f4d843e0c890fd1c81d9d
/src/NotificationDetails.java
e4cb5a056df9a9b3fdc23af601d2193afc687967
[]
no_license
suyogmirgal/factory-java-design-pattern
7b5d4f953ec269c1e5d4c2e5a8f3db7432ef14b9
a96219e7fa9e378d98bfef1c9ce6d8ed1b23c2b0
refs/heads/master
2023-02-25T14:13:18.996361
2021-01-20T14:33:44
2021-01-20T14:33:44
331,201,784
0
0
null
null
null
null
UTF-8
Java
false
false
188
java
public class NotificationDetails { String user; String message; public NotificationDetails(String user, String message) { this.user = user; this.message = message; } }
9128646e225551a2128af38a96bcb1b0f8797efa
09c7aec300537d7b286c3497312de304473b3f48
/app/src/main/java/com/supergeek/junejaspc/nqueens/ChessBoard.java
9eddde3fc78fd0d78ebf3a3e5f364856aa8d8292
[]
no_license
shubhamjuneja11/Queen
92c8d660cf1b550b4989a2ac5848370659b81bc5
29de70b3fbe85e948ae5cdde085a252cb74515d5
refs/heads/master
2021-06-26T05:46:54.357891
2017-09-08T20:35:48
2017-09-08T20:35:48
84,084,117
0
0
null
null
null
null
UTF-8
Java
false
false
27,538
java
package com.supergeek.junejaspc.nqueens; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v4.app.LoaderManager; import android.support.v4.app.NavUtils; import android.support.v4.app.TaskStackBuilder; import android.support.v4.content.Loader; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.DisplayMetrics; import android.view.View; import android.widget.EditText; import android.widget.GridLayout; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import static com.supergeek.junejaspc.nqueens.LoaderForSubmit.readfromstream; public class ChessBoard extends AppCompatActivity implements View.OnClickListener, LoaderManager.LoaderCallbacks<LeaderBoard_row> { GridLayout gridLayout; ImageButton button_set[][]; AlertDialog.Builder builder; InterstitialAd mInterstitialAd; int i, height, width, totalbuttons, rowlimit, j, total_queens,addcount,backcount; boolean decide,game_started; TextView time; DisplayMetrics displayMetrics; boolean buttons_state[][],done; Runnable startTimer; AlertDialog dialog; boolean saved; View view2; GradientDrawable shapeDrawable, shape2, shape3; public static String colors[] = new String[]{"#7333BF", "#CB2A62", "#A8AD1F", "#D34B20", "#649035", "#359053", "#31B0AF", "#2C65A9", "#13EBE8", "#969734", "#85CBFE", "#F7B7C9", "#FF8181","#E68DFC", "#B1B1B6", "#D18CFE", "#D0D2D4", "#C797F4", "#13EBE8", "#A4FEFF", "#FAB182", "#FDA9BF"}; private String user_name, mytime,savedgame; int mylevel,avatar=0; private final int REFRESH_RATE = 100; private String hours, minutes, seconds, milliseconds; private long secs, mins, hrs; private long elapsedTime, startTime; private Handler mHandler = new Handler(); SharedPreferences sharedPreferences; public static String savecompleted="complete"; public static String savemilli="milli",response; private long savedtime; SharedPreferences.Editor editor; private String url; private URL myurl; ProgressBar progress; private AdView mAdView,mAdView2; @Override protected void onPause() { super.onPause(); stop_tick_tock(); editor.putLong("temptime",elapsedTime); editor.apply(); if (mAdView != null) { mAdView.pause(); } if (mAdView2 != null) { mAdView2.pause(); } //game_started=false; } @Override protected void onResume() { try { super.onResume(); if (mAdView != null) { mAdView.resume(); } if (mAdView2 != null) { mAdView2.resume(); } if(game_started) { if(dialog==null) { builder = new AlertDialog.Builder(this); View view = getLayoutInflater().inflate(R.layout.newdialog, null); builder.setView(view); dialog = builder.create(); dialog.setCancelable(false); dialog.show(); } savedtime=sharedPreferences.getLong("temptime",savedtime); } } catch (Exception e){} } public void startgame(View view){ dialog.dismiss(); dialog=null; tick_tock(); game_started=true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chess_board); url="http://geekyboy.16mb.com/saveusername.php"; getSupportActionBar().setTitle("ChessBoard"); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setHomeButtonEnabled(false); // disable the button actionBar.setDisplayHomeAsUpEnabled(false); // remove the left caret actionBar.setDisplayShowHomeEnabled(false); // remove the icon } sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this); editor =sharedPreferences.edit(); game_started=true; addcount=sharedPreferences.getInt("addcount",0); try { myurl=new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } rowlimit = getIntent().getIntExtra("count", 4); //savedtime=0; saved = getIntent().getBooleanExtra("saved", false); if(saved) savedtime=sharedPreferences.getLong(colors[rowlimit-4]+savemilli,0); time = (TextView) findViewById(R.id.mytime); shapeDrawable = new GradientDrawable(); shapeDrawable.setStroke(1, getResources().getColor(R.color.black)); shapeDrawable.setColor(Color.parseColor(colors[rowlimit - 4])); shape2 = new GradientDrawable(); shape3 = new GradientDrawable(); shape2.setStroke(1, getResources().getColor(R.color.black)); shape2.setColor(Color.parseColor("#FFFFFF")); shape3.setStroke(1, getResources().getColor(R.color.black)); shape3.setColor(Color.parseColor("#FF0000")); gridLayout = (GridLayout) findViewById(R.id.grid); displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); decide = true; total_queens = 0; buttons_state = new boolean[rowlimit][rowlimit]; /*****************************************************************************************/ mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .build(); mAdView.loadAd(adRequest); mAdView2 = (AdView) findViewById(R.id.adView2); AdRequest adRequest2 = new AdRequest.Builder() .build(); mAdView2.loadAd(adRequest2); /********************************************************************************************/ decideFactor(); boardsetup(); } public void decideFactor() { totalbuttons = rowlimit * rowlimit; height = displayMetrics.heightPixels / rowlimit; width = displayMetrics.widthPixels / rowlimit; gridLayout.setRowCount(rowlimit); gridLayout.setColumnCount(rowlimit); } public void boardsetup() { button_set = new ImageButton[rowlimit][rowlimit]; for (i = 0; i < rowlimit; i++) { for (j = 0; j < rowlimit; j++) { button_set[i][j] = new ImageButton(this); button_set[i][j].setScaleType(ImageView.ScaleType.CENTER_CROP); button_set[i][j].setLayoutParams(new LinearLayout.LayoutParams(width, width)); if (decide) { button_set[i][j].setBackgroundDrawable(shapeDrawable); } else { button_set[i][j].setBackgroundDrawable(shape2); } decide = !decide; gridLayout.addView(button_set[i][j]); button_set[i][j].setOnClickListener(this); } if (rowlimit % 2 == 0) decide = !decide; } if(saved) checksavedgame(); } public void checksavedgame(){ savedgame=sharedPreferences.getString(colors[rowlimit-4],"1"); if(!savedgame.equals("1")) resumegame(); } public void resumegame(){ try { int k = 0; char c[] = savedgame.toCharArray(); for (int a = 0; a < rowlimit; a++) { for (int b = 0; b < rowlimit; b++) { if (c[k++] == '1') { buttons_state[a][b] = true; resumeonClick(button_set[a][b]); } else buttons_state[a][b] = false; } } total_queens=sharedPreferences.getInt(colors[rowlimit-4]+"queen",0); } catch (Exception e) { } } @Override public void onClick(View v) { for (i = 0; i < rowlimit; i++) for (j = 0; j < rowlimit; j++) if (button_set[i][j] == v) { decideButtonStatus(i,j,v); } } public void resumeonClick(View v){ for (i = 0; i < rowlimit; i++) for (j = 0; j < rowlimit; j++) if (button_set[i][j] == v) { resumedecidebuttonstatus(i,j,v); } } public void resumedecidebuttonstatus(int i,int j,View v){ if (!buttons_state[i][j]) { if (i % 2 == 0 && j % 2 == 0 || i % 2 != 0 && j % 2 != 0) { v.setBackgroundDrawable(shapeDrawable); } else {v.setBackgroundDrawable(shape2); } ((ImageButton) v).setImageResource(0); total_queens--; //buttons_state[i][j] = !buttons_state[i][j]; check_status(i, j); } else { if (total_queens < rowlimit) { total_queens++; ((ImageButton) v).setImageResource(R.drawable.queen); ((ImageButton) v).setScaleType(ImageView.ScaleType.CENTER_CROP); // buttons_state[i][j] = !buttons_state[i][j]; check_status(i, j); if (total_queens == rowlimit) check_completed(); } } } public void decideButtonStatus(int i,int j,View v){ if (buttons_state[i][j]) { if (i % 2 == 0 && j % 2 == 0 || i % 2 != 0 && j % 2 != 0) { v.setBackgroundDrawable(shapeDrawable); } else {v.setBackgroundDrawable(shape2); } ((ImageButton) v).setImageResource(0); total_queens--; buttons_state[i][j] = !buttons_state[i][j]; check_status(i, j); } else { if (total_queens < rowlimit) { total_queens++; ((ImageButton) v).setImageResource(R.drawable.queen); buttons_state[i][j] = !buttons_state[i][j]; check_status(i, j); if (total_queens == rowlimit) check_completed(); } } } public void check_status(int m, int n) { int i, j; for (i = 0; i < rowlimit; i++) { for (j = 0; j < rowlimit; j++) { if (buttons_state[i][j]) { if (!mark_status(i, j)) { button_set[i][j].setBackgroundDrawable(shape3); } else { if (i % 2 == 0 && j % 2 == 0 || i % 2 != 0 && j % 2 != 0) button_set[i][j].setBackgroundDrawable(shapeDrawable); else button_set[i][j].setBackgroundDrawable(shape2); } } } } } public boolean mark_status(int m, int n) { int i, j; //vertically for (i = 0; i < rowlimit; i++) { if (buttons_state[i][n] && i != m) { return false; } } //horizontally for (i = 0; i < rowlimit; i++) { if (buttons_state[m][i] && i != n) { return false; } } for (i = m, j = n; i < rowlimit && j < rowlimit; i++, j++) { if (buttons_state[i][j] && (i != m && j != n)) { return false; } } for (i = m, j = n; i >= 0 && j >= 0; i--, j--) { if (buttons_state[i][j] && (i != m && j != n)) { return false; } } for (i = m, j = n; i < rowlimit && j >= 0; i++, j--) { if (buttons_state[i][j] && (i != m && j != n)) { return false; } } for (i = m, j = n; i >= 0 && j < rowlimit; i--, j++) { if (buttons_state[i][j] && (i != m && j != n)) { return false; } } return true; } public boolean check_completed() { String s=""; for(i=0;i<rowlimit;i++) for(j=0;j<rowlimit;j++) if(buttons_state[i][j])s+="1"; else s+="0"; boolean flag = true; int i, j; outerloop: for (i = 0; i < rowlimit; i++) { for (j = 0; j < rowlimit; j++) { if (buttons_state[i][j]) if (!mark_status(i, j)) { return false; /*flag = false; break outerloop;*/ } else { } } } if (flag) { stop_tick_tock(); editor.putBoolean(colors[rowlimit-4]+savecompleted,true); editor.apply(); AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = getLayoutInflater().inflate(R.layout.congrats_dialog, null); TextView tv1, tv2; tv1 = (TextView) view.findViewById(R.id.complete_time); tv2 = (TextView) findViewById(R.id.mytime); tv1.setText(tv2.getText().toString()); builder.setView(view); dialog = builder.create(); dialog.setCancelable(false); dialog.show(); game_started=false; if(addcount%2==0) { mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-5750055305709604/4691384174"); AdRequest adRequest = new AdRequest.Builder() .build(); // Load ads into Interstitial Ads mInterstitialAd.loadAd(adRequest); mInterstitialAd.setAdListener(new AdListener() { public void onAdLoaded() { showInterstitial(); } }); } addcount++; editor.putInt("addcount",addcount); editor.apply(); return true; } return false; } private void showInterstitial() { if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } } public void tick_tock() { try { elapsedTime = 0; startTime = System.currentTimeMillis(); startTimer = new Runnable() { public void run() { elapsedTime = System.currentTimeMillis() - startTime+savedtime; updateTimer(elapsedTime); mHandler.postDelayed(this, REFRESH_RATE); } }; startTimer.run(); } catch (Exception e) { e.printStackTrace(); } } public void stop_tick_tock() { mHandler.removeCallbacks(startTimer); } private void updateTimer(float time) { secs = (long) (time / 1000); mins = (long) ((time / 1000) / 60); hrs = (long) (((time / 1000) / 60) / 60); /* Convert the seconds to String * and format to ensure it has * a leading zero when required */ secs = secs % 60; seconds = String.valueOf(secs); if (secs == 0) { seconds = "00"; } if (secs < 10 && secs > 0) { seconds = "0" + seconds; } /* Convert the minutes to String and format the String */ mins = mins % 60; minutes = String.valueOf(mins); if (mins == 0) { minutes = "00"; } if (mins < 10 && mins > 0) { minutes = "0" + minutes; } /* Convert the hours to String and format the String */ hours = String.valueOf(hrs); if (hrs == 0) { hours = "00"; } if (hrs < 10 && hrs > 0) { hours = "0" + hours; } milliseconds = String.valueOf((long) time); if (milliseconds.length() == 2) { milliseconds = "0" + milliseconds; } if (milliseconds.length() <= 1) { milliseconds = "00"; } if (milliseconds.length() >= 3) milliseconds = milliseconds.substring(milliseconds.length() - 3, milliseconds.length() - 1); this.time.setText(hours + ":" + minutes + ":" + seconds + "." + milliseconds); } public void mynewgame(View view) { try { Intent intent = getIntent(); intent.putExtra("count", rowlimit); intent.putExtra("saved", false); elapsedTime=0; editor.putInt("temptime",0); editor.apply(); startActivity(intent); finish(); } catch (Exception e){} } public void anotherlevel(View view) { Intent intent = new Intent(this, LevelActivity.class); startActivity(intent); finish(); } public void onleaderboard(View view) { dialog.dismiss(); dialog=null; if(check_user()) { putandgo(); } } public void putandgo(){ putonBoard(); Intent intent=new Intent(ChessBoard.this,LeaderBoardActivity.class); intent.putExtra("level",rowlimit-3); startActivity(intent); } public void back(View view){ goback(); } public void goback(){ game_started=false; try { if(dialog!=null) dialog.dismiss(); dialog=null; Intent upIntent=NavUtils.getParentActivityIntent(this);; if (NavUtils.shouldUpRecreateTask(this, upIntent)) { TaskStackBuilder.create(this) .addNextIntentWithParentStack(upIntent) .startActivities(); } else { NavUtils.navigateUpTo(this, upIntent); } } catch (Exception e) { } } @Override public void onBackPressed() { backcount=sharedPreferences.getInt("backcount",1); if(backcount%9==0){ mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-5750055305709604/4691384174"); AdRequest adRequest = new AdRequest.Builder() .build(); // Load ads into Interstitial Ads mInterstitialAd.loadAd(adRequest); mInterstitialAd.setAdListener(new AdListener() { public void onAdLoaded() { showInterstitial(); } }); } editor.putInt("backcount",backcount+1); editor.apply(); stop_tick_tock(); game_started=false; if(!(total_queens==rowlimit&&check_completed())) { AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = getLayoutInflater().inflate(R.layout.dialog, null); builder.setView(view); dialog = builder.create(); dialog.setCancelable(false); dialog.show(); } else { dialog.dismiss(); dialog=null; goback(); // super.onBackPressed(); } } public void yessave(View view) { dialog.dismiss(); dialog=null; int y,z; String s=""; for(y=0;y<rowlimit;y++){ for(z=0;z<rowlimit;z++){ if(buttons_state[y][z])s+='1'; else s+='0'; } } LevelActivity.decide[rowlimit-3]=true; editor.putString(colors[rowlimit-4],s); editor.putInt(colors[rowlimit-4]+"queen",total_queens); editor.putBoolean(String.valueOf(rowlimit-3),true); editor.putLong(colors[rowlimit-4]+savemilli,elapsedTime); editor.apply(); game_started=false; super.onBackPressed(); } public void nosave(View view) { dialog.dismiss(); dialog=null; game_started=false; super.onBackPressed(); } public void putonBoard() { game_started=false; mytime = time.getText().toString(); mylevel = rowlimit-3; senddata(); } public void senddata(){ ConnectivityManager connectivity=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo network=connectivity.getActiveNetworkInfo(); if(network!=null&&network.isConnected()) { try { LoaderManager loaderManager = getSupportLoaderManager(); loaderManager.initLoader(1, null, this).forceLoad(); } catch (Exception e){} } // else Toast.makeText(this, "Internet is not connected", Toast.LENGTH_SHORT).show(); } public boolean check_user(){ user_name=sharedPreferences.getString("username",""); if(!user_name.equals("")) return true; else{ if(createusername()) return false; } return false; } public boolean createusername() { AlertDialog.Builder builder = new AlertDialog.Builder(this); view2 = getLayoutInflater().inflate(R.layout.usernamedialog, null); GridView gridview = (GridView) view2.findViewById(R.id.gridview); gridview.setAdapter(new ImageAdapter(this)); builder.setView(view2); progress=(ProgressBar)view2.findViewById(R.id.progress); dialog = builder.create(); dialog.setCancelable(false); dialog.show(); return true; } public void submit(View view){ try {progress.setVisibility(View.VISIBLE); EditText user = (EditText) view2.findViewById(R.id.username); user_name = user.getText().toString(); if(checkusername()) { avatar = ImageAdapter.selected_avatar; ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo network = connectivity.getActiveNetworkInfo(); if (network != null && network.isConnected()) { new MyAsyncClass().execute(); } } } catch(Exception e){ e.printStackTrace(); } } private boolean checkusername(){ user_name=user_name.trim(); if(user_name.equals("")) { Toast.makeText(this, "Username can't be empty", Toast.LENGTH_SHORT).show(); return false; } else return true; } @Override public Loader<LeaderBoard_row> onCreateLoader(int id, Bundle args) { try { user_name=sharedPreferences.getString("username","user"); mylevel=rowlimit-3; mytime=String.valueOf(elapsedTime); return new LoaderForSubmit(this,new LeaderBoard_row(user_name,mylevel,mytime,avatar)); } catch (MalformedURLException e) { e.printStackTrace(); return null; } } @Override public void onLoadFinished(Loader<LeaderBoard_row> loader, LeaderBoard_row data) { } @Override public void onLoaderReset(Loader<LeaderBoard_row> loader) { } private class MyAsyncClass extends AsyncTask<Void,Void,Boolean>{ @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Boolean doInBackground(Void... params) { if(connect(myurl)) { return true;} else {return false;} } @Override protected void onPostExecute(Boolean aBoolean) { progress.setVisibility(View.GONE); super.onPostExecute(aBoolean); if(aBoolean) { done=true; } else done=false; if (done) Toast.makeText(ChessBoard.this, "Username in use.Try a different one.", Toast.LENGTH_SHORT).show(); else { if(dialog!=null) { dialog.dismiss(); dialog = null; editor.putString("username", user_name); editor.putInt("avatar", avatar); editor.apply(); Toast.makeText(ChessBoard.this, "Username created", Toast.LENGTH_SHORT).show(); putandgo(); } } } } public boolean connect(URL url){ try{ InputStream inputstream=null; HttpURLConnection connection=null; connection=(HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setReadTimeout(10000); connection.setReadTimeout(15000); connection.setDoInput(true); connection.setDoOutput(true); Uri.Builder builder = new Uri.Builder() .appendQueryParameter("username",user_name) .appendQueryParameter("avatar",String.valueOf(avatar)); String query = builder.build().getEncodedQuery(); OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(query); writer.flush(); writer.close(); os.close(); connection.connect(); inputstream=connection.getInputStream(); response=readfromstream(inputstream); if(checkresponse()) { return true; } else { return false;} } catch (IOException e) { e.printStackTrace(); } return false; } public boolean checkresponse(){ try { JSONObject object=new JSONObject(response); int m=object.getInt("success"); if(m==1){ return false;} else{ return true;} } catch (JSONException e) { e.printStackTrace(); } return false; } @Override protected void onDestroy() { super.onDestroy(); editor.remove("temptime"); editor.apply(); if (mAdView != null) { mAdView.destroy(); } if (mAdView2 != null) { mAdView2.destroy(); } } public void onmainmenu(View view){ Intent intent=new Intent(this,MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } }
71b95a9562acfae61479240d1e072a4aa6312acd
f7ae90b6af01b682d7bb9350ce2c7dae8fd6a9a3
/feign-user-service/src/main/java/com/demo/feignuserservice/client/OrderClient.java
21a4c313545ed632ef00df06c5119da21d814206
[]
no_license
sumit0987/microservices
b9a2e13b625af278ae537667e65e17e2016db514
10fb9457a9f03465fa2c506dd2313ed61310036f
refs/heads/master
2022-11-19T11:22:54.620251
2020-04-13T17:32:28
2020-04-13T17:32:28
253,853,365
0
0
null
null
null
null
UTF-8
Java
false
false
982
java
package com.demo.feignuserservice.client; import java.util.List; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import com.demo.feignuserservice.dto.OrderDto; //@FeignClient(value="order-service",url="http://127.0.0.1:8080/orders") @FeignClient(name="http://order-service/orders") public interface OrderClient { @GetMapping("/info") public String getPortNo(); @GetMapping("") public List<OrderDto> getAllOrders(); @GetMapping("/{id}") public String getOrder(@PathVariable("id") int id); @GetMapping("/byparam") public String getOrderByReqParam(@RequestParam("id") int id); @PostMapping("") public OrderDto saveOrder(@RequestBody OrderDto order); }
e918e8ea88b8789ef819e886c56af95719694b03
8e15d4343035150f1eb1791de15ed3a01a9930f9
/src/main/java/com/camisbrussi/javaWS/resources/UserResource.java
3039a895501a2c3e10a4629bbb854eed9c353833
[]
no_license
camisbrussi/course_JavaWS
9558ec645e5cf6fff07d1d11457789d8eba5feb3
80a3e30284137bc51e802c7c78216975ff92e0dc
refs/heads/main
2023-02-19T06:48:08.296639
2021-01-24T18:06:20
2021-01-24T18:06:20
331,142,327
0
0
null
null
null
null
UTF-8
Java
false
false
1,924
java
package com.camisbrussi.javaWS.resources; import java.net.URI; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.camisbrussi.javaWS.entities.User; import com.camisbrussi.javaWS.services.UserService; @RestController @RequestMapping(value = "/users") public class UserResource { @Autowired private UserService service; @GetMapping public ResponseEntity<List<User>> findAll() { List<User> list = service.findAll(); return ResponseEntity.ok().body(list); } @GetMapping(value = "/{id}") public ResponseEntity<User> findById(@PathVariable Long id) { User obj = service.findById(id); return ResponseEntity.ok().body(obj); } @PostMapping public ResponseEntity<User> insert(@RequestBody User obj) { obj = service.insert(obj); URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(obj.getId()).toUri(); return ResponseEntity.created(uri).body(obj); } @DeleteMapping(value = "/{id}") public ResponseEntity<Void> delete(@PathVariable Long id) { service.delete(id); return ResponseEntity.noContent().build(); } @PutMapping(value = "/{id}") public ResponseEntity<User> update(@PathVariable Long id, @RequestBody User obj){ obj = service.update(id, obj); return ResponseEntity.ok().body(obj); } }
ea4771dba67ffff06d2274ff6a6125c842cac9f2
f99f6ccd65f344d4c8651f4e4b058ec7f440f60c
/beforeGrpc/daocommon/src/main/java/com/yhglobal/gongxiao/foundation/supplier/dao/SupplierDao.java
822bbcfbc3a9da057299bd9ef7e38400b732e52f
[]
no_license
wilnd/gongxiao
fa60c9d5d57c3cbbb69d39e3848b42850bf22e12
f18bc2f48b4041ab09ee46876fd9f7a0dcb57a52
refs/heads/master
2020-03-28T05:50:50.258483
2018-09-07T09:32:00
2018-09-07T09:32:00
147,799,238
0
1
null
null
null
null
UTF-8
Java
false
false
989
java
package com.yhglobal.gongxiao.foundation.supplier.dao; import com.yhglobal.gongxiao.foundation.supplier.model.Supplier; import com.yhglobal.gongxiao.foundation.supplier.dao.mapping.SupplierMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class SupplierDao { @Autowired private SupplierMapper supplierMapper; public List<Supplier> selectAll() { return supplierMapper.selectAll(); } public Supplier getBySupplierId(Long supplierId) { return supplierMapper.getBySupplierId(supplierId); } public int updateSupplierInfo(String supplierCode, String easSupplierCode, String easSupplierName) { return supplierMapper.updateSupplierInfo(supplierCode, easSupplierCode, easSupplierName); } public Supplier getSupplierByCode(String supplierCode) { return supplierMapper.getSupplierByCode(supplierCode); } }
4a50c3ecdcae8514d8fd364b7f83c42470197283
e2f81f86b90ce8955a9f7bb31f84382f45c93f95
/OpenRedmine/src/main/java/jp/redmine/redmineclient/adapter/RedmineIssueAttachmentListAdapter.java
e052f42a5249d44ec16b5d5bea87eb3dde448f8f
[]
no_license
lucernae/OpenRedmine
e28d486074928a73f5ad46dab8182d703bbe2093
8684ce113cd39225287ca335318c2f8edda444bb
refs/heads/master
2020-12-25T04:01:15.493798
2014-06-21T16:53:15
2014-06-21T16:53:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,038
java
package jp.redmine.redmineclient.adapter; import java.sql.SQLException; import jp.redmine.redmineclient.R; import jp.redmine.redmineclient.db.cache.DatabaseCacheHelper; import jp.redmine.redmineclient.entity.RedmineAttachment; import jp.redmine.redmineclient.form.RedmineAttachmentListItemForm; import android.content.Context; import android.view.View; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; public class RedmineIssueAttachmentListAdapter extends RedmineDaoAdapter<RedmineAttachment, Long, DatabaseCacheHelper> { protected Integer connection_id; protected Integer issue_id; public RedmineIssueAttachmentListAdapter(DatabaseCacheHelper m, Context context) { super(m, context, RedmineAttachment.class); } public void setupParameter(int connection, int issue){ connection_id = connection; issue_id = issue; } @Override public boolean isValidParameter(){ if(issue_id == null || connection_id == null) return false; else return true; } @Override protected int getItemViewId() { return R.layout.issueattachmentitem; } @Override protected void setupView(View view, RedmineAttachment data) { RedmineAttachmentListItemForm form; if(view.getTag() != null && view.getTag() instanceof RedmineAttachmentListItemForm){ form = (RedmineAttachmentListItemForm)view.getTag(); } else { form = new RedmineAttachmentListItemForm(view); } form.setValue(data); } @Override protected long getDbItemId(RedmineAttachment item) { if(item == null){ return -1; } else { return item.getId(); } } @Override protected QueryBuilder<RedmineAttachment, Long> getQueryBuilder() throws SQLException { QueryBuilder<RedmineAttachment, Long> builder = dao.queryBuilder(); Where<RedmineAttachment,Long> where = builder.where() .eq(RedmineAttachment.CONNECTION, connection_id) .and() .eq(RedmineAttachment.ISSUE_ID, issue_id) ; builder.setWhere(where); builder.orderBy(RedmineAttachment.ATTACHMENT_ID, true); return builder; } }
41ebaeafaa49496601dcb015146e89ccb1483b63
c29de12f1f1632b7e5c0fae856cedfdd0d1f04da
/java/formulario-integrado/src/formulario/integrado/controller/LoginController.java
4c043cfb962d54dd92a934cf3a5411958cec6c2b
[]
no_license
thpoiani/formulario-integrado
6bb7cf8e806825b7177b159d451f562375f2ddb6
27a87cb603c3dcd3d6ebbcb34fe8eed6969428e0
refs/heads/master
2020-04-22T09:17:10.247277
2013-12-04T21:42:28
2013-12-04T21:42:28
32,117,982
0
0
null
null
null
null
UTF-8
Java
false
false
3,103
java
package formulario.integrado.controller; import formulario.integrado.business.ILoginBusiness; import formulario.integrado.business.LoginBusiness; import formulario.integrado.model.Login; import formulario.integrado.vendor.Dialog; import java.sql.SQLException; import java.util.Iterator; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; public class LoginController extends AbstractController { private ILoginBusiness loginBusiness; @FXML private Button login; @FXML private TextField prontuario; @FXML private PasswordField senha; @Override void initialize() { assert login != null : "fx:id=\"login\" was not injected: check your FXML file 'login.fxml'."; assert prontuario != null : "fx:id=\"prontuario\" was not injected: check your FXML file 'login.fxml'."; assert senha != null : "fx:id=\"senha\" was not injected: check your FXML file 'login.fxml'."; this.loginBusiness = new LoginBusiness(); Platform.runLater(new Runnable() { @Override public void run() { setWindow(login.getScene().getWindow()); } }); } @FXML void loginAction(ActionEvent event) { Login login = assemblyRequest(); if (login.isValid()) { try { if (this.loginBusiness.isAuthenticated(login)) { super.start("principal.fxml", "Principal"); super.close(); } else { Dialog.showError("Erro de autenticação", "Prontuário ou senha incorretos."); } } catch (SQLException ex) { ex.printStackTrace(); Dialog.showError("Login", "Falha em estabelecer conexão com o banco de dados."); } } this.showErrors(login); } /** * Método para recuperar dados inseridos pelo usuário * * @return Login */ private Login assemblyRequest() { Login login = new Login(); login.setProntuario(this.prontuario.getText()); login.setSenha(this.senha.getText()); return login; } /** * Método para colorir borda de campos inválidos * * @param Login login */ private void showErrors(Login login) { prontuario.setStyle(super.getClearStyle()); senha.setStyle(super.getClearStyle()); Iterator<String> iterator = login.createErrorIterator(); while (iterator.hasNext()) { switch (iterator.next()) { case "prontuario": prontuario.setStyle(super.getErrorStyle()); break; case "senha": senha.setStyle(super.getErrorStyle()); break; } } } }
[ "[email protected]@094e63fc-2494-60af-4612-397b49e1a6fc" ]
[email protected]@094e63fc-2494-60af-4612-397b49e1a6fc
afde57443f53cbd7ad565b27c38305ee2c13f689
f44a8ff6083e674dcf5e3e2917ef242bbbe8656b
/src/module-info.java
3aedd398b7c71965081b4f3d4a39549ab9f13257
[]
no_license
FrancescoRaco/VRP-Server
239c32764f8be179a5ca0f9e6c065100f0f3dde4
c46098c88314cf827f0fc4ba8abe31c15667d400
refs/heads/master
2020-06-13T18:13:20.990860
2019-07-02T01:26:08
2019-07-02T01:26:08
190,551,738
0
0
null
null
null
null
UTF-8
Java
false
false
268
java
module vrpServer { //Make the following packages visible outside exports core; exports server; exports test; exports test.busExamples; //Declare the needed libraries requires graphhopper.web; requires java.json; requires json.simple; requires jsprit.core; }
cfe291f7ad4ebcd5291df1389322ff290c18aabd
b21562c3f6b6dbd54c7c0224a605f28af4502215
/app/src/main/java/com/nikorych/mymovie/Data/MovieDatabase.java
3a5fef8d8fdc4b8981a19b4b07a7279fb8091ded
[]
no_license
nT14Ko/MoviesApp
045c7e7533c5baae23b9ba27911a4bce4882d009
75e0c253bf95b87834340600218bf7da1f0e2a9f
refs/heads/master
2022-09-14T13:02:05.859872
2020-06-02T12:01:52
2020-06-02T12:01:52
268,789,011
0
0
null
null
null
null
UTF-8
Java
false
false
824
java
package com.nikorych.mymovie.Data; import android.content.Context; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; @Database(entities = {Movie.class, FavouriteMovie.class}, version = 5, exportSchema = false) public abstract class MovieDatabase extends RoomDatabase { private static final String DB_NAME = "movies.db"; private static MovieDatabase database; private static final Object LOCK = new Object(); public static MovieDatabase getInstance(Context context) { synchronized (LOCK) { if (database == null) { database = Room.databaseBuilder(context, MovieDatabase.class, DB_NAME).fallbackToDestructiveMigration().build(); } } return database; } public abstract MovieDao movieDao(); }
f4174b01c06dd473dc96b5745a16391bf278d400
d9afc102711659a176e72fdb22a9662d44764c43
/app/src/main/java/org/nestordevelopments/lapurisima/Base2f.java
bcc5e56a5413d42342482cfc10268679f44aed47
[ "Apache-2.0" ]
permissive
nesmaba/LaPurisimaPublic
97cae52011e8beb066247ba7e17d2d21a6a68877
1be8c6e7b4ae1761369e811c259094166fda679b
refs/heads/master
2021-01-11T00:29:53.000408
2017-10-01T18:58:09
2017-10-01T18:58:09
70,524,464
0
0
null
null
null
null
UTF-8
Java
false
false
1,735
java
package org.nestordevelopments.lapurisima; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import org.nestordevelopments.lapurisima.Modelo.AlumnosSQLiteHelper; import java.io.IOException; public class Base2f extends AppCompatActivity { static CursosAsistenciaFragment fragmentCursosAsistencias; static AlumnosAsistenciaFragment fragmentAlumnosAsistencias; static AlumnosSQLiteHelper db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base2f); Intent intent = this.getIntent(); if(intent != null){ String boton= intent.getStringExtra("BotonPulsado"); if(boton.equals("Asistencias")) { fragmentCursosAsistencias = new CursosAsistenciaFragment(); getSupportFragmentManager().beginTransaction().replace(R.id.frameLayoutBase1, fragmentCursosAsistencias).commit(); fragmentAlumnosAsistencias = new AlumnosAsistenciaFragment(); getSupportFragmentManager().beginTransaction().replace(R.id.frameLayoutBase2, fragmentAlumnosAsistencias).commit(); } } inicializarBD(); } public boolean inicializarBD(){ // Esto es para inicializar la BD db = new AlumnosSQLiteHelper(this, AlumnosSQLiteHelper.DB_NAME, null, AlumnosSQLiteHelper.DB_VERSION); try { db.createDataBase(); db.openDataBase(); return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } }
501195acfa6b5419c526ba506664b679648f1de5
5bbf63a905ee7370d9ce10c120925ac53e666d64
/src/main/java/com/github/sigor/kafka/tutorial2/TwitterProducer.java
5fc7c379b794e2d4795f68363c2883d8efa6268a
[]
no_license
igor-storozhev/kafka-beginner-course
a2466dd10f8d8aa918020ebe4fd7feccc9a50b3c
dc5376f90953b6f37900df0319a4511860520c09
refs/heads/master
2022-12-14T13:09:59.295676
2020-09-16T14:59:40
2020-09-16T14:59:40
293,891,936
0
1
null
null
null
null
UTF-8
Java
false
false
3,162
java
package com.github.sigor.kafka.tutorial2; import com.google.common.collect.Lists; import com.twitter.hbc.ClientBuilder; import com.twitter.hbc.core.Client; import com.twitter.hbc.core.Constants; import com.twitter.hbc.core.Hosts; import com.twitter.hbc.core.HttpHosts; import com.twitter.hbc.core.endpoint.StatusesFilterEndpoint; import com.twitter.hbc.core.processor.StringDelimitedProcessor; import com.twitter.hbc.httpclient.auth.Authentication; import com.twitter.hbc.httpclient.auth.OAuth1; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; public class TwitterProducer { Logger logger = LoggerFactory.getLogger(TwitterProducer.class.getName()); String consumerKey = ""; String consumerSecret = ""; String token = ""; String tokenSecret = ""; public TwitterProducer() {} // constructor public static void main(String[] args) { new TwitterProducer().run(); } private void run() { logger.info("Setup"); /** Set up your blocking queues: Be sure to size these properly based on expected TPS of your stream */ BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>(1000); // create twitter client Client client = createTwitterClient(msgQueue); client.connect(); // create twitter producer // loop to send tweets to kafka // on a different thread, or multiple different threads.... while (!client.isDone()) { String msg = null; try { msg = msgQueue.poll(5, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); client.stop(); } if(msg != null) { logger.info(msg); } } logger.info("End of application"); } public Client createTwitterClient(BlockingQueue<String> msgQueue) { /** Declare the host you want to connect to, the endpoint, and authentication (basic auth or oauth) */ Hosts hosebirdHosts = new HttpHosts(Constants.STREAM_HOST); StatusesFilterEndpoint hosebirdEndpoint = new StatusesFilterEndpoint(); // Optional: set up some followings and track terms List<Long> followings = Lists.newArrayList(1234L, 566788L); List<String> terms = Lists.newArrayList("kafka","bitcoin"); hosebirdEndpoint.trackTerms(terms); // These secrets should be read from a config file Authentication hosebirdAuth = new OAuth1(consumerKey, consumerSecret, token, tokenSecret); ClientBuilder builder = new ClientBuilder() .name("Hosebird-Client-01") // optional: mainly for the logs .hosts(hosebirdHosts) .authentication(hosebirdAuth) .endpoint(hosebirdEndpoint) .processor(new StringDelimitedProcessor(msgQueue)); Client hosebirdClient = builder.build(); return hosebirdClient; } }
c1ad0369e93a3907f5cc49bba657d3ff8d6784a2
8b62e05f34373f6171aeeb94d0761bad4775f623
/src/repositorio/RepositorioListaProduto.java
c23d2ea928ec9af1dc53410b19956a1c5545a0fb
[]
no_license
hilderlanherbert/pet_shop
9d54e9c04e443d7a409b5313ac966be707aae07d
ad1522ae73890a570f96f8a998bb173f372d8071
refs/heads/master
2021-08-02T08:13:23.066917
2021-07-20T14:38:35
2021-07-20T14:38:35
156,426,152
2
1
null
null
null
null
UTF-8
Java
false
false
2,025
java
package repositorio; import classesBasicas.Produtos; import erros.ProdutoNaoEncontradoException; import interfaces.RepositorioProduto; public class RepositorioListaProduto implements RepositorioProduto { private Produtos produto; private RepositorioListaProduto proximo; //construtor comum public RepositorioListaProduto() { this.produto = null; this.proximo = null; } // insere o elemento na posicao da lista e referencia proximo para uma nova lista public void inserir(Produtos produto){ if (this.produto == null) { this.produto = produto; this.proximo = new RepositorioListaProduto(); } else { this.proximo.inserir(produto); } } public void remover(String tipo) throws ProdutoNaoEncontradoException { Produtos produtoAchado = this.procurar(tipo); if(this.produto!=null){ if(this.produto.equals(produtoAchado)){ this.produto = this.proximo.produto; this.proximo = this.proximo.proximo; }else{ this.proximo.remover(tipo); } }else{ throw new ProdutoNaoEncontradoException(); } } public void atualizar(Produtos produto) throws ProdutoNaoEncontradoException { this.remover(produto.getTipo()); this.inserir(produto); } public Produtos procurar(String tipo) throws ProdutoNaoEncontradoException { if (this.produto != null) { if (this.produto.getTipo().equals(tipo)) { return this.produto; } else { this.proximo.procurar(tipo); } } throw new ProdutoNaoEncontradoException(); } public boolean existe(String tipo) { try{ this.procurar(tipo); return true; }catch(ProdutoNaoEncontradoException pnee){ return false; } } }
525eb82ce741ecf0010d336d4f3addeaa89270a8
0f4481fbec99f5963f5d7ff623c1de2f9b585542
/TallerMecanico/TallerMecanico-ejb/src/java/com/inacap/entity/Dtc.java
0080f8fa03ac9ebc4034964ee43844da42896c4a
[]
no_license
Danny43/ProyectoWeb
e5682d7c7fdffd0eedf748a862ffcf63958ec080
8839955a61e1f9fdc1fbf72ffefdb8510471b4fe
refs/heads/master
2020-03-23T15:29:38.332493
2018-07-20T20:08:54
2018-07-20T20:08:54
135,937,076
0
0
null
2018-06-06T01:48:45
2018-06-03T20:13:02
Java
UTF-8
Java
false
false
3,220
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 com.inacap.entity; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author CarlosCoronado */ @Entity @Table(name = "dtc") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Dtc.findAll", query = "SELECT d FROM Dtc d") , @NamedQuery(name = "Dtc.findByIdDtc", query = "SELECT d FROM Dtc d WHERE d.idDtc = :idDtc")}) public class Dtc implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "id_dtc") private String idDtc; @Basic(optional = false) @Lob @Column(name = "descripcion") private String descripcion; @JoinTable(name = "dtc_has_orden_trabajo", joinColumns = { @JoinColumn(name = "dtc_id_dtc", referencedColumnName = "id_dtc")}, inverseJoinColumns = { @JoinColumn(name = "orden_trabajo_id_orden_trabajo", referencedColumnName = "id_orden_trabajo")}) @ManyToMany private List<OrdenTrabajo> ordenTrabajoList; public Dtc() { } public Dtc(String idDtc) { this.idDtc = idDtc; } public Dtc(String idDtc, String descripcion) { this.idDtc = idDtc; this.descripcion = descripcion; } public String getIdDtc() { return idDtc; } public void setIdDtc(String idDtc) { this.idDtc = idDtc; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } @XmlTransient public List<OrdenTrabajo> getOrdenTrabajoList() { return ordenTrabajoList; } public void setOrdenTrabajoList(List<OrdenTrabajo> ordenTrabajoList) { this.ordenTrabajoList = ordenTrabajoList; } @Override public int hashCode() { int hash = 0; hash += (idDtc != null ? idDtc.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Dtc)) { return false; } Dtc other = (Dtc) object; if ((this.idDtc == null && other.idDtc != null) || (this.idDtc != null && !this.idDtc.equals(other.idDtc))) { return false; } return true; } @Override public String toString() { return "com.inacap.entity.Dtc[ idDtc=" + idDtc + " ]"; } }
[ "Daniel@DESKTOP-OH841GJ" ]
Daniel@DESKTOP-OH841GJ
938ea0f64b12fad486fad3988a6ad5b47f79c404
58b2937048759e48d6de204ff520466247e31782
/app/src/main/java/mobileattendancecom/mobileattendance/studentAttendvw.java
e5d96a614f0e8e6261ca5d5aee61adf486421b7f
[]
no_license
NSK25/mobile-attendence-master
0babcd1fd7ed75c4b498ff0fd5dc6fa81fb4252b
b79907f58c01e5232aed32cbb87d584444014bf3
refs/heads/master
2020-03-25T19:43:22.975754
2018-08-09T03:37:56
2018-08-09T03:37:56
144,097,034
0
0
null
null
null
null
UTF-8
Java
false
false
2,475
java
package mobileattendancecom.mobileattendance; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; /** * Created by riju on 7/5/16. */ public class studentAttendvw extends AppCompatActivity { TextView vwSterm; TextView vwSyear; ListView listViewStudents; ArrayList<String> arylistStudents; ArrayAdapter<String> studAdapter; dataStorage listData; String crTerm; ArrayList<String> ccurDate; String scourse; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_attend_studvw); Intent myIntent = getIntent(); scourse = myIntent.getStringExtra("courseid"); vwSterm = (TextView)findViewById(R.id.txtSterm); vwSyear = (TextView)findViewById(R.id.txtSyear); listViewStudents = (ListView) findViewById(R.id.listViewSt); arylistStudents = new ArrayList<String>(); DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); String now = df.format(new Date()); ccurDate = new ArrayList<String>(); for (String retval: now.split("/")) { ccurDate.add(retval); } String mdscat = ccurDate.get(0)+ccurDate.get(1); int mdTerm = Integer.parseInt(mdscat); courseDetails fcrses = new courseDetails(); crTerm = fcrses.getTermvalue(mdTerm); vwSterm.setText(crTerm); vwSyear.setText(scourse); listData=dataStorage.getInstance(this); } @Override protected void onStart() { super.onStart(); arylistStudents=listData.markedAttendstvw(scourse); studAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arylistStudents); listViewStudents.setAdapter(studAdapter); studAdapter.notifyDataSetChanged(); } @Override public void onBackPressed() { Intent homeIntent = new Intent(getApplicationContext(), studentHome.class); homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); homeIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(homeIntent); } }
ba5c903b8266d56e6eadf943bb2cf6684355c5ad
c474b03758be154e43758220e47b3403eb7fc1fc
/apk/decompiled/com.tinder_2018-07-26_source_from_JADX/sources/io/paperdb/PaperTable.java
d2bb54c061cbcdad8983b80b9542c8e3b021e624
[]
no_license
EstebanDalelR/tinderAnalysis
f80fe1f43b3b9dba283b5db1781189a0dd592c24
941e2c634c40e5dbf5585c6876ef33f2a578b65c
refs/heads/master
2020-04-04T09:03:32.659099
2018-11-23T20:41:28
2018-11-23T20:41:28
155,805,042
0
0
null
2018-11-18T16:02:45
2018-11-02T02:44:34
null
UTF-8
Java
false
false
143
java
package io.paperdb; class PaperTable<T> { T mContent; PaperTable() { } PaperTable(T t) { this.mContent = t; } }
2020c4de3c304f21b7aa3edea82081a45b47f393
159ab8748c74281282c3a0a323a7a9728c9f5805
/java/21days-v6-source-code/chapter19/RssFilter.java
161431535d58af0354678afeb7552b2f276ef397
[]
no_license
99sun99/java_practice
4ed8eefc4013d7a169b5a619989eb3b9b3525a75
4c01d2977e57a1a92986fc018c47884f214a5303
refs/heads/master
2021-01-16T16:50:50.006695
2020-02-26T06:52:08
2020-02-26T06:52:08
243,188,645
0
0
null
null
null
null
UTF-8
Java
false
false
2,919
java
import nu.xom.*; public class RssFilter { public static void main(String[] arguments) { if (arguments.length < 2) { System.out.println("Usage: java RssFilter rssFile searchTerm"); System.exit(-1); } // Save the RSS location and search term String rssFile = arguments[0]; String searchTerm = arguments[1]; try { // Fill a tree with an RSS file's XML data // The file can be local or something on the // Web accessible via a URL. Builder bob = new Builder(); Document doc = bob.build(rssFile); // Get the file's root element (<rss>) Element rss = doc.getRootElement(); // Get the element's version attribute Attribute rssVersion = rss.getAttribute("version"); String version = rssVersion.getValue(); // Add the DTD for RSS 0.91 feeds, if needed if ( (version.equals("0.91")) & (doc.getDocType() == null) ) { DocType rssDtd = new DocType("rss", "http://my.netscape.com/publish/formats/rss-0.91.dtd"); doc.insertChild(rssDtd, 0); } // Get the first (and only) <channel> element Element channel = rss.getFirstChildElement("channel"); // Get its <title> element Element title = channel.getFirstChildElement("title"); Text titleText = (Text)title.getChild(0); // Change the title to reflect the search term titleText.setValue(titleText.getValue() + ": Search for " + searchTerm + " articles"); // Get all of the <item> elements and loop through them Elements items = channel.getChildElements("item"); for (int i = 0; i < items.size(); i++) { // Get an <item> element Element item = items.get(i); // Look for a <title> element inside it Element itemTitle = item.getFirstChildElement("title"); // If found, look for its contents if (itemTitle != null) { Text itemTitleText = (Text) itemTitle.getChild(0); // If the search text is not found in the item, // delete it from the tree if (itemTitleText.toString().indexOf(searchTerm) == -1) channel.removeChild(item); } } // Display the results with a serializer Serializer output = new Serializer(System.out); output.setIndent(2); output.write(doc); } catch (Exception exc) { System.out.println("Error: " + exc.getMessage()); exc.printStackTrace(); } } }
414a94b5f49ae8251f9e40e6777d767efa2ffc40
042f19f54f6e2d05d8b27c109a4a238f0052c71f
/app/src/main/java/application/com/zheng/ilock/SecondActivity.java
e5a108ebf2e78e74ceab1954a77f49d8adddd68a
[]
no_license
zhenghung/iLock-
fe91a06307e1e08834963a1e65339a0d0aa105fd
2f820c0f1d4c02a562291d2cdb81d6222b8cd919
refs/heads/master
2021-01-18T00:08:52.951526
2017-12-19T04:38:11
2017-12-19T04:38:11
81,747,011
2
0
null
null
null
null
UTF-8
Java
false
false
836
java
package application.com.zheng.ilock; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); final Button button1 = (Button) findViewById(R.id.button); button1.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { goToThirdActivity(); } }); } public void goToThirdActivity() { Intent intent = new Intent(this, ThirdActivity.class); startActivity(intent); } }
95ddeb411635c51b90e8c5e4c467beefbebef8d7
09ca502b44715c987b65fc3e06d41e60d4d08bc0
/bonita-server/src/test/java/org/ow2/bonita/connector/examples/test/SingleInputFieldConnectorTest.java
e617836db36564f94101591bfcce275264e484c8
[]
no_license
fivegg/bbonita-runtime-5-10-1
29b51fe1fd18c7307809c50c28f3a33aab63786d
585aa4ca3cf14771f03d087cfb82237aff99897d
refs/heads/master
2016-09-05T09:47:31.631120
2013-12-20T03:03:11
2013-12-20T03:03:11
14,005,787
1
0
null
null
null
null
UTF-8
Java
false
false
1,994
java
/** * Copyright (C) 2009 Bull S. A. S. * Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation * version 2.1 of the License. * 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 Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth * Floor, Boston, MA 02110-1301, USA. **/ package org.ow2.bonita.connector.examples.test; import org.ow2.bonita.connector.core.Connector; import org.ow2.bonita.connector.core.ConnectorTest; import org.ow2.bonita.connector.examples.SingleInputFieldConnector; import org.ow2.bonita.util.BonitaException; public class SingleInputFieldConnectorTest extends ConnectorTest { public void testValidate() throws BonitaException { SingleInputFieldConnector connector = new SingleInputFieldConnector(); connector.setField(null); assertTrue("No errors with a field!", connector.validate().isEmpty()); connector.setField(""); assertTrue(connector.validate().isEmpty()); connector.setInputField(null); assertTrue("No error with an input field!", connector.validate().isEmpty()); connector.setInputField(""); assertTrue(connector.validate().isEmpty()); connector.setNumber(0); assertTrue("No error with an input field!", connector.validate().isEmpty()); connector.setInputField(""); assertTrue(connector.validate().isEmpty()); } @Override protected Class<? extends Connector> getConnectorClass() { return SingleInputFieldConnector.class; } }
c9837732ed20115e2f3ae0b64a2b0d36b143bc36
6052f4647363d160d7b044e4488aae106ba4f0db
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/encoderTrial.java
ab7ba7d551738a7b8333060176d67539b03ac02e
[ "BSD-3-Clause" ]
permissive
bignaczak/SkyStone_eBots_2019
2b3e7193d0e10ce9f26e0e9556cf6b7978c3f695
e86db45732d8a02cc88d1b89e9b4d865c85ee804
refs/heads/master
2020-06-26T05:20:49.564582
2019-12-15T13:06:37
2019-12-15T13:06:37
199,543,688
0
0
null
null
null
null
UTF-8
Java
false
false
874
java
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; @TeleOp @Disabled public class encoderTrial extends eBotsOpMode2019 { @Override public void runOpMode(){ DcMotor motor1; Integer encoderCount; motor1 = hardwareMap.get(DcMotor.class, "motor1"); motor1.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); telemetry.addLine("Encoder Count: "); telemetry.update(); waitForStart(); motor1.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); while (opModeIsActive()){ encoderCount = motor1.getCurrentPosition(); telemetry.addData("Encoder Count: ", encoderCount.toString()); telemetry.update(); } } }
b52ab21502938bc3b05444cb60776876ae04e3e1
d3e7473a1282a8ca494e12899265066790af641b
/app/src/main/java/hyxd/parentapp/im/extension/SnapChatAttachment.java
a0e34dc7fe08b833d6e6a40c17260aa08a762e08
[]
no_license
HLJJMS/JingKeJiaZhang
1290520670df8bc1f6d77581bd6f29ee42e8faec
3f5a8c3692854389af2f3fa6a1cb5e0bf4c7a996
refs/heads/master
2020-03-30T00:40:20.166293
2018-09-27T07:21:21
2018-09-27T07:21:21
150,536,481
0
1
null
null
null
null
UTF-8
Java
false
false
1,412
java
package hyxd.parentapp.im.extension; import android.text.TextUtils; import com.alibaba.fastjson.JSONObject; import com.netease.nimlib.sdk.msg.attachment.FileAttachment; /** * Created by zhoujianghua on 2015/7/8. */ public class SnapChatAttachment extends FileAttachment { private static final String KEY_PATH = "path"; private static final String KEY_SIZE = "size"; private static final String KEY_MD5 = "md5"; private static final String KEY_URL = "url"; public SnapChatAttachment() { super(); } public SnapChatAttachment(JSONObject data) { load(data); } @Override public String toJson(boolean send) { JSONObject data = new JSONObject(); try { if (!send && !TextUtils.isEmpty(path)) { data.put(KEY_PATH, path); } if (!TextUtils.isEmpty(md5)) { data.put(KEY_MD5, md5); } data.put(KEY_URL, url); data.put(KEY_SIZE, size); } catch (Exception e) { e.printStackTrace(); } return CustomAttachParser.packData(CustomAttachmentType.SnapChat, data); } private void load(JSONObject data) { path = data.getString(KEY_PATH); md5 = data.getString(KEY_MD5); url = data.getString(KEY_URL); size = data.containsKey(KEY_SIZE) ? data.getLong(KEY_SIZE) : 0; } }
1e0262aa8db71762135513e88ab030260c10670a
e41e83239bd24d2585462e13a2758f8d94a6b13c
/src/sandbox/RealEngineering.java
9428b991ec8adb14f3348434aabaf6a6fbfb0ab8
[]
no_license
ignac8/talandar
ed1561884aa9f32a951ab144628a566a1b7cdbd1
4826af5cbe914eae8bd949e7c074d3765e940371
refs/heads/master
2023-04-25T09:26:56.331489
2017-12-13T18:37:25
2017-12-13T18:37:25
366,116,968
0
0
null
null
null
null
UTF-8
Java
false
false
1,165
java
package sandbox; import fitnessevaluator.starcraft.StarcraftEvaluator; import jnibwapi.JNIBWAPI; import jnibwapi.Position; import jnibwapi.Unit; import neuralnetwork.ConstantNeuralNetwork; import neuralnetwork.NeuralNetwork; import player.NeuralNetworkPlayer; import player.factory.PlayerFactory; public class RealEngineering { public static void main(String... args) { StarcraftEvaluator starcraftEvaluator = StarcraftEvaluator.getInstance(); NeuralNetworkPlayer<JNIBWAPI, Unit, Position> neuralNetworkStarcraftPlayer = PlayerFactory.getStarcraftNeuralNetworkPlayer(0); starcraftEvaluator.setPlayer(neuralNetworkStarcraftPlayer); //NeuralNetwork neuralNetwork = fromJson(loadFile("best-0.1,0.001,1000,3.json"), NeuralNetwork.class); NeuralNetwork neuralNetwork = new ConstantNeuralNetwork(5, 14, 7, 5); neuralNetworkStarcraftPlayer.setNeuralNetwork(neuralNetwork); for (int counter = 0; counter < 9 * 10; counter++) { double fitness = starcraftEvaluator.evaluate(); System.out.println(counter); System.out.println(fitness); } System.exit(0); } }
e4772911ebd99a11bcb0482165f3c69a2a546113
4a3e4fe5f6df562168f9210da81ac1a19a77f796
/src/main/java/com/hk/logistics/service/impl/RegionTypeServiceImpl.java
ac82e10aefb65c704c151b28830a145556425f25
[]
no_license
vikrantch-hk/HKLogistics
d31320d87ad7310fb70743f368d10f997b4d514f
9f957ce7414ac5cd80196089a647b341d36498b9
refs/heads/master
2020-03-21T05:45:28.071303
2018-06-22T11:28:08
2018-06-22T11:28:08
138,178,097
0
0
null
null
null
null
UTF-8
Java
false
false
4,309
java
package com.hk.logistics.service.impl; import com.hk.logistics.service.RegionTypeService; import com.hk.logistics.domain.RegionType; import com.hk.logistics.repository.RegionTypeRepository; import com.hk.logistics.repository.search.RegionTypeSearchRepository; import com.hk.logistics.service.dto.RegionTypeDTO; import com.hk.logistics.service.mapper.RegionTypeMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.elasticsearch.index.query.QueryBuilders.*; /** * Service Implementation for managing RegionType. */ @Service @Transactional public class RegionTypeServiceImpl implements RegionTypeService { private final Logger log = LoggerFactory.getLogger(RegionTypeServiceImpl.class); private final RegionTypeRepository regionTypeRepository; private final RegionTypeMapper regionTypeMapper; private final RegionTypeSearchRepository regionTypeSearchRepository; public RegionTypeServiceImpl(RegionTypeRepository regionTypeRepository, RegionTypeMapper regionTypeMapper, RegionTypeSearchRepository regionTypeSearchRepository) { this.regionTypeRepository = regionTypeRepository; this.regionTypeMapper = regionTypeMapper; this.regionTypeSearchRepository = regionTypeSearchRepository; } /** * Save a regionType. * * @param regionTypeDTO the entity to save * @return the persisted entity */ @Override public RegionTypeDTO save(RegionTypeDTO regionTypeDTO) { log.debug("Request to save RegionType : {}", regionTypeDTO); RegionType regionType = regionTypeMapper.toEntity(regionTypeDTO); regionType = regionTypeRepository.save(regionType); RegionTypeDTO result = regionTypeMapper.toDto(regionType); regionTypeSearchRepository.save(regionType); return result; } /** * Get all the regionTypes. * * @return the list of entities */ @Override @Transactional(readOnly = true) public List<RegionTypeDTO> findAll() { log.debug("Request to get all RegionTypes"); return regionTypeRepository.findAll().stream() .map(regionTypeMapper::toDto) .collect(Collectors.toCollection(LinkedList::new)); } /** * Get one regionType by id. * * @param id the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Optional<RegionTypeDTO> findOne(Long id) { log.debug("Request to get RegionType : {}", id); return regionTypeRepository.findById(id) .map(regionTypeMapper::toDto); } /** * Delete the regionType by id. * * @param id the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete RegionType : {}", id); regionTypeRepository.deleteById(id); regionTypeSearchRepository.deleteById(id); } /** * Search for the regionType corresponding to the query. * * @param query the query of the search * @return the list of entities */ @Override @Transactional(readOnly = true) public List<RegionTypeDTO> search(String query) { log.debug("Request to search RegionTypes for query {}", query); return StreamSupport .stream(regionTypeSearchRepository.search(queryStringQuery(query)).spliterator(), false) .map(regionTypeMapper::toDto) .collect(Collectors.toList()); } @Override @Transactional public List<RegionTypeDTO> upload(List<RegionTypeDTO> batch) { log.debug("Request to upload RegionType : {}", batch); List<RegionType> inList = batch.parallelStream().map(dto -> regionTypeMapper.toEntity(dto)) .collect(Collectors.toList()); List<RegionType> outList = regionTypeRepository.saveAll(inList); List<RegionTypeDTO> result = outList.parallelStream().map(regionType -> regionTypeMapper.toDto(regionType)) .collect(Collectors.toList()); regionTypeSearchRepository.saveAll(inList); return result; } }
c94af6368f4e45272a073c80f830f51028b0ca1e
949c2524bb7a501147cb4afc467947de054250a7
/app/src/main/java/com/caowj/opengl/utils/GLEnvironment.java
a55313d07d667bed156c4700f21ca467359235d8
[]
no_license
tangnuo/AndroidOpenGLDemo_Kotlin
a27cfdf4871044e923bb1f415598858b996797fd
684f77a182b223006483e464f6d4876deb00eac0
refs/heads/master
2022-11-26T09:02:31.449608
2020-07-30T08:05:45
2020-07-30T08:05:45
283,652,594
1
0
null
null
null
null
UTF-8
Java
false
false
48,246
java
package com.caowj.opengl.utils; import android.content.Context; import android.opengl.EGL14; import android.opengl.EGLExt; import android.opengl.GLDebugHelper; import android.opengl.GLSurfaceView; import android.util.Log; import android.view.SurfaceHolder; import java.io.Writer; import java.lang.ref.WeakReference; import java.util.ArrayList; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; class GLEnvironment implements SurfaceHolder.Callback2 { public final static int RENDERMODE_WHEN_DIRTY = 0; public final static int RENDERMODE_CONTINUOUSLY = 1; public final static int DEBUG_CHECK_GL_ERROR = 1; public final static int DEBUG_LOG_GL_CALLS = 2; private final static String TAG = "GLSurfaceView"; private final static boolean LOG_ATTACH_DETACH = false; private final static boolean LOG_THREADS = false; private final static boolean LOG_PAUSE_RESUME = false; private final static boolean LOG_SURFACE = false; private final static boolean LOG_RENDERER = false; private final static boolean LOG_RENDERER_DRAW_FRAME = false; private final static boolean LOG_EGL = false; private static final GLThreadManager sGLThreadManager = new GLThreadManager(); private final WeakReference<GLEnvironment> mThisWeakRef = new WeakReference<>(this); public Object nativeWindow; private GLThread mGLThread; private GLSurfaceView.Renderer mRenderer; private boolean mDetached; private EGLConfigChooser mEGLConfigChooser; private EGLContextFactory mEGLContextFactory; private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory; private int mDebugFlags; private int mEGLContextClientVersion; private boolean mPreserveEGLContextOnPause; public GLEnvironment(Context context) { init(); } @Override protected void finalize() throws Throwable { try { if (mGLThread != null) { // GLThread may still be running if this view was never // attached to a window. mGLThread.requestExitAndWait(); } } finally { super.finalize(); } } private void init() { } public int getDebugFlags() { return mDebugFlags; } public boolean getPreserveEGLContextOnPause() { return mPreserveEGLContextOnPause; } public void setPreserveEGLContextOnPause(boolean preserveOnPause) { mPreserveEGLContextOnPause = preserveOnPause; } public void setRenderer(GLSurfaceView.Renderer renderer) { checkRenderThreadState(); if (mEGLConfigChooser == null) { mEGLConfigChooser = new SimpleEGLConfigChooser(true); } if (mEGLContextFactory == null) { mEGLContextFactory = new DefaultContextFactory(); } if (mEGLWindowSurfaceFactory == null) { mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory(); } mRenderer = renderer; mGLThread = new GLThread(mThisWeakRef); mGLThread.start(); } public void setEGLContextFactory(EGLContextFactory factory) { checkRenderThreadState(); mEGLContextFactory = factory; } public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) { checkRenderThreadState(); mEGLWindowSurfaceFactory = factory; } public void setEGLConfigChooser(EGLConfigChooser configChooser) { checkRenderThreadState(); mEGLConfigChooser = configChooser; } public void setEGLConfigChooser(boolean needDepth) { setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); } public void setEGLConfigChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) { setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize)); } public void setEGLContextClientVersion(int version) { checkRenderThreadState(); mEGLContextClientVersion = version; } public int getRenderMode() { return mGLThread.getRenderMode(); } public void setRenderMode(int renderMode) { mGLThread.setRenderMode(renderMode); } public void requestRender() { mGLThread.requestRender(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { mGLThread.onWindowResize(w, h); } @Override public void surfaceRedrawNeeded(SurfaceHolder holder) { if (mGLThread != null) { mGLThread.requestRenderAndWait(); } } public void onPause() { mGLThread.onPause(); } public void onResume() { mGLThread.onResume(); } public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } protected void onAttachedToWindow() { if (LOG_ATTACH_DETACH) { Log.d(TAG, "onAttachedToWindow reattach =" + mDetached); } if (mDetached && (mRenderer != null)) { int renderMode = RENDERMODE_CONTINUOUSLY; if (mGLThread != null) { renderMode = mGLThread.getRenderMode(); } mGLThread = new GLThread(mThisWeakRef); if (renderMode != RENDERMODE_CONTINUOUSLY) { mGLThread.setRenderMode(renderMode); } mGLThread.start(); } mDetached = false; } protected void onDetachedFromWindow() { if (LOG_ATTACH_DETACH) { Log.d(TAG, "onDetachedFromWindow"); } if (mGLThread != null) { mGLThread.requestExitAndWait(); } mDetached = true; } public void setNativeWindow(Object object) { this.nativeWindow = object; } private void checkRenderThreadState() { if (mGLThread != null) { throw new IllegalStateException( "setRenderer has already been called for this instance."); } } public interface EGLContextFactory { EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig); void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context); } public interface EGLWindowSurfaceFactory { /** * @return null if the surface cannot be constructed. */ EGLSurface createSurface(EGL10 egl, EGLDisplay display, EGLConfig config, Object nativeWindow); void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface); } public interface EGLConfigChooser { EGLConfig chooseConfig(EGL10 egl, EGLDisplay display); } private static class DefaultWindowSurfaceFactory implements EGLWindowSurfaceFactory { public EGLSurface createSurface(EGL10 egl, EGLDisplay display, EGLConfig config, Object nativeWindow) { EGLSurface result = null; try { result = egl.eglCreateWindowSurface(display, config, nativeWindow, null); } catch (IllegalArgumentException e) { // This exception indicates that the surface flinger surface // is not valid. This can happen if the surface flinger surface has // been torn down, but the application has not yet been // notified via SurfaceHolder.Callback.surfaceDestroyed. // In theory the application should be notified first, // but in practice sometimes it is not. See b/4588890 Log.e(TAG, "eglCreateWindowSurface", e); } return result; } public void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface) { egl.eglDestroySurface(display, surface); } } private static class EglHelper { EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; private WeakReference<GLEnvironment> mGLSurfaceViewWeakRef; public EglHelper(WeakReference<GLEnvironment> glSurfaceViewWeakRef) { mGLSurfaceViewWeakRef = glSurfaceViewWeakRef; } public static void throwEglException(String function, int error) { String message = formatEglError(function, error); if (LOG_THREADS) { Log.e("EglHelper", "throwEglException tid=" + Thread.currentThread().getId() + " " + message); } throw new RuntimeException(message); } public static void logEglErrorAsWarning(String tag, String function, int error) { Log.w(tag, formatEglError(function, error)); } public static String formatEglError(String function, int error) { return function + " failed: " + error; } public void start() { if (LOG_EGL) { Log.w("EglHelper", "start() tid=" + Thread.currentThread().getId()); } /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); if (mEglDisplay == EGL10.EGL_NO_DISPLAY) { throw new RuntimeException("eglGetDisplay failed"); } /* * We can now initialize EGL for that display */ int[] version = new int[2]; if (!mEgl.eglInitialize(mEglDisplay, version)) { throw new RuntimeException("eglInitialize failed"); } GLEnvironment view = mGLSurfaceViewWeakRef.get(); if (view == null) { mEglConfig = null; mEglContext = null; } else { mEglConfig = view.mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay); /* * Create an EGL context. We want to do this as rarely as we can, because an * EGL context is a somewhat heavy object. */ mEglContext = view.mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig); } if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) { mEglContext = null; throwEglException("createContext"); } if (LOG_EGL) { Log.w("EglHelper", "createContext " + mEglContext + " tid=" + Thread.currentThread().getId()); } mEglSurface = null; } public boolean createSurface() { if (LOG_EGL) { Log.w("EglHelper", "createSurface() tid=" + Thread.currentThread().getId()); } /* * Check preconditions. */ if (mEgl == null) { throw new RuntimeException("egl not initialized"); } if (mEglDisplay == null) { throw new RuntimeException("eglDisplay not initialized"); } if (mEglConfig == null) { throw new RuntimeException("mEglConfig not initialized"); } /* * The window size has changed, so we need to create a new * surface. */ destroySurfaceImp(); /* * Create an EGL surface we can render into. */ GLEnvironment view = mGLSurfaceViewWeakRef.get(); if (view != null) { mEglSurface = view.mEGLWindowSurfaceFactory.createSurface(mEgl, mEglDisplay, mEglConfig, view.nativeWindow); } else { mEglSurface = null; } if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) { int error = mEgl.eglGetError(); if (error == EGL10.EGL_BAD_NATIVE_WINDOW) { Log.e("EglHelper", "createWindowSurface returned EGL_BAD_NATIVE_WINDOW."); } return false; } /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) { /* * Could not make the context current, probably because the underlying * SurfaceView surface has been destroyed. */ logEglErrorAsWarning("EGLHelper", "eglMakeCurrent", mEgl.eglGetError()); return false; } return true; } GL createGL() { GL gl = mEglContext.getGL(); GLEnvironment view = mGLSurfaceViewWeakRef.get(); if (view != null) { if ((view.mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS)) != 0) { int configFlags = 0; Writer log = null; if ((view.mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) { configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR; } if ((view.mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) { log = new LogWriter(); } gl = GLDebugHelper.wrap(gl, configFlags, log); } } return gl; } public int swap() { if (!mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) { return mEgl.eglGetError(); } return EGL10.EGL_SUCCESS; } public void destroySurface() { if (LOG_EGL) { Log.w("EglHelper", "destroySurface() tid=" + Thread.currentThread().getId()); } destroySurfaceImp(); } private void destroySurfaceImp() { if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); GLEnvironment view = mGLSurfaceViewWeakRef.get(); if (view != null) { view.mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, mEglSurface); } mEglSurface = null; } } public void finish() { if (LOG_EGL) { Log.w("EglHelper", "finish() tid=" + Thread.currentThread().getId()); } if (mEglContext != null) { GLEnvironment view = mGLSurfaceViewWeakRef.get(); if (view != null) { view.mEGLContextFactory.destroyContext(mEgl, mEglDisplay, mEglContext); } mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } private void throwEglException(String function) { throwEglException(function, mEgl.eglGetError()); } } static class GLThread extends Thread { // Once the thread is started, all accesses to the following member // variables are protected by the sGLThreadManager monitor private boolean mShouldExit; private boolean mExited; private boolean mRequestPaused; private boolean mPaused; private boolean mHasSurface; private boolean mSurfaceIsBad; private boolean mWaitingForSurface; private boolean mHaveEglContext; private boolean mHaveEglSurface; private boolean mFinishedCreatingEglSurface; private boolean mShouldReleaseEglContext; private int mWidth; private int mHeight; private int mRenderMode; private boolean mRequestRender; private boolean mWantRenderNotification; private boolean mRenderComplete; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private boolean mSizeChanged = true; private EglHelper mEglHelper; /** * Set once at thread construction time, nulled out when the parent view is garbage * called. This weak reference allows the GLSurfaceView to be garbage collected while * the GLThread is still alive. */ private WeakReference<GLEnvironment> mGLSurfaceViewWeakRef; GLThread(WeakReference<GLEnvironment> glSurfaceViewWeakRef) { super(); mWidth = 0; mHeight = 0; mRequestRender = true; mRenderMode = RENDERMODE_CONTINUOUSLY; mWantRenderNotification = false; mGLSurfaceViewWeakRef = glSurfaceViewWeakRef; } @Override public void run() { setName("GLThread " + getId()); if (LOG_THREADS) { Log.i("GLThread", "starting tid=" + getId()); } try { guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sGLThreadManager.threadExiting(this); } } /* * This private method should only be called inside a * synchronized(sGLThreadManager) block. */ private void stopEglSurfaceLocked() { if (mHaveEglSurface) { mHaveEglSurface = false; mEglHelper.destroySurface(); } } /* * This private method should only be called inside a * synchronized(sGLThreadManager) block. */ private void stopEglContextLocked() { if (mHaveEglContext) { mEglHelper.finish(); mHaveEglContext = false; sGLThreadManager.releaseEglContextLocked(this); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(mGLSurfaceViewWeakRef); mHaveEglContext = false; mHaveEglSurface = false; mWantRenderNotification = false; try { GL10 gl = null; boolean createEglContext = false; boolean createEglSurface = false; boolean createGlInterface = false; boolean lostEglContext = false; boolean sizeChanged = false; boolean wantRenderNotification = false; boolean doRenderNotification = false; boolean askedToReleaseEglContext = false; int w = 0; int h = 0; Runnable event = null; while (true) { synchronized (sGLThreadManager) { while (true) { if (mShouldExit) { return; } if (!mEventQueue.isEmpty()) { event = mEventQueue.remove(0); break; } // Update the pause state. boolean pausing = false; if (mPaused != mRequestPaused) { pausing = mRequestPaused; mPaused = mRequestPaused; sGLThreadManager.notifyAll(); if (LOG_PAUSE_RESUME) { Log.i("GLThread", "mPaused is now " + mPaused + " tid=" + getId()); } } // Do we need to give up the EGL context? if (mShouldReleaseEglContext) { if (LOG_SURFACE) { Log.i("GLThread", "releasing EGL context because asked to tid=" + getId()); } stopEglSurfaceLocked(); stopEglContextLocked(); mShouldReleaseEglContext = false; askedToReleaseEglContext = true; } // Have we lost the EGL context? if (lostEglContext) { stopEglSurfaceLocked(); stopEglContextLocked(); lostEglContext = false; } // When pausing, release the EGL surface: if (pausing && mHaveEglSurface) { if (LOG_SURFACE) { Log.i("GLThread", "releasing EGL surface because paused tid=" + getId()); } stopEglSurfaceLocked(); } // When pausing, optionally release the EGL Context: if (pausing && mHaveEglContext) { GLEnvironment view = mGLSurfaceViewWeakRef.get(); boolean preserveEglContextOnPause = view != null && view.mPreserveEGLContextOnPause; if (!preserveEglContextOnPause) { stopEglContextLocked(); if (LOG_SURFACE) { Log.i("GLThread", "releasing EGL context because paused tid=" + getId()); } } } // Have we lost the SurfaceView surface? if ((!mHasSurface) && (!mWaitingForSurface)) { if (LOG_SURFACE) { Log.i("GLThread", "noticed surfaceView surface lost tid=" + getId()); } if (mHaveEglSurface) { stopEglSurfaceLocked(); } mWaitingForSurface = true; mSurfaceIsBad = false; sGLThreadManager.notifyAll(); } // Have we acquired the surface view surface? if (mHasSurface && mWaitingForSurface) { if (LOG_SURFACE) { Log.i("GLThread", "noticed surfaceView surface acquired tid=" + getId()); } mWaitingForSurface = false; sGLThreadManager.notifyAll(); } if (doRenderNotification) { if (LOG_SURFACE) { Log.i("GLThread", "sending render notification tid=" + getId()); } mWantRenderNotification = false; doRenderNotification = false; mRenderComplete = true; sGLThreadManager.notifyAll(); } // Ready to draw? if (readyToDraw()) { // If we don't have an EGL context, try to acquire one. if (!mHaveEglContext) { if (askedToReleaseEglContext) { askedToReleaseEglContext = false; } else { try { mEglHelper.start(); } catch (RuntimeException t) { sGLThreadManager.releaseEglContextLocked(this); throw t; } mHaveEglContext = true; createEglContext = true; sGLThreadManager.notifyAll(); } } if (mHaveEglContext && !mHaveEglSurface) { mHaveEglSurface = true; createEglSurface = true; createGlInterface = true; sizeChanged = true; } if (mHaveEglSurface) { if (mSizeChanged) { sizeChanged = true; w = mWidth; h = mHeight; mWantRenderNotification = true; if (LOG_SURFACE) { Log.i("GLThread", "noticing that we want render notification tid=" + getId()); } // Destroy and recreate the EGL surface. createEglSurface = true; mSizeChanged = false; } mRequestRender = false; sGLThreadManager.notifyAll(); if (mWantRenderNotification) { wantRenderNotification = true; } break; } } // By design, this is the only place in a GLThread thread where we wait(). if (LOG_THREADS) { Log.i("GLThread", "waiting tid=" + getId() + " mHaveEglContext: " + mHaveEglContext + " mHaveEglSurface: " + mHaveEglSurface + " mFinishedCreatingEglSurface: " + mFinishedCreatingEglSurface + " mPaused: " + mPaused + " mHasSurface: " + mHasSurface + " mSurfaceIsBad: " + mSurfaceIsBad + " mWaitingForSurface: " + mWaitingForSurface + " mWidth: " + mWidth + " mHeight: " + mHeight + " mRequestRender: " + mRequestRender + " mRenderMode: " + mRenderMode); } sGLThreadManager.wait(); } } // end of synchronized(sGLThreadManager) if (event != null) { event.run(); event = null; continue; } if (createEglSurface) { if (LOG_SURFACE) { Log.w("GLThread", "egl createSurface"); } if (mEglHelper.createSurface()) { synchronized (sGLThreadManager) { mFinishedCreatingEglSurface = true; sGLThreadManager.notifyAll(); } } else { synchronized (sGLThreadManager) { mFinishedCreatingEglSurface = true; mSurfaceIsBad = true; sGLThreadManager.notifyAll(); } continue; } createEglSurface = false; } if (createGlInterface) { gl = (GL10) mEglHelper.createGL(); createGlInterface = false; } if (createEglContext) { if (LOG_RENDERER) { Log.w("GLThread", "onSurfaceCreated"); } GLEnvironment view = mGLSurfaceViewWeakRef.get(); if (view != null) { view.mRenderer.onSurfaceCreated(gl, mEglHelper.mEglConfig); } createEglContext = false; } if (sizeChanged) { if (LOG_RENDERER) { Log.w("GLThread", "onSurfaceChanged(" + w + ", " + h + ")"); } GLEnvironment view = mGLSurfaceViewWeakRef.get(); if (view != null) { view.mRenderer.onSurfaceChanged(gl, w, h); } sizeChanged = false; } if (LOG_RENDERER_DRAW_FRAME) { Log.w("GLThread", "onDrawFrame tid=" + getId()); } { GLEnvironment view = mGLSurfaceViewWeakRef.get(); if (view != null) { view.mRenderer.onDrawFrame(gl); } } int swapError = mEglHelper.swap(); switch (swapError) { case EGL10.EGL_SUCCESS: break; case EGL11.EGL_CONTEXT_LOST: if (LOG_SURFACE) { Log.i("GLThread", "egl context lost tid=" + getId()); } lostEglContext = true; break; default: // Other errors typically mean that the current surface is bad, // probably because the SurfaceView surface has been destroyed, // but we haven't been notified yet. // Log the error to help developers understand why rendering stopped. EglHelper.logEglErrorAsWarning("GLThread", "eglSwapBuffers", swapError); synchronized (sGLThreadManager) { mSurfaceIsBad = true; sGLThreadManager.notifyAll(); } break; } if (wantRenderNotification) { doRenderNotification = true; wantRenderNotification = false; } } } finally { /* * clean-up everything... */ synchronized (sGLThreadManager) { stopEglSurfaceLocked(); stopEglContextLocked(); } } } public boolean ableToDraw() { return mHaveEglContext && mHaveEglSurface && readyToDraw(); } private boolean readyToDraw() { return (!mPaused) && mHasSurface && (!mSurfaceIsBad) && (mWidth > 0) && (mHeight > 0) && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY)); } public int getRenderMode() { synchronized (sGLThreadManager) { return mRenderMode; } } public void setRenderMode(int renderMode) { if (!((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY))) { throw new IllegalArgumentException("renderMode"); } synchronized (sGLThreadManager) { mRenderMode = renderMode; sGLThreadManager.notifyAll(); } } public void requestRender() { synchronized (sGLThreadManager) { mRequestRender = true; sGLThreadManager.notifyAll(); } } public void requestRenderAndWait() { synchronized (sGLThreadManager) { // If we are already on the GL thread, this means a client callback // has caused reentrancy, for example via updating the SurfaceView parameters. // We will return to the client rendering code, so here we don't need to // do anything. if (Thread.currentThread() == this) { return; } mWantRenderNotification = true; mRequestRender = true; mRenderComplete = false; sGLThreadManager.notifyAll(); while (!mExited && !mPaused && !mRenderComplete && ableToDraw()) { try { sGLThreadManager.wait(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } } public void surfaceCreated() { synchronized (sGLThreadManager) { if (LOG_THREADS) { Log.i("GLThread", "surfaceCreated tid=" + getId()); } mHasSurface = true; mFinishedCreatingEglSurface = false; sGLThreadManager.notifyAll(); while (mWaitingForSurface && !mFinishedCreatingEglSurface && !mExited) { try { sGLThreadManager.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } public void surfaceDestroyed() { synchronized (sGLThreadManager) { if (LOG_THREADS) { Log.i("GLThread", "surfaceDestroyed tid=" + getId()); } mHasSurface = false; sGLThreadManager.notifyAll(); while ((!mWaitingForSurface) && (!mExited)) { try { sGLThreadManager.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } public void onPause() { synchronized (sGLThreadManager) { if (LOG_PAUSE_RESUME) { Log.i("GLThread", "onPause tid=" + getId()); } mRequestPaused = true; sGLThreadManager.notifyAll(); while ((!mExited) && (!mPaused)) { if (LOG_PAUSE_RESUME) { Log.i("Main thread", "onPause waiting for mPaused."); } try { sGLThreadManager.wait(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } } public void onResume() { synchronized (sGLThreadManager) { if (LOG_PAUSE_RESUME) { Log.i("GLThread", "onResume tid=" + getId()); } mRequestPaused = false; mRequestRender = true; mRenderComplete = false; sGLThreadManager.notifyAll(); while ((!mExited) && mPaused && (!mRenderComplete)) { if (LOG_PAUSE_RESUME) { Log.i("Main thread", "onResume waiting for !mPaused."); } try { sGLThreadManager.wait(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } } public void onWindowResize(int w, int h) { synchronized (sGLThreadManager) { mWidth = w; mHeight = h; mSizeChanged = true; mRequestRender = true; mRenderComplete = false; // If we are already on the GL thread, this means a client callback // has caused reentrancy, for example via updating the SurfaceView parameters. // We need to process the size change eventually though and update our EGLSurface. // So we set the parameters and return so they can be processed on our // next iteration. if (Thread.currentThread() == this) { return; } sGLThreadManager.notifyAll(); // Wait for thread to react to resize and render a frame while (!mExited && !mPaused && !mRenderComplete && ableToDraw()) { if (LOG_SURFACE) { Log.i("Main thread", "onWindowResize waiting for render complete from tid=" + getId()); } try { sGLThreadManager.wait(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized (sGLThreadManager) { mShouldExit = true; sGLThreadManager.notifyAll(); while (!mExited) { try { sGLThreadManager.wait(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } } // End of member variables protected by the sGLThreadManager monitor. public void requestReleaseEglContextLocked() { mShouldReleaseEglContext = true; sGLThreadManager.notifyAll(); } /** * Queue an "event" to be run on the GL rendering thread. * * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { if (r == null) { throw new IllegalArgumentException("r must not be null"); } synchronized (sGLThreadManager) { mEventQueue.add(r); sGLThreadManager.notifyAll(); } } } static class LogWriter extends Writer { private StringBuilder mBuilder = new StringBuilder(); @Override public void close() { flushBuilder(); } @Override public void flush() { flushBuilder(); } @Override public void write(char[] buf, int offset, int count) { for (int i = 0; i < count; i++) { char c = buf[offset + i]; if (c == '\n') { flushBuilder(); } else { mBuilder.append(c); } } } private void flushBuilder() { if (mBuilder.length() > 0) { Log.v("GLSurfaceView", mBuilder.toString()); mBuilder.delete(0, mBuilder.length()); } } } private static class GLThreadManager { private static String TAG = "GLThreadManager"; public synchronized void threadExiting(GLThread thread) { if (LOG_THREADS) { Log.i("GLThread", "exiting tid=" + thread.getId()); } thread.mExited = true; notifyAll(); } /* * Releases the EGL context. Requires that we are already in the * sGLThreadManager monitor when this is called. */ public void releaseEglContextLocked(GLThread thread) { notifyAll(); } } private class DefaultContextFactory implements EGLContextFactory { private int EGL_CONTEXT_CLIENT_VERSION = 0x3098; public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig config) { int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, mEGLContextClientVersion, EGL10.EGL_NONE}; return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT, mEGLContextClientVersion != 0 ? attrib_list : null); } public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) { if (!egl.eglDestroyContext(display, context)) { Log.e("DefaultContextFactory", "display:" + display + " context: " + context); if (LOG_THREADS) { Log.i("DefaultContextFactory", "tid=" + Thread.currentThread().getId()); } EglHelper.throwEglException("eglDestroyContex", egl.eglGetError()); } } } private abstract class BaseConfigChooser implements EGLConfigChooser { protected int[] mConfigSpec; public BaseConfigChooser(int[] configSpec) { mConfigSpec = filterConfigSpec(configSpec); } public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { int[] num_config = new int[1]; if (!egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config)) { throw new IllegalArgumentException("eglChooseConfig failed"); } int numConfigs = num_config[0]; if (numConfigs <= 0) { throw new IllegalArgumentException( "No configs match configSpec"); } EGLConfig[] configs = new EGLConfig[numConfigs]; if (!egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs, num_config)) { throw new IllegalArgumentException("eglChooseConfig#2 failed"); } EGLConfig config = chooseConfig(egl, display, configs); if (config == null) { throw new IllegalArgumentException("No config chosen"); } return config; } abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs); private int[] filterConfigSpec(int[] configSpec) { if (mEGLContextClientVersion != 2 && mEGLContextClientVersion != 3) { return configSpec; } /* We know none of the subclasses define EGL_RENDERABLE_TYPE. * And we know the configSpec is well formed. */ int len = configSpec.length; int[] newConfigSpec = new int[len + 2]; System.arraycopy(configSpec, 0, newConfigSpec, 0, len - 1); newConfigSpec[len - 1] = EGL10.EGL_RENDERABLE_TYPE; if (mEGLContextClientVersion == 2) { newConfigSpec[len] = EGL14.EGL_OPENGL_ES2_BIT; /* EGL_OPENGL_ES2_BIT */ } else { newConfigSpec[len] = EGLExt.EGL_OPENGL_ES3_BIT_KHR; /* EGL_OPENGL_ES3_BIT_KHR */ } newConfigSpec[len + 1] = EGL10.EGL_NONE; return newConfigSpec; } } private class ComponentSizeChooser extends BaseConfigChooser { // Subclasses can adjust these values: protected int mRedSize; protected int mGreenSize; protected int mBlueSize; protected int mAlphaSize; protected int mDepthSize; protected int mStencilSize; private int[] mValue; public ComponentSizeChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) { super(new int[]{ EGL10.EGL_RED_SIZE, redSize, EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE, blueSize, EGL10.EGL_ALPHA_SIZE, alphaSize, EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE, stencilSize, EGL10.EGL_NONE}); mValue = new int[1]; mRedSize = redSize; mGreenSize = greenSize; mBlueSize = blueSize; mAlphaSize = alphaSize; mDepthSize = depthSize; mStencilSize = stencilSize; } @Override public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) { for (EGLConfig config : configs) { int d = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); int s = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); if ((d >= mDepthSize) && (s >= mStencilSize)) { int r = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0); int g = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0); int b = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); int a = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); if ((r == mRedSize) && (g == mGreenSize) && (b == mBlueSize) && (a == mAlphaSize)) { return config; } } } return null; } private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) { if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { return mValue[0]; } return defaultValue; } } private class SimpleEGLConfigChooser extends ComponentSizeChooser { public SimpleEGLConfigChooser(boolean withDepthBuffer) { super(8, 8, 8, 0, withDepthBuffer ? 16 : 0, 0); } } }
55b7dee0c685ac14c47dc5b3b503de2192c5fa68
38faefe9ac88d887cefc32cd4a1f727499e58748
/src/org/yangjiesleep/storesys/MenuDemo.java
257b61b7eacb39b2997ac449007ee46c4342aa2b
[ "Apache-2.0" ]
permissive
yongjj/StoreManagementSystem
679bf79fdb5b0fd244304e701b0c824e10926c92
78d655ee0beaacc14d042226392369c4c8ab311d
refs/heads/master
2021-01-09T21:49:00.470998
2015-10-04T13:42:09
2015-10-04T13:42:09
43,637,574
0
1
null
null
null
null
GB18030
Java
false
false
12,526
java
package org.yangjiesleep.storesys; import tian.biye.R; import android.app.TabActivity; import android.content.Intent; import android.graphics.Color; import android.opengl.Visibility; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.TabHost; /** * 主菜单页面 * @author j * */ public class MenuDemo extends TabActivity { /** * 添加用户键 */ private Button tianjia1; /** * 修改用户键 */ private Button xiugai1; /** * 删除用户键 */ private Button shanchu1; /** * 查询用户键 */ private Button chaxun1; /** * 添加商品键 */ private Button tianjia2; /** * 修改商品键 */ private Button xiugai2; /** * 删除商品键 */ private Button shanchu2; /** * 查询商品键 */ private Button chaxun2; /** * 添加供应商键 */ private Button tianjia3; /** * 修改供应商键 */ private Button xiugai3; /** * 删除供应商键 */ private Button shanchu3; /** * 查询供应商键 */ private Button chaxun3; /** * 添加入库键 */ private Button tianjia4; /** * 修改入库键 */ private Button xiugai4; /** * 删除入库键 */ private Button shanchu4; /** * 查询入库键 */ private Button chaxun4; /** * 添加出库键 */ private Button tianjia5; /** * 修改出库键 */ private Button xiugai5; /** * 删除出库键 */ private Button shanchu5; /** * 查询出库键 */ private Button chaxun5; /** * 用户管理键 */ private Button yonghu; /** * 修改密码键 */ private Button mima; String names=null; protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); TabHost tab=getTabHost(); tab.setPadding(0, -20, 0, 0); tab.setDrawingCacheBackgroundColor(Color.BLUE); LayoutInflater inf=getLayoutInflater(); inf.inflate(R.layout.menudemo, tab.getTabContentView()); Bundle name=getIntent().getExtras(); names=name.getString("username"); System.out.println(names); /** * 所有按钮初始化 */ tianjia1=(Button) findViewById(R.id.tianjia1); xiugai1=(Button) findViewById(R.id.xiugai1); shanchu1=(Button) findViewById(R.id.shanchu1); chaxun1=(Button) findViewById(R.id.chaxun1); tianjia2=(Button) findViewById(R.id.tianjia2); xiugai2=(Button) findViewById(R.id.xiugai2); shanchu2=(Button) findViewById(R.id.shanchu2); chaxun2=(Button) findViewById(R.id.chaxun2); tianjia3=(Button) findViewById(R.id.tianjia3); xiugai3=(Button) findViewById(R.id.xiugai3); shanchu3=(Button) findViewById(R.id.shanchu3); chaxun3=(Button) findViewById(R.id.chaxun3); tianjia4=(Button) findViewById(R.id.tianjia4); xiugai4=(Button) findViewById(R.id.xiugai4); shanchu4=(Button) findViewById(R.id.shanchu4); chaxun4=(Button) findViewById(R.id.chaxun4); tianjia5=(Button) findViewById(R.id.tianjia5); xiugai5=(Button) findViewById(R.id.xiugai5); shanchu5=(Button) findViewById(R.id.shanchu5); chaxun5=(Button) findViewById(R.id.chaxun5); yonghu=(Button) findViewById(R.id.yonghu); mima=(Button) findViewById(R.id.mima); if(!names.equals("ceshi")){ System.out.println("111111111111111111"); yonghu.setVisibility(View.INVISIBLE);} /** * tabhost.tabspec创建 */ final TabHost.TabSpec tabs1 = tab.newTabSpec("基本信息"); tabs1.setContent(R.id.li1); tabs1.setIndicator("基本信息", null); final TabHost.TabSpec tabs2 = tab.newTabSpec("库存管理"); tabs2.setContent(R.id.li2); tabs2.setIndicator("库存管理", null); final TabHost.TabSpec tabs3 = tab.newTabSpec("信息查询"); tabs3.setContent(R.id.li3); tabs3.setIndicator("信息查询", null); final TabHost.TabSpec tabs4 = tab.newTabSpec("关于"); tabs4.setContent(R.id.li4); tabs4.setIndicator("关于", null); final TabHost.TabSpec tabs5 = tab.newTabSpec("用户管理"); tabs5.setContent(R.id.li5); tabs5.setIndicator("用户管理", null); tab.addTab(tabs1); tab.addTab(tabs2); tab.addTab(tabs3); tab.addTab(tabs5); tab.addTab(tabs4); } /** * 商品信息按钮监听 * @param v */ public void onshangpin(View v){ tianjia1.setVisibility(View.VISIBLE); xiugai1.setVisibility(View.VISIBLE); shanchu1.setVisibility(View.VISIBLE); chaxun1.setVisibility(View.VISIBLE); tianjia2.setVisibility(View.INVISIBLE); xiugai2.setVisibility(View.INVISIBLE); shanchu2.setVisibility(View.INVISIBLE); chaxun2.setVisibility(View.INVISIBLE); tianjia3.setVisibility(View.INVISIBLE); xiugai3.setVisibility(View.INVISIBLE); shanchu3.setVisibility(View.INVISIBLE); chaxun3.setVisibility(View.INVISIBLE); } /** * 供应商信息按钮监听 * @param v */ public void ongongyingshang(View v){ tianjia3.setVisibility(View.VISIBLE); xiugai3.setVisibility(View.VISIBLE); shanchu3.setVisibility(View.VISIBLE); chaxun3.setVisibility(View.VISIBLE); tianjia2.setVisibility(View.INVISIBLE); xiugai2.setVisibility(View.INVISIBLE); shanchu2.setVisibility(View.INVISIBLE); chaxun2.setVisibility(View.INVISIBLE); tianjia1.setVisibility(View.INVISIBLE); xiugai1.setVisibility(View.INVISIBLE); shanchu1.setVisibility(View.INVISIBLE); chaxun1.setVisibility(View.INVISIBLE); } /** * 客户信息按钮监听 * @param v */ public void onkehu(View v){ tianjia2.setVisibility(View.VISIBLE); xiugai2.setVisibility(View.VISIBLE); shanchu2.setVisibility(View.VISIBLE); chaxun2.setVisibility(View.VISIBLE); tianjia1.setVisibility(View.INVISIBLE); xiugai1.setVisibility(View.INVISIBLE); shanchu1.setVisibility(View.INVISIBLE); chaxun1.setVisibility(View.INVISIBLE); tianjia3.setVisibility(View.INVISIBLE); xiugai3.setVisibility(View.INVISIBLE); shanchu3.setVisibility(View.INVISIBLE); chaxun3.setVisibility(View.INVISIBLE); } /** * 商品入库信息按钮监听 * @param v */ public void onruku(View v){ tianjia4.setVisibility(View.VISIBLE); xiugai4.setVisibility(View.VISIBLE); shanchu4.setVisibility(View.VISIBLE); chaxun4.setVisibility(View.VISIBLE); tianjia5.setVisibility(View.INVISIBLE); xiugai5.setVisibility(View.INVISIBLE); shanchu5.setVisibility(View.INVISIBLE); chaxun5.setVisibility(View.INVISIBLE); } /** * 商品出库信息按钮监听 * @param v */ public void onchuku(View v){ tianjia5.setVisibility(View.VISIBLE); xiugai5.setVisibility(View.VISIBLE); shanchu5.setVisibility(View.VISIBLE); chaxun5.setVisibility(View.VISIBLE); tianjia4.setVisibility(View.INVISIBLE); xiugai4.setVisibility(View.INVISIBLE); shanchu4.setVisibility(View.INVISIBLE); chaxun4.setVisibility(View.INVISIBLE); } /** * 添加供应商按钮监听 * @param v */ public void tianjiag(View v){ Intent intent=new Intent(); Bundle bundle = new Bundle(); bundle.putString("username",names); intent.putExtras(bundle); intent.setClass(getApplicationContext(), Tianjiag.class); startActivity(intent); } /** * 查询供应商按钮监听 * @param v */ public void chaxung(View v){ Intent intent=new Intent(); Bundle bundle = new Bundle(); bundle.putString("username",names); intent.putExtras(bundle); intent.setClass(getApplicationContext(), Chaxung.class); startActivity(intent); } /** * 添加入库信息按钮监听 * @param v */ public void tianjiar(View v){ Intent intent=new Intent(); Bundle bundle = new Bundle(); bundle.putString("username",names); intent.putExtras(bundle); intent.setClass(getApplicationContext(), Tianjiar.class); startActivity(intent); } /** * 查询入库信息按钮监听 * @param v */ public void chaxunruku(View v){ Intent intent=new Intent(); Bundle bundle = new Bundle(); bundle.putString("username",names); intent.putExtras(bundle); intent.setClass(getApplicationContext(), Chaxunr.class); startActivity(intent); } /** * 添加商品信息按钮监听 * @param v */ public void ontianjias(View v){ Intent intent=new Intent(); Bundle bundle = new Bundle(); bundle.putString("username",names); intent.putExtras(bundle); intent.setClass(getApplicationContext(), Tianjias.class); startActivity(intent); } /** * 添加客户信息按钮监听 * @param v */ public void tianjiak(View v){ Intent intent=new Intent(); Bundle bundle = new Bundle(); bundle.putString("username",names); intent.putExtras(bundle); intent.setClass(getApplicationContext(), Tianjiak.class); startActivity(intent); } /** * 查询客户信息按钮监听 * @param v */ public void chaxunk(View v){ Intent intent=new Intent(); Bundle bundle = new Bundle(); bundle.putString("username",names); intent.putExtras(bundle); intent.setClass(getApplicationContext(), Chaxunk.class); startActivity(intent); } /** * 添加出库按钮监听 * @param v */ public void tianjiac(View v){ Intent intent=new Intent(); Bundle bundle = new Bundle(); bundle.putString("username",names); intent.putExtras(bundle); intent.setClass(getApplicationContext(), Tianjiac.class); startActivity(intent); } /** * 查询出库按钮监听 * @param v */ public void chaxunc(View v){ Intent intent=new Intent(); Bundle bundle = new Bundle(); bundle.putString("username",names); intent.putExtras(bundle); intent.setClass(getApplicationContext(), Chaxunc.class); startActivity(intent); } /** * 修改密码按钮监听 * @param v */ public void mima(View v){ Intent intent=new Intent(); Bundle bundle = new Bundle(); bundle.putString("username",names); intent.putExtras(bundle); intent.setClass(getApplicationContext(),Xiugai.class); startActivity(intent); } /** * 用户管理按钮监听 * @param v */ public void yonghu(View v){ Intent intent=new Intent(); Bundle bundle = new Bundle(); bundle.putString("username",names); intent.putExtras(bundle); intent.setClass(getApplicationContext(),Yonghu.class); startActivity(intent); } /** * 删除商品按钮监听 * @param v */ public void shanchus(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Shanchus.class); startActivity(intent); } /** * 删除客户按钮监听 * @param v */ public void shanchuk(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Shanchuk.class); startActivity(intent); } /** * 查询商品按钮监听 * @param v */ public void chaxuns(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Chaxuns.class); startActivity(intent); } /** * 删除供应商按钮监听 * @param v */ public void shanchug(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Shanchug.class); startActivity(intent); } /** * 修改商品按钮监听 * @param v */ public void xiugais(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Xiugais.class); startActivity(intent); } /** * 修改客户按钮监听 * @param v */ public void xiugaik(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Xiugaik.class); startActivity(intent); } /** * 修改供应商按钮监听 * @param v */ public void xiugaig(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Xiugaig.class); startActivity(intent); } /** * 删除出库按钮监听 * @param v */ public void shanchuc(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Shanchuc.class); startActivity(intent); } /** * 删除入库按钮监听 * @param v */ public void shanchur(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Shanchur.class); startActivity(intent); } /** * 修改入库按钮监听 * @param v */ public void xiugair(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Xiugair.class); startActivity(intent); } /** * 修改出库按钮监听 * @param v */ public void xiugaic(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Xiugaic.class); startActivity(intent); } /** * 库存信息查询按钮监听 * @param v */ public void kucun(View v){ Intent intent=new Intent(); intent.setClass(MenuDemo.this, Kucun.class); startActivity(intent); } }
27d5d4c2bf453d9fd8683deca64040c020612403
0b97c83f90f92ea0e5eaf0386b7ce77cc2b4f2ae
/jar/src/main/java/gogui/random/strategy/OnLineGenerator.java
39bb180f872346a52418d67f8cb2350ebfde6990
[]
no_license
enedhilien/goGui_java
a907f45b5f68302b6dc748881a4b6a67dc528f20
3cf2cc0b99041feaf0c3993b738a74d7ac3aca1c
refs/heads/master
2021-01-14T09:54:52.618541
2015-01-06T02:37:56
2015-01-06T02:37:56
27,838,437
0
0
null
null
null
null
UTF-8
Java
false
false
1,327
java
package gogui.random.strategy; import gogui.GeoList; import gogui.Line; import gogui.Point; import gogui.random.PointsGenerator; import java.util.List; /** * Generates points on line */ public class OnLineGenerator implements PointGeneratorStrategy { private static Line line; public OnLineGenerator(Line line) { this.line = line; } public static OnLineGenerator onLine(Line line) { OnLineGenerator.line = line; return new OnLineGenerator(line); } @Override public List<Point> generate(int pointsCount) { List<Point> result = new GeoList<>(); double x_min = Math.min(line.getLeftPoint().x, line.getRightPoint().x); double x_max = Math.max(line.getLeftPoint().x, line.getRightPoint().x); double y_min = Math.min(line.getLeftPoint().y, line.getRightPoint().y); double y_max = Math.max(line.getLeftPoint().y, line.getRightPoint().y); for (int i = 0; i < pointsCount; i++) { double x = PointsGenerator.realRandom(x_min, x_max); double y; if (x_min == 0 && x_max == 0) { y = PointsGenerator.realRandom(y_min, y_max); } else { y = line.getY(x); } result.add(new Point(x, y)); } return result; } }
31a9c40fe2342fb198ee3ade13fc25cb59b84da7
e7357909eadd7738034e4426dbed363c92233748
/src/main/java/pl/sda/travel360/domain/Travel.java
55d1f8f8fb259f1c168dd4ce8379744283d6c20d
[]
no_license
MichalKiernicki/SpringTravel360
0546aa16407f030c996bb87cdcb88e9daa166beb
c01a147df2de7c5231aab123992501e762bbd380
refs/heads/master
2023-08-25T12:25:18.195635
2021-10-17T10:11:22
2021-10-17T10:11:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
537
java
package pl.sda.travel360.domain; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.Set; @Data @Builder @NoArgsConstructor @AllArgsConstructor @Entity @Table public class Travel { @Id @GeneratedValue private Long id; private String name; @ManyToOne private Country country; @Column(length = 5000) private String desctription; @ManyToMany private Set<TravelParcitipals> parcitipants; }
600549f64e83aece694821444274dc4996a59776
8a0212db45620e090af21a1d2ff2ed30a4a210f6
/sculptor-maven/sculptor-maven-plugin/src/main/java/org/sculptor/maven/plugin/ScanningOutputStream.java
aeffc409c6e733d6be9043171f5a3e159c23a96b
[ "Apache-2.0" ]
permissive
zhongweijun/sculptor
061a09ef95b2774cf0684ac8b76362638b6a9a45
c29228ba63f50d599d068ab04afe419f051703b9
refs/heads/master
2021-01-16T23:11:00.431455
2013-11-24T00:58:04
2013-11-24T00:58:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,144
java
/* * Copyright 2013 The Sculptor Project Team, including 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.sculptor.maven.plugin; import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; /** * {@link AbstractLogOutputStream} which scans the lines before writing to the * wrapped {@link PrintStream}: For the log level <code>ERROR</code> the line is * logged as an error. * <p> * The lines from logger of class <code>org.sculptor.generator.ext.Helper</code> * are checked for files created or skipped by the code generator. The list of * these {@link File}s can be retrieved by via the corresponding getters. */ public class ScanningOutputStream extends AbstractLogOutputStream { protected static final String LINE_PREFIX_DEBUG = "[DEBUG] "; protected static final String LINE_PREFIX_INFO = "[INFO] "; protected static final String LINE_PREFIX_WARN = "[WARN] "; protected static final String LINE_PREFIX_ERROR = "[ERROR] "; protected static final String LINE_PREFIX_FILE = "[FILE] "; protected static final String LINE_PREFIX_FILE_CREATED = LINE_PREFIX_FILE + "Created file : "; protected static final String LINE_PREFIX_FILE_SKIPPED = LINE_PREFIX_FILE + "Skipped file : "; protected final PrintStream out; private boolean isVerbose; private List<File> createdFiles = new ArrayList<File>(); private List<File> skippedFiles = new ArrayList<File>(); /** * Creates a new output stream for stdout. * * @param out * stdout {@link PrintStream} the scanned line are written to * @param isVerbose * if <code>true</code> then every line is sent to this output stream */ public ScanningOutputStream(PrintStream out, boolean isVerbose) { this(out, isVerbose, false); } /** * Creates a new output stream for stdout or stderr. * * @param out * stdout or stderr {@link PrintStream} the scanned line are written to * @param isVerbose * if <code>true</code> then every line is sent to this output stream * @param isErrorStream * if <code>true</code> then every line sent to this output stream * increases the error count */ public ScanningOutputStream(PrintStream out, boolean isVerbose, boolean isErrorStream) { super(isErrorStream); this.out = out; this.isVerbose = isVerbose; } public List<File> getCreatedFiles() { return createdFiles; } public List<File> getSkippedFiles() { return skippedFiles; } /** * For the log level <code>ERROR</code> the line is logged as an error. The * lines from logger of class <code>org.sculptor.generator.ext.Helper</code> * are checked for files created or skipped by the code generator. */ @Override protected boolean doProcessLine(String line, int level) { if (line.startsWith(LINE_PREFIX_DEBUG)) { if (isVerbose) { out.println(line); } } else if (line.startsWith(LINE_PREFIX_WARN)) { out.println("[WARNING] " + line.substring(LINE_PREFIX_WARN.length())); } else if (line.startsWith(LINE_PREFIX_ERROR)) { out.println(line); return true; } else if (line.startsWith(LINE_PREFIX_FILE)) { if (line.startsWith(LINE_PREFIX_FILE_CREATED)) { createdFiles.add(new File(line.substring(LINE_PREFIX_FILE_CREATED.length()))); } else if (line.startsWith(LINE_PREFIX_FILE_SKIPPED)) { skippedFiles.add(new File(line.substring(LINE_PREFIX_FILE_SKIPPED.length()))); } if (isVerbose) { out.println("[INFO] " + line.substring(LINE_PREFIX_FILE.length())); } } else { out.println(line); } return false; } }
e1a0c107716e51a4199a177a2cf55027c9c41219
f56b576e748a5a1a1c401bdf5b8a099330b7b377
/Netbeans Project/src/server/http/servlet/delete/GetKG.java
7e2e4f1dd12b40c10d26731923160387b9f0b55e
[]
no_license
Lolikitty/Weight-Lose
85ba2e02b51cff3cfa4ee7e54f1918907e6d2a78
9ae32294befbe730b423d72cb99e297174691e2d
refs/heads/Demonic
2016-08-12T18:30:01.048329
2015-08-13T02:40:18
2015-08-13T02:40:18
28,794,989
0
0
null
null
null
null
UTF-8
Java
false
false
1,531
java
/* * Copyright © 2014 Chenghsi Inc. All rights reserved */ package server.http.servlet.delete; import java.io.IOException; import java.io.PrintWriter; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import server.database.SQL; /** * Last modification time : 2014/11/10 * * @author Loli */ public class GetKG extends HttpServlet { @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType("text/html;charset=UTF-8"); String id = req.getParameter("id"); String sql = "select kg from kg where id='" + id + "' ORDER BY time desc LIMIT 10;"; String msg = ""; ResultSet rs = null; try { rs = new SQL().getData(sql); while (rs.next()) { msg += rs.getString("kg") + ","; } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { System.out.println(ex); } finally { try { if (rs != null) { rs.close(); } } catch (Exception e) { System.out.println("RS : " + e); } } PrintWriter out = res.getWriter(); out.println(msg); } }
caa5e6fa4c2ebade09aa6d8bae64a7fb6d57168b
55aca439e180a9bcf0a36f60320013979905d1e5
/efreight-afbase/src/main/java/com/efreight/afbase/entity/DebitNoteTree.java
d4abcb35fb1e3697aa9301efc85cc4d4a689d017
[]
no_license
zhoudy-github/efreight-cloud
1a8f791f350a37c1f2828985ebc20287199a8027
fc669facfdc909b51779a88575ab4351e275bd25
refs/heads/master
2023-03-18T07:24:18.001404
2021-03-23T06:55:54
2021-03-23T06:55:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
695
java
package com.efreight.afbase.entity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.math.BigDecimal; import java.util.List; @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class DebitNoteTree { private Boolean checkBox = false; private String debitNoteId; private String customerName; private String currency; private BigDecimal amountTaxRate; private Boolean isParent = true; private List<DebitNote> children; private String currencyAmount; private String currencyAmount2; private BigDecimal functionalAmount; private BigDecimal functionalAmountWriteoff; }
152d77caa432d4f5c1f1f27cc615148cbf3757a8
ce874d2203d5d82507b72a71289a3e1e4b44c338
/src/main/java/net/nokok/azm/ClassReader.java
dc4c843b7a35e9a2220c389f6eb4a7331b89cf81
[]
no_license
nokok/azm
932295b8a3258b808daeb6f29dadcf417963a7b9
2bf6419e4587a2bd47e9891d010736b61ef45123
refs/heads/master
2021-04-18T20:35:23.105352
2018-04-06T15:18:28
2018-04-06T15:18:28
126,351,496
0
0
null
null
null
null
UTF-8
Java
false
false
175,730
java
// ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. package net.nokok.azm; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * A parser to make a {@link ClassVisitor} visit a ClassFile structure, as defined in the Java * Virtual Machine Specification (JVMS). This class parses the ClassFile content and calls the * appropriate visit methods of a given {@link ClassVisitor} for each field, method and bytecode * instruction encountered. * * @author Eric Bruneton * @author Eugene Kuleshov * @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html">JVMS 4</a> */ public class ClassReader { /** * A flag to skip the Code attributes. If this flag is set the Code attributes are neither parsed * nor visited. */ public static final int SKIP_CODE = 1; /** * A flag to skip the SourceFile, SourceDebugExtension, LocalVariableTable, LocalVariableTypeTable * and LineNumberTable attributes. If this flag is set these attributes are neither parsed nor * visited (i.e. {@link ClassVisitor#visitSource}, {@link MethodVisitor#visitLocalVariable} and * {@link MethodVisitor#visitLineNumber} are not called). */ public static final int SKIP_DEBUG = 2; /** * A flag to skip the StackMap and StackMapTable attributes. If this flag is set these attributes * are neither parsed nor visited (i.e. {@link MethodVisitor#visitFrame} is not called). This flag * is useful when the {@link ClassWriter#COMPUTE_FRAMES} option is used: it avoids visiting frames * that will be ignored and recomputed from scratch. */ public static final int SKIP_FRAMES = 4; /** * A flag to expand the stack map frames. By default stack map frames are visited in their * original format (i.e. "expanded" for classes whose version is less than V1_6, and "compressed" * for the other classes). If this flag is set, stack map frames are always visited in expanded * format (this option adds a decompression/compression step in ClassReader and ClassWriter which * degrades performance quite a lot). */ public static final int EXPAND_FRAMES = 8; /** * A flag to expand the ASM specific instructions into an equivalent sequence of standard bytecode * instructions. When resolving a forward jump it may happen that the signed 2 bytes offset * reserved for it is not sufficient to store the bytecode offset. In this case the jump * instruction is replaced with a temporary ASM specific instruction using an unsigned 2 bytes * offset (see {@link Label#resolve}). This internal flag is used to re-read classes containing * such instructions, in order to replace them with standard instructions. In addition, when this * flag is used, goto_w and jsr_w are <i>not</i> converted into goto and jsr, to make sure that * infinite loops where a goto_w is replaced with a goto in ClassReader and converted back to a * goto_w in ClassWriter cannot occur. */ static final int EXPAND_ASM_INSNS = 256; /** * A byte array containing the JVMS ClassFile structure to be parsed. <i>The content of this array * must not be modified. This field is intended for {@link Attribute} sub classes, and is normally * not needed by class visitors.</i> * <p> * <p>NOTE: the ClassFile structure can start at any offset within this array, i.e. it does not * necessarily start at offset 0. Use {@link #getItem} and {@link #header} to get correct * ClassFile element offsets within this byte array. */ public final byte[] b; /** * The offset in bytes, in {@link #b}, of each cp_info entry of the ClassFile's constant_pool * array, <i>plus one</i>. In other words, the offset of constant pool entry i is given by * cpInfoOffsets[i] - 1, i.e. its cp_info's tag field is given by b[cpInfoOffsets[i] - 1]. */ private final int[] cpInfoOffsets; /** * The String objects corresponding to the CONSTANT_Utf8 items. This cache avoids multiple parsing * of a given CONSTANT_Utf8 constant pool item. */ private final String[] constantUtf8Values; /** * A conservative estimate of the maximum length of the strings contained in the constant pool of * the class. */ private final int maxStringLength; /** * The offset in bytes, in {@link #b}, of the ClassFile's access_flags field. */ public final int header; // ----------------------------------------------------------------------------------------------- // Constructors // ----------------------------------------------------------------------------------------------- /** * Constructs a new {@link ClassReader} object. * * @param classFile the JVMS ClassFile structure to be read. */ public ClassReader(final byte[] classFile) { this(classFile, 0, classFile.length); } /** * Constructs a new {@link ClassReader} object. * * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read. * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read. * @param classFileLength the length in bytes of the ClassFile to be read. */ public ClassReader( final byte[] classFileBuffer, final int classFileOffset, final int classFileLength) { this(classFileBuffer, classFileOffset, /* checkClassVersion = */ true); } /** * Constructs a new {@link ClassReader} object. <i>This internal constructor must not be exposed * as a public API</i>. * * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read. * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read. * @param checkClassVersion whether to check the class version or not. */ ClassReader( final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion) { this.b = classFileBuffer; // Check the class' major_version. This field is after the magic and minor_version fields, which // use 4 and 2 bytes respectively. if (checkClassVersion && readShort(classFileOffset + 6) > Opcodes.V10) { throw new IllegalArgumentException( "Unsupported class file major version " + readShort(classFileOffset + 6)); } // Create the constant pool arrays. The constant_pool_count field is after the magic, // minor_version and major_version fields, which use 4, 2 and 2 bytes respectively. int constantPoolCount = readUnsignedShort(classFileOffset + 8); cpInfoOffsets = new int[constantPoolCount]; constantUtf8Values = new String[constantPoolCount]; // Compute the offset of each constant pool entry, as well as a conservative estimate of the // maximum length of the constant pool strings. The first constant pool entry is after the // magic, minor_version, major_version and constant_pool_count fields, which use 4, 2, 2 and 2 // bytes respectively. int currentCpInfoIndex = 1; int currentCpInfoOffset = classFileOffset + 10; int currentMaxStringLength = 0; // The offset of the other entries depend on the total size of all the previous entries. while (currentCpInfoIndex < constantPoolCount) { cpInfoOffsets[currentCpInfoIndex++] = currentCpInfoOffset + 1; int cpInfoSize; switch (classFileBuffer[currentCpInfoOffset]) { case Symbol.CONSTANT_FIELDREF_TAG: case Symbol.CONSTANT_METHODREF_TAG: case Symbol.CONSTANT_INTERFACE_METHODREF_TAG: case Symbol.CONSTANT_INTEGER_TAG: case Symbol.CONSTANT_FLOAT_TAG: case Symbol.CONSTANT_NAME_AND_TYPE_TAG: case Symbol.CONSTANT_INVOKE_DYNAMIC_TAG: cpInfoSize = 5; break; case Symbol.CONSTANT_LONG_TAG: case Symbol.CONSTANT_DOUBLE_TAG: cpInfoSize = 9; currentCpInfoIndex++; break; case Symbol.CONSTANT_UTF8_TAG: cpInfoSize = 3 + readUnsignedShort(currentCpInfoOffset + 1); if (cpInfoSize > currentMaxStringLength) { // The size in bytes of this CONSTANT_Utf8 structure provides a conservative estimate // of the length in characters of the corresponding string, and is much cheaper to // compute than this exact length. currentMaxStringLength = cpInfoSize; } break; case Symbol.CONSTANT_METHOD_HANDLE_TAG: cpInfoSize = 4; break; case Symbol.CONSTANT_CLASS_TAG: case Symbol.CONSTANT_STRING_TAG: case Symbol.CONSTANT_METHOD_TYPE_TAG: case Symbol.CONSTANT_PACKAGE_TAG: case Symbol.CONSTANT_MODULE_TAG: cpInfoSize = 3; break; default: throw new IllegalArgumentException(); } currentCpInfoOffset += cpInfoSize; } this.maxStringLength = currentMaxStringLength; // The Classfile's access_flags field is just after the last constant pool entry. this.header = currentCpInfoOffset; } /** * Constructs a new {@link ClassReader} object. * * @param inputStream an input stream of the JVMS ClassFile structure to be read. This input * stream must contain nothing more than the ClassFile structure itself. It is read from its * current position to its end. * @throws IOException if a problem occurs during reading. */ public ClassReader(final InputStream inputStream) throws IOException { this(readStream(inputStream, false)); } /** * Constructs a new {@link ClassReader} object. * * @param className the fully qualified name of the class to be read. The ClassFile structure is * retrieved with the current class loader's {@link ClassLoader#getSystemResourceAsStream}. * @throws IOException if an exception occurs during reading. */ public ClassReader(final String className) throws IOException { this( readStream( ClassLoader.getSystemResourceAsStream(className.replace('.', '/') + ".class"), true)); } /** * Reads the given input stream and returns its content as a byte array. * * @param inputStream an input stream. * @param close true to close the input stream after reading. * @return the content of the given input stream. * @throws IOException if a problem occurs during reading. */ private static byte[] readStream(final InputStream inputStream, final boolean close) throws IOException { if (inputStream == null) { throw new IOException("Class not found"); } try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] data = new byte[inputStream.available()]; int bytesRead; while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) { outputStream.write(data, 0, bytesRead); } outputStream.flush(); return outputStream.toByteArray(); } finally { if (close) { inputStream.close(); } } } // ----------------------------------------------------------------------------------------------- // Accessors // ----------------------------------------------------------------------------------------------- /** * Returns the class's access flags (see {@link Opcodes}). This value may not reflect Deprecated * and Synthetic flags when bytecode is before 1.5 and those flags are represented by attributes. * * @return the class access flags. * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public int getAccess() { return readUnsignedShort(header); } /** * Returns the internal name of the class (see {@link Type#getInternalName()}). * * @return the internal class name. * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public String getClassName() { // this_class is just after the access_flags field (using 2 bytes). return readClass(header + 2, new char[maxStringLength]); } /** * Returns the internal of name of the super class (see {@link Type#getInternalName()}). For * interfaces, the super class is {@link Object}. * * @return the internal name of the super class, or <tt>null</tt> for {@link Object} class. * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public String getSuperName() { // super_class is after the access_flags and this_class fields (2 bytes each). return readClass(header + 4, new char[maxStringLength]); } /** * Returns the internal names of the implemented interfaces (see {@link Type#getInternalName()}). * * @return the internal names of the directly implemented interfaces. Inherited implemented * interfaces are not returned. * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public String[] getInterfaces() { // interfaces_count is after the access_flags, this_class and super_class fields (2 bytes each). int currentOffset = header + 6; int interfacesCount = readUnsignedShort(currentOffset); String[] interfaces = new String[interfacesCount]; if (interfacesCount > 0) { char[] charBuffer = new char[maxStringLength]; for (int i = 0; i < interfacesCount; ++i) { currentOffset += 2; interfaces[i] = readClass(currentOffset, charBuffer); } } return interfaces; } // ----------------------------------------------------------------------------------------------- // Public methods // ----------------------------------------------------------------------------------------------- /** * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this * {@link ClassReader}. * * @param classVisitor the visitor that must visit this class. * @param parsingOptions the options to use to parse this class. One or more of {@link * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}. */ public void accept(final ClassVisitor classVisitor, final int parsingOptions) { accept(classVisitor, new Attribute[0], parsingOptions); } /** * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this * {@link ClassReader}. * * @param classVisitor the visitor that must visit this class. * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of * the class. Any attribute whose type is not equal to the type of one the prototypes will not * be parsed: its byte array value will be passed unchanged to the ClassWriter. <i>This may * corrupt it if this value contains references to the constant pool, or has syntactic or * semantic links with a class element that has been transformed by a class adapter between * the reader and the writer</i>. * @param parsingOptions the options to use to parse this class. One or more of {@link * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}. */ public void accept( final ClassVisitor classVisitor, final Attribute[] attributePrototypes, final int parsingOptions) { Context context = new Context(); context.attributePrototypes = attributePrototypes; context.parsingOptions = parsingOptions; context.charBuffer = new char[maxStringLength]; // Read the access_flags, this_class, super_class, interface_count and interfaces fields. char[] charBuffer = context.charBuffer; int currentOffset = header; int accessFlags = readUnsignedShort(currentOffset); String thisClass = readClass(currentOffset + 2, charBuffer); String superClass = readClass(currentOffset + 4, charBuffer); String[] interfaces = new String[readUnsignedShort(currentOffset + 6)]; currentOffset += 8; for (int i = 0; i < interfaces.length; ++i) { interfaces[i] = readClass(currentOffset, charBuffer); currentOffset += 2; } // Read the class attributes (the variables are ordered as in Section 4.7 of the JVMS). // Attribute offsets exclude the attribute_name_index and attribute_length fields. // - The offset of the InnerClasses attribute, or 0. int innerClassesOffset = 0; // - The offset of the EnclosingMethod attribute, or 0. int enclosingMethodOffset = 0; // - The string corresponding to the Signature attribute, or null. String signature = null; // - The string corresponding to the SourceFile attribute, or null. String sourceFile = null; // - The string corresponding to the SourceDebugExtension attribute, or null. String sourceDebugExtension = null; // - The offset of the RuntimeVisibleAnnotations attribute, or 0. int runtimeVisibleAnnotationsOffset = 0; // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. int runtimeInvisibleAnnotationsOffset = 0; // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. int runtimeVisibleTypeAnnotationsOffset = 0; // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. int runtimeInvisibleTypeAnnotationsOffset = 0; // - The offset of the Module attribute, or 0. int moduleOffset = 0; // - The offset of the ModulePackages attribute, or 0. int modulePackagesOffset = 0; // - The string corresponding to the ModuleMainClass attribute, or null. String moduleMainClass = null; // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). // This list in the <i>reverse order</i> or their order in the ClassFile structure. Attribute attributes = null; int currentAttributeOffset = getFirstAttributeOffset(); for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) { // Read the attribute_info's attribute_name and attribute_length fields. String attributeName = readUTF8(currentAttributeOffset, charBuffer); int attributeLength = readInt(currentAttributeOffset + 2); currentAttributeOffset += 6; // The tests are sorted in decreasing frequency order (based on frequencies observed on // typical classes). if (Constants.SOURCE_FILE.equals(attributeName)) { sourceFile = readUTF8(currentAttributeOffset, charBuffer); } else if (Constants.INNER_CLASSES.equals(attributeName)) { innerClassesOffset = currentAttributeOffset; } else if (Constants.ENCLOSING_METHOD.equals(attributeName)) { enclosingMethodOffset = currentAttributeOffset; } else if (Constants.SIGNATURE.equals(attributeName)) { signature = readUTF8(currentAttributeOffset, charBuffer); } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { runtimeVisibleAnnotationsOffset = currentAttributeOffset; } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { runtimeVisibleTypeAnnotationsOffset = currentAttributeOffset; } else if (Constants.DEPRECATED.equals(attributeName)) { accessFlags |= Opcodes.ACC_DEPRECATED; } else if (Constants.SYNTHETIC.equals(attributeName)) { accessFlags |= Opcodes.ACC_SYNTHETIC; } else if (Constants.SOURCE_DEBUG_EXTENSION.equals(attributeName)) { sourceDebugExtension = readUTF(currentAttributeOffset, attributeLength, new char[attributeLength]); } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { runtimeInvisibleAnnotationsOffset = currentAttributeOffset; } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { runtimeInvisibleTypeAnnotationsOffset = currentAttributeOffset; } else if (Constants.MODULE.equals(attributeName)) { moduleOffset = currentAttributeOffset; } else if (Constants.MODULE_MAIN_CLASS.equals(attributeName)) { moduleMainClass = readClass(currentAttributeOffset, charBuffer); } else if (Constants.MODULE_PACKAGES.equals(attributeName)) { modulePackagesOffset = currentAttributeOffset; } else if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) { // Read the num_bootstrap_methods field and create an array of this size. int[] bootstrapMethodOffsets = new int[readUnsignedShort(currentAttributeOffset)]; // Compute and store the offset of each 'bootstrap_methods' array field entry. int currentBootstrapMethodOffset = currentAttributeOffset + 2; for (int j = 0; j < bootstrapMethodOffsets.length; ++j) { bootstrapMethodOffsets[j] = currentBootstrapMethodOffset; // Skip the bootstrap_method_ref and num_bootstrap_arguments fields (2 bytes each), // as well as the bootstrap_arguments array field (of size num_bootstrap_arguments * 2). currentBootstrapMethodOffset += 4 + readUnsignedShort(currentBootstrapMethodOffset + 2) * 2; } context.bootstrapMethodOffsets = bootstrapMethodOffsets; } else { Attribute attribute = readAttribute( attributePrototypes, attributeName, currentAttributeOffset, attributeLength, charBuffer, -1, null); attribute.nextAttribute = attributes; attributes = attribute; } currentAttributeOffset += attributeLength; } // Visit the class declaration. The minor_version and major_version fields start 6 bytes before // the first constant pool entry, which itself starts at cpInfoOffsets[1] - 1 (by definition). classVisitor.visit( readInt(cpInfoOffsets[1] - 7), accessFlags, thisClass, signature, superClass, interfaces); // Visit the SourceFile and SourceDebugExtenstion attributes. if ((parsingOptions & SKIP_DEBUG) == 0 && (sourceFile != null || sourceDebugExtension != null)) { classVisitor.visitSource(sourceFile, sourceDebugExtension); } // Visit the Module, ModulePackages and ModuleMainClass attributes. if (moduleOffset != 0) { readModule(classVisitor, context, moduleOffset, modulePackagesOffset, moduleMainClass); } // Visit the EnclosingMethod attribute. if (enclosingMethodOffset != 0) { String className = readClass(enclosingMethodOffset, charBuffer); int methodIndex = readUnsignedShort(enclosingMethodOffset + 2); String name = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex], charBuffer); String type = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex] + 2, charBuffer); classVisitor.visitOuterClass(className, name, type); } // Visit the RuntimeVisibleAnnotations attribute. if (runtimeVisibleAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the RuntimeInvisibleAnnotations attribute. if (runtimeInvisibleAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the RuntimeVisibleTypeAnnotations attribute. if (runtimeVisibleTypeAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( classVisitor.visitTypeAnnotation( context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor, /* visible = */ true), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the RuntimeInvisibleTypeAnnotations attribute. if (runtimeInvisibleTypeAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( classVisitor.visitTypeAnnotation( context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor, /* visible = */ false), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the non standard attributes. while (attributes != null) { // Copy and reset the nextAttribute field so that it can also be used in ClassWriter. Attribute nextAttribute = attributes.nextAttribute; attributes.nextAttribute = null; classVisitor.visitAttribute(attributes); attributes = nextAttribute; } // Visit the InnerClasses attribute. if (innerClassesOffset != 0) { int numberOfClasses = readUnsignedShort(innerClassesOffset); int currentClassesOffset = innerClassesOffset + 2; while (numberOfClasses-- > 0) { classVisitor.visitInnerClass( readClass(currentClassesOffset, charBuffer), readClass(currentClassesOffset + 2, charBuffer), readUTF8(currentClassesOffset + 4, charBuffer), readUnsignedShort(currentClassesOffset + 6)); currentClassesOffset += 8; } } // Visit the fields and methods. int fieldsCount = readUnsignedShort(currentOffset); currentOffset += 2; while (fieldsCount-- > 0) { currentOffset = readField(classVisitor, context, currentOffset); } int methodsCount = readUnsignedShort(currentOffset); currentOffset += 2; while (methodsCount-- > 0) { currentOffset = readMethod(classVisitor, context, currentOffset); } // Visit the end of the class. classVisitor.visitEnd(); } // ---------------------------------------------------------------------------------------------- // Methods to parse modules, fields and methods // ---------------------------------------------------------------------------------------------- /** * Reads the module attribute and visit it. * * @param classVisitor the current class visitor * @param context information about the class being parsed. * @param moduleOffset the offset of the Module attribute (excluding the attribute_info's * attribute_name_index and attribute_length fields). * @param modulePackagesOffset the offset of the ModulePackages attribute (excluding the * attribute_info's attribute_name_index and attribute_length fields), or 0. * @param moduleMainClass the string corresponding to the ModuleMainClass attribute, or null. */ private void readModule( final ClassVisitor classVisitor, final Context context, final int moduleOffset, final int modulePackagesOffset, final String moduleMainClass) { char[] buffer = context.charBuffer; // Read the module_name_index, module_flags and module_version_index fields and visit them. int currentOffset = moduleOffset; String moduleName = readModule(currentOffset, buffer); int moduleFlags = readUnsignedShort(currentOffset + 2); String moduleVersion = readUTF8(currentOffset + 4, buffer); currentOffset += 6; ModuleVisitor moduleVisitor = classVisitor.visitModule(moduleName, moduleFlags, moduleVersion); if (moduleVisitor == null) { return; } // Visit the ModuleMainClass attribute. if (moduleMainClass != null) { moduleVisitor.visitMainClass(moduleMainClass); } // Visit the ModulePackages attribute. if (modulePackagesOffset != 0) { int packageCount = readUnsignedShort(modulePackagesOffset); int currentPackageOffset = modulePackagesOffset + 2; while (packageCount-- > 0) { moduleVisitor.visitPackage(readPackage(currentPackageOffset, buffer)); currentPackageOffset += 2; } } // Read the 'requires_count' and 'requires' fields. int requiresCount = readUnsignedShort(currentOffset); currentOffset += 2; while (requiresCount-- > 0) { // Read the requires_index, requires_flags and requires_version fields and visit them. String requires = readModule(currentOffset, buffer); int requiresFlags = readUnsignedShort(currentOffset + 2); String requiresVersion = readUTF8(currentOffset + 4, buffer); currentOffset += 6; moduleVisitor.visitRequire(requires, requiresFlags, requiresVersion); } // Read the 'exports_count' and 'exports' fields. int exportsCount = readUnsignedShort(currentOffset); currentOffset += 2; while (exportsCount-- > 0) { // Read the exports_index, exports_flags, exports_to_count and exports_to_index fields // and visit them. String exports = readPackage(currentOffset, buffer); int exportsFlags = readUnsignedShort(currentOffset + 2); int exportsToCount = readUnsignedShort(currentOffset + 4); currentOffset += 6; String[] exportsTo = null; if (exportsToCount != 0) { exportsTo = new String[exportsToCount]; for (int i = 0; i < exportsToCount; ++i) { exportsTo[i] = readModule(currentOffset, buffer); currentOffset += 2; } } moduleVisitor.visitExport(exports, exportsFlags, exportsTo); } // Reads the 'opens_count' and 'opens' fields. int opensCount = readUnsignedShort(currentOffset); currentOffset += 2; while (opensCount-- > 0) { // Read the opens_index, opens_flags, opens_to_count and opens_to_index fields and visit them. String opens = readPackage(currentOffset, buffer); int opensFlags = readUnsignedShort(currentOffset + 2); int opensToCount = readUnsignedShort(currentOffset + 4); currentOffset += 6; String[] opensTo = null; if (opensToCount != 0) { opensTo = new String[opensToCount]; for (int i = 0; i < opensToCount; ++i) { opensTo[i] = readModule(currentOffset, buffer); currentOffset += 2; } } moduleVisitor.visitOpen(opens, opensFlags, opensTo); } // Read the 'uses_count' and 'uses' fields. int usesCount = readUnsignedShort(currentOffset); currentOffset += 2; while (usesCount-- > 0) { moduleVisitor.visitUse(readClass(currentOffset, buffer)); currentOffset += 2; } // Read the 'provides_count' and 'provides' fields. int providesCount = readUnsignedShort(currentOffset); currentOffset += 2; while (providesCount-- > 0) { // Read the provides_index, provides_with_count and provides_with_index fields and visit them. String provides = readClass(currentOffset, buffer); int providesWithCount = readUnsignedShort(currentOffset + 2); currentOffset += 4; String[] providesWith = new String[providesWithCount]; for (int i = 0; i < providesWithCount; ++i) { providesWith[i] = readClass(currentOffset, buffer); currentOffset += 2; } moduleVisitor.visitProvide(provides, providesWith); } // Visit the end of the module attributes. moduleVisitor.visitEnd(); } /** * Reads a JVMS field_info structure and makes the given visitor visit it. * * @param classVisitor the visitor that must visit the field. * @param context information about the class being parsed. * @param fieldInfoOffset the start offset of the field_info structure. * @return the offset of the first byte following the field_info structure. */ private int readField( final ClassVisitor classVisitor, final Context context, final int fieldInfoOffset) { char[] charBuffer = context.charBuffer; // Read the access_flags, name_index and descriptor_index fields. int currentOffset = fieldInfoOffset; int accessFlags = readUnsignedShort(currentOffset); String name = readUTF8(currentOffset + 2, charBuffer); String descriptor = readUTF8(currentOffset + 4, charBuffer); currentOffset += 6; // Read the field attributes (the variables are ordered as in Section 4.7 of the JVMS). // Attribute offsets exclude the attribute_name_index and attribute_length fields. // - The value corresponding to the ConstantValue attribute, or null. Object constantValue = null; // - The string corresponding to the Signature attribute, or null. String signature = null; // - The offset of the RuntimeVisibleAnnotations attribute, or 0. int runtimeVisibleAnnotationsOffset = 0; // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. int runtimeInvisibleAnnotationsOffset = 0; // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. int runtimeVisibleTypeAnnotationsOffset = 0; // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. int runtimeInvisibleTypeAnnotationsOffset = 0; // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). // This list in the <i>reverse order</i> or their order in the ClassFile structure. Attribute attributes = null; int attributesCount = readUnsignedShort(currentOffset); currentOffset += 2; while (attributesCount-- > 0) { // Read the attribute_info's attribute_name and attribute_length fields. String attributeName = readUTF8(currentOffset, charBuffer); int attributeLength = readInt(currentOffset + 2); currentOffset += 6; // The tests are sorted in decreasing frequency order (based on frequencies observed on // typical classes). if (Constants.CONSTANT_VALUE.equals(attributeName)) { int constantvalueIndex = readUnsignedShort(currentOffset); constantValue = constantvalueIndex == 0 ? null : readConst(constantvalueIndex, charBuffer); } else if (Constants.SIGNATURE.equals(attributeName)) { signature = readUTF8(currentOffset, charBuffer); } else if (Constants.DEPRECATED.equals(attributeName)) { accessFlags |= Opcodes.ACC_DEPRECATED; } else if (Constants.SYNTHETIC.equals(attributeName)) { accessFlags |= Opcodes.ACC_SYNTHETIC; } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { runtimeVisibleAnnotationsOffset = currentOffset; } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { runtimeVisibleTypeAnnotationsOffset = currentOffset; } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { runtimeInvisibleAnnotationsOffset = currentOffset; } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { runtimeInvisibleTypeAnnotationsOffset = currentOffset; } else { Attribute attribute = readAttribute( context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null); attribute.nextAttribute = attributes; attributes = attribute; } currentOffset += attributeLength; } // Visit the field declaration. FieldVisitor fieldVisitor = classVisitor.visitField(accessFlags, name, descriptor, signature, constantValue); if (fieldVisitor == null) { return currentOffset; } // Visit the RuntimeVisibleAnnotations attribute. if (runtimeVisibleAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the RuntimeInvisibleAnnotations attribute. if (runtimeInvisibleAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the RuntimeVisibleTypeAnnotations attribute. if (runtimeVisibleTypeAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( fieldVisitor.visitTypeAnnotation( context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor, /* visible = */ true), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the RuntimeInvisibleTypeAnnotations attribute. if (runtimeInvisibleTypeAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( fieldVisitor.visitTypeAnnotation( context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor, /* visible = */ false), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the non standard attributes. while (attributes != null) { // Copy and reset the nextAttribute field so that it can also be used in FieldWriter. Attribute nextAttribute = attributes.nextAttribute; attributes.nextAttribute = null; fieldVisitor.visitAttribute(attributes); attributes = nextAttribute; } // Visit the end of the field. fieldVisitor.visitEnd(); return currentOffset; } /** * Reads a JVMS method_info structure and makes the given visitor visit it. * * @param classVisitor the visitor that must visit the method. * @param context information about the class being parsed. * @param methodInfoOffset the start offset of the method_info structure. * @return the offset of the first byte following the method_info structure. */ private int readMethod( final ClassVisitor classVisitor, final Context context, final int methodInfoOffset) { char[] charBuffer = context.charBuffer; // Read the access_flags, name_index and descriptor_index fields. int currentOffset = methodInfoOffset; context.currentMethodAccessFlags = readUnsignedShort(currentOffset); context.currentMethodName = readUTF8(currentOffset + 2, charBuffer); context.currentMethodDescriptor = readUTF8(currentOffset + 4, charBuffer); currentOffset += 6; // Read the method attributes (the variables are ordered as in Section 4.7 of the JVMS). // Attribute offsets exclude the attribute_name_index and attribute_length fields. // - The offset of the Code attribute, or 0. int codeOffset = 0; // - The offset of the Exceptions attribute, or 0. int exceptionsOffset = 0; // - The strings corresponding to the Exceptions attribute, or null. String[] exceptions = null; // - The string corresponding to the Signature attribute, or null. int signature = 0; // - The offset of the RuntimeVisibleAnnotations attribute, or 0. int runtimeVisibleAnnotationsOffset = 0; // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. int runtimeInvisibleAnnotationsOffset = 0; // - The offset of the RuntimeVisibleParameterAnnotations attribute, or 0. int runtimeVisibleParameterAnnotationsOffset = 0; // - The offset of the RuntimeInvisibleParameterAnnotations attribute, or 0. int runtimeInvisibleParameterAnnotationsOffset = 0; // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. int runtimeVisibleTypeAnnotationsOffset = 0; // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. int runtimeInvisibleTypeAnnotationsOffset = 0; // - The offset of the AnnotationDefault attribute, or 0. int annotationDefaultOffset = 0; // - The offset of the MethodParameters attribute, or 0. int methodParametersOffset = 0; // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). // This list in the <i>reverse order</i> or their order in the ClassFile structure. Attribute attributes = null; int attributesCount = readUnsignedShort(currentOffset); currentOffset += 2; while (attributesCount-- > 0) { // Read the attribute_info's attribute_name and attribute_length fields. String attributeName = readUTF8(currentOffset, charBuffer); int attributeLength = readInt(currentOffset + 2); currentOffset += 6; // The tests are sorted in decreasing frequency order (based on frequencies observed on // typical classes). if (Constants.CODE.equals(attributeName)) { if ((context.parsingOptions & SKIP_CODE) == 0) { codeOffset = currentOffset; } } else if (Constants.EXCEPTIONS.equals(attributeName)) { exceptionsOffset = currentOffset; exceptions = new String[readUnsignedShort(exceptionsOffset)]; int currentExceptionOffset = exceptionsOffset + 2; for (int i = 0; i < exceptions.length; ++i) { exceptions[i] = readClass(currentExceptionOffset, charBuffer); currentExceptionOffset += 2; } } else if (Constants.SIGNATURE.equals(attributeName)) { signature = readUnsignedShort(currentOffset); } else if (Constants.DEPRECATED.equals(attributeName)) { context.currentMethodAccessFlags |= Opcodes.ACC_DEPRECATED; } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { runtimeVisibleAnnotationsOffset = currentOffset; } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { runtimeVisibleTypeAnnotationsOffset = currentOffset; } else if (Constants.ANNOTATION_DEFAULT.equals(attributeName)) { annotationDefaultOffset = currentOffset; } else if (Constants.SYNTHETIC.equals(attributeName)) { context.currentMethodAccessFlags |= Opcodes.ACC_SYNTHETIC; } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { runtimeInvisibleAnnotationsOffset = currentOffset; } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { runtimeInvisibleTypeAnnotationsOffset = currentOffset; } else if (Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) { runtimeVisibleParameterAnnotationsOffset = currentOffset; } else if (Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) { runtimeInvisibleParameterAnnotationsOffset = currentOffset; } else if (Constants.METHOD_PARAMETERS.equals(attributeName)) { methodParametersOffset = currentOffset; } else { Attribute attribute = readAttribute( context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null); attribute.nextAttribute = attributes; attributes = attribute; } currentOffset += attributeLength; } // Visit the method declaration. MethodVisitor methodVisitor = classVisitor.visitMethod( context.currentMethodAccessFlags, context.currentMethodName, context.currentMethodDescriptor, signature == 0 ? null : readUTF(signature, charBuffer), exceptions); if (methodVisitor == null) { return currentOffset; } // If the returned MethodVisitor is in fact a MethodWriter, it means there is no method // adapter between the reader and the writer. If, in addition, the writer's constant pool was // copied from this reader (mw.getSource() == this), and the signature and exceptions of the // method have not been changed, then it is possible to skip all visit events and just copy the // original code of the method to the writer (the access_flags, name_index and descriptor_index // can have been changed, this is not important since they are not copied from the reader). if (methodVisitor instanceof MethodWriter) { MethodWriter methodWriter = (MethodWriter) methodVisitor; if (methodWriter.getSource() == this && signature == methodWriter.signatureIndex) { boolean sameExceptions = false; if (exceptions == null) { sameExceptions = methodWriter.numberOfExceptions == 0; } else if (exceptions.length == methodWriter.numberOfExceptions) { sameExceptions = true; int currentExceptionOffset = exceptionsOffset + 2; for (int i = 0; i < exceptions.length; ++i) { if (methodWriter.exceptionIndexTable[i] != readUnsignedShort(currentExceptionOffset)) { sameExceptions = false; break; } currentExceptionOffset += 2; } } if (sameExceptions) { // We do not copy directly the code into methodWriter to save a byte array copy operation. // The real copy will be done in {@link MethodWriter#putMethodInfo}. methodWriter.sourceOffset = methodInfoOffset + 6; methodWriter.sourceLength = currentOffset - methodWriter.sourceOffset; return currentOffset; } } } // Visit the MethodParameters attribute. if (methodParametersOffset != 0) { int parametersCount = readByte(methodParametersOffset); int currentParameterOffset = methodParametersOffset + 1; while (parametersCount-- > 0) { // Read the name_index and access_flags fields and visit them. methodVisitor.visitParameter( readUTF8(currentParameterOffset, charBuffer), readUnsignedShort(currentParameterOffset + 2)); currentParameterOffset += 4; } } // Visit the AnnotationDefault attribute. if (annotationDefaultOffset != 0) { AnnotationVisitor annotationVisitor = methodVisitor.visitAnnotationDefault(); readElementValue(annotationVisitor, annotationDefaultOffset, null, charBuffer); if (annotationVisitor != null) { annotationVisitor.visitEnd(); } } // Visit the RuntimeVisibleAnnotations attribute. if (runtimeVisibleAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the RuntimeInvisibleAnnotations attribute. if (runtimeInvisibleAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the RuntimeVisibleTypeAnnotations attribute. if (runtimeVisibleTypeAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( methodVisitor.visitTypeAnnotation( context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor, /* visible = */ true), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the RuntimeInvisibleTypeAnnotations attribute. if (runtimeInvisibleTypeAnnotationsOffset != 0) { int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; while (numAnnotations-- > 0) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues( methodVisitor.visitTypeAnnotation( context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor, /* visible = */ false), currentAnnotationOffset, /* named = */ true, charBuffer); } } // Visit the RuntimeVisibleParameterAnnotations attribute. if (runtimeVisibleParameterAnnotationsOffset != 0) { readParameterAnnotations( methodVisitor, context, runtimeVisibleParameterAnnotationsOffset, /* visible = */ true); } // Visit the RuntimeInvisibleParameterAnnotations attribute. if (runtimeInvisibleParameterAnnotationsOffset != 0) { readParameterAnnotations( methodVisitor, context, runtimeInvisibleParameterAnnotationsOffset, /* visible = */ false); } // Visit the non standard attributes. while (attributes != null) { // Copy and reset the nextAttribute field so that it can also be used in MethodWriter. Attribute nextAttribute = attributes.nextAttribute; attributes.nextAttribute = null; methodVisitor.visitAttribute(attributes); attributes = nextAttribute; } // Visit the Code attribute. if (codeOffset != 0) { methodVisitor.visitCode(); readCode(methodVisitor, context, codeOffset); } // Visit the end of the method. methodVisitor.visitEnd(); return currentOffset; } // ---------------------------------------------------------------------------------------------- // Methods to parse a Code attribute // ---------------------------------------------------------------------------------------------- /** * Reads a JVMS 'Code' attribute and makes the given visitor visit it. * * @param methodVisitor the visitor that must visit the Code attribute. * @param context information about the class being parsed. * @param codeOffset the start offset in {@link #b} of the Code attribute, excluding its * attribute_name_index and attribute_length fields. */ private void readCode( final MethodVisitor methodVisitor, final Context context, final int codeOffset) { int currentOffset = codeOffset; // Read the max_stack, max_locals and code_length fields. final byte[] classFileBuffer = b; final char[] charBuffer = context.charBuffer; final int maxStack = readUnsignedShort(currentOffset); final int maxLocals = readUnsignedShort(currentOffset + 2); final int codeLength = readInt(currentOffset + 4); currentOffset += 8; // Read the bytecode 'code' array to create a label for each referenced instruction. final int bytecodeStartOffset = currentOffset; final int bytecodeEndOffset = currentOffset + codeLength; final Label[] labels = context.currentMethodLabels = new Label[codeLength + 1]; while (currentOffset < bytecodeEndOffset) { final int bytecodeOffset = currentOffset - bytecodeStartOffset; final int opcode = classFileBuffer[currentOffset] & 0xFF; switch (opcode) { case Constants.NOP: case Constants.ACONST_NULL: case Constants.ICONST_M1: case Constants.ICONST_0: case Constants.ICONST_1: case Constants.ICONST_2: case Constants.ICONST_3: case Constants.ICONST_4: case Constants.ICONST_5: case Constants.LCONST_0: case Constants.LCONST_1: case Constants.FCONST_0: case Constants.FCONST_1: case Constants.FCONST_2: case Constants.DCONST_0: case Constants.DCONST_1: case Constants.IALOAD: case Constants.LALOAD: case Constants.FALOAD: case Constants.DALOAD: case Constants.AALOAD: case Constants.BALOAD: case Constants.CALOAD: case Constants.SALOAD: case Constants.IASTORE: case Constants.LASTORE: case Constants.FASTORE: case Constants.DASTORE: case Constants.AASTORE: case Constants.BASTORE: case Constants.CASTORE: case Constants.SASTORE: case Constants.POP: case Constants.POP2: case Constants.DUP: case Constants.DUP_X1: case Constants.DUP_X2: case Constants.DUP2: case Constants.DUP2_X1: case Constants.DUP2_X2: case Constants.SWAP: case Constants.IADD: case Constants.LADD: case Constants.FADD: case Constants.DADD: case Constants.ISUB: case Constants.LSUB: case Constants.FSUB: case Constants.DSUB: case Constants.IMUL: case Constants.LMUL: case Constants.FMUL: case Constants.DMUL: case Constants.IDIV: case Constants.LDIV: case Constants.FDIV: case Constants.DDIV: case Constants.IREM: case Constants.LREM: case Constants.FREM: case Constants.DREM: case Constants.INEG: case Constants.LNEG: case Constants.FNEG: case Constants.DNEG: case Constants.ISHL: case Constants.LSHL: case Constants.ISHR: case Constants.LSHR: case Constants.IUSHR: case Constants.LUSHR: case Constants.IAND: case Constants.LAND: case Constants.IOR: case Constants.LOR: case Constants.IXOR: case Constants.LXOR: case Constants.I2L: case Constants.I2F: case Constants.I2D: case Constants.L2I: case Constants.L2F: case Constants.L2D: case Constants.F2I: case Constants.F2L: case Constants.F2D: case Constants.D2I: case Constants.D2L: case Constants.D2F: case Constants.I2B: case Constants.I2C: case Constants.I2S: case Constants.LCMP: case Constants.FCMPL: case Constants.FCMPG: case Constants.DCMPL: case Constants.DCMPG: case Constants.IRETURN: case Constants.LRETURN: case Constants.FRETURN: case Constants.DRETURN: case Constants.ARETURN: case Constants.RETURN: case Constants.ARRAYLENGTH: case Constants.ATHROW: case Constants.MONITORENTER: case Constants.MONITOREXIT: case Constants.ILOAD_0: case Constants.ILOAD_1: case Constants.ILOAD_2: case Constants.ILOAD_3: case Constants.LLOAD_0: case Constants.LLOAD_1: case Constants.LLOAD_2: case Constants.LLOAD_3: case Constants.FLOAD_0: case Constants.FLOAD_1: case Constants.FLOAD_2: case Constants.FLOAD_3: case Constants.DLOAD_0: case Constants.DLOAD_1: case Constants.DLOAD_2: case Constants.DLOAD_3: case Constants.ALOAD_0: case Constants.ALOAD_1: case Constants.ALOAD_2: case Constants.ALOAD_3: case Constants.ISTORE_0: case Constants.ISTORE_1: case Constants.ISTORE_2: case Constants.ISTORE_3: case Constants.LSTORE_0: case Constants.LSTORE_1: case Constants.LSTORE_2: case Constants.LSTORE_3: case Constants.FSTORE_0: case Constants.FSTORE_1: case Constants.FSTORE_2: case Constants.FSTORE_3: case Constants.DSTORE_0: case Constants.DSTORE_1: case Constants.DSTORE_2: case Constants.DSTORE_3: case Constants.ASTORE_0: case Constants.ASTORE_1: case Constants.ASTORE_2: case Constants.ASTORE_3: currentOffset += 1; break; case Constants.IFEQ: case Constants.IFNE: case Constants.IFLT: case Constants.IFGE: case Constants.IFGT: case Constants.IFLE: case Constants.IF_ICMPEQ: case Constants.IF_ICMPNE: case Constants.IF_ICMPLT: case Constants.IF_ICMPGE: case Constants.IF_ICMPGT: case Constants.IF_ICMPLE: case Constants.IF_ACMPEQ: case Constants.IF_ACMPNE: case Constants.GOTO: case Constants.JSR: case Constants.IFNULL: case Constants.IFNONNULL: createLabel(bytecodeOffset + readShort(currentOffset + 1), labels); currentOffset += 3; break; case Constants.ASM_IFEQ: case Constants.ASM_IFNE: case Constants.ASM_IFLT: case Constants.ASM_IFGE: case Constants.ASM_IFGT: case Constants.ASM_IFLE: case Constants.ASM_IF_ICMPEQ: case Constants.ASM_IF_ICMPNE: case Constants.ASM_IF_ICMPLT: case Constants.ASM_IF_ICMPGE: case Constants.ASM_IF_ICMPGT: case Constants.ASM_IF_ICMPLE: case Constants.ASM_IF_ACMPEQ: case Constants.ASM_IF_ACMPNE: case Constants.ASM_GOTO: case Constants.ASM_JSR: case Constants.ASM_IFNULL: case Constants.ASM_IFNONNULL: createLabel(bytecodeOffset + readUnsignedShort(currentOffset + 1), labels); currentOffset += 3; break; case Constants.GOTO_W: case Constants.JSR_W: case Constants.ASM_GOTO_W: createLabel(bytecodeOffset + readInt(currentOffset + 1), labels); currentOffset += 5; break; case Constants.WIDE: switch (classFileBuffer[currentOffset + 1] & 0xFF) { case Constants.ILOAD: case Constants.FLOAD: case Constants.ALOAD: case Constants.LLOAD: case Constants.DLOAD: case Constants.ISTORE: case Constants.FSTORE: case Constants.ASTORE: case Constants.LSTORE: case Constants.DSTORE: case Constants.RET: currentOffset += 4; break; case Constants.IINC: currentOffset += 6; break; default: throw new IllegalArgumentException(); } break; case Constants.TABLESWITCH: // Skip 0 to 3 padding bytes. currentOffset += 4 - (bytecodeOffset & 3); // Read the default label and the number of table entries. createLabel(bytecodeOffset + readInt(currentOffset), labels); int numTableEntries = readInt(currentOffset + 8) - readInt(currentOffset + 4) + 1; currentOffset += 12; // Read the table labels. while (numTableEntries-- > 0) { createLabel(bytecodeOffset + readInt(currentOffset), labels); currentOffset += 4; } break; case Constants.LOOKUPSWITCH: // Skip 0 to 3 padding bytes. currentOffset += 4 - (bytecodeOffset & 3); // Read the default label and the number of switch cases. createLabel(bytecodeOffset + readInt(currentOffset), labels); int numSwitchCases = readInt(currentOffset + 4); currentOffset += 8; // Read the switch labels. while (numSwitchCases-- > 0) { createLabel(bytecodeOffset + readInt(currentOffset + 4), labels); currentOffset += 8; } break; case Constants.ILOAD: case Constants.LLOAD: case Constants.FLOAD: case Constants.DLOAD: case Constants.ALOAD: case Constants.ISTORE: case Constants.LSTORE: case Constants.FSTORE: case Constants.DSTORE: case Constants.ASTORE: case Constants.RET: case Constants.BIPUSH: case Constants.NEWARRAY: case Constants.LDC: currentOffset += 2; break; case Constants.SIPUSH: case Constants.LDC_W: case Constants.LDC2_W: case Constants.GETSTATIC: case Constants.PUTSTATIC: case Constants.GETFIELD: case Constants.PUTFIELD: case Constants.INVOKEVIRTUAL: case Constants.INVOKESPECIAL: case Constants.INVOKESTATIC: case Constants.NEW: case Constants.ANEWARRAY: case Constants.CHECKCAST: case Constants.INSTANCEOF: case Constants.IINC: currentOffset += 3; break; case Constants.INVOKEINTERFACE: case Constants.INVOKEDYNAMIC: currentOffset += 5; break; case Constants.MULTIANEWARRAY: currentOffset += 4; break; default: throw new IllegalArgumentException(); } } // Read the 'exception_table_length' and 'exception_table' field to create a label for each // referenced instruction, and to make methodVisitor visit the corresponding try catch blocks. { int exceptionTableLength = readUnsignedShort(currentOffset); currentOffset += 2; while (exceptionTableLength-- > 0) { Label start = createLabel(readUnsignedShort(currentOffset), labels); Label end = createLabel(readUnsignedShort(currentOffset + 2), labels); Label handler = createLabel(readUnsignedShort(currentOffset + 4), labels); String catchType = readUTF8(cpInfoOffsets[readUnsignedShort(currentOffset + 6)], charBuffer); currentOffset += 8; methodVisitor.visitTryCatchBlock(start, end, handler, catchType); } } // Read the Code attributes to create a label for each referenced instruction (the variables // are ordered as in Section 4.7 of the JVMS). Attribute offsets exclude the // attribute_name_index and attribute_length fields. // - The offset of the current 'stack_map_frame' in the StackMap[Table] attribute, or 0. // Initially, this is the offset of the first 'stack_map_frame' entry. Then this offset is // updated after each stack_map_frame is read. int stackMapFrameOffset = 0; // - The end offset of the StackMap[Table] attribute, or 0. int stackMapTableEndOffset = 0; // - Whether the stack map frames are compressed (i.e. in a StackMapTable) or not. boolean compressedFrames = true; // - The offset of the LocalVariableTable attribute, or 0. int localVariableTableOffset = 0; // - The offset of the LocalVariableTypeTable attribute, or 0. int localVariableTypeTableOffset = 0; // - The offset of each 'type_annotation' entry in the RuntimeVisibleTypeAnnotations // attribute, or null. int[] visibleTypeAnnotationOffsets = null; // - The offset of each 'type_annotation' entry in the RuntimeInvisibleTypeAnnotations // attribute, or null. int[] invisibleTypeAnnotationOffsets = null; // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). // This list in the <i>reverse order</i> or their order in the ClassFile structure. Attribute attributes = null; int attributesCount = readUnsignedShort(currentOffset); currentOffset += 2; while (attributesCount-- > 0) { // Read the attribute_info's attribute_name and attribute_length fields. String attributeName = readUTF8(currentOffset, charBuffer); int attributeLength = readInt(currentOffset + 2); currentOffset += 6; if (Constants.LOCAL_VARIABLE_TABLE.equals(attributeName)) { if ((context.parsingOptions & SKIP_DEBUG) == 0) { localVariableTableOffset = currentOffset; // Parse the attribute to find the corresponding (debug only) labels. int currentLocalVariableTableOffset = currentOffset; int localVariableTableLength = readUnsignedShort(currentLocalVariableTableOffset); currentLocalVariableTableOffset += 2; while (localVariableTableLength-- > 0) { int startPc = readUnsignedShort(currentLocalVariableTableOffset); createDebugLabel(startPc, labels); int length = readUnsignedShort(currentLocalVariableTableOffset + 2); createDebugLabel(startPc + length, labels); // Skip the name_index, descriptor_index and index fields (2 bytes each). currentLocalVariableTableOffset += 10; } } } else if (Constants.LOCAL_VARIABLE_TYPE_TABLE.equals(attributeName)) { localVariableTypeTableOffset = currentOffset; // Here we do not extract the labels corresponding to the attribute content. We assume they // are the same or a subset of those of the LocalVariableTable attribute. } else if (Constants.LINE_NUMBER_TABLE.equals(attributeName)) { if ((context.parsingOptions & SKIP_DEBUG) == 0) { // Parse the attribute to find the corresponding (debug only) labels. int currentLineNumberTableOffset = currentOffset; int lineNumberTableLength = readUnsignedShort(currentLineNumberTableOffset); currentLineNumberTableOffset += 2; while (lineNumberTableLength-- > 0) { int startPc = readUnsignedShort(currentLineNumberTableOffset); int lineNumber = readUnsignedShort(currentLineNumberTableOffset + 2); currentLineNumberTableOffset += 4; createDebugLabel(startPc, labels); labels[startPc].addLineNumber(lineNumber); } } } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { visibleTypeAnnotationOffsets = readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ true); // Here we do not extract the labels corresponding to the attribute content. This would // require a full parsing of the attribute, which would need to be repeated when parsing // the bytecode instructions (see below). Instead, the content of the attribute is read one // type annotation at a time (i.e. after a type annotation has been visited, the next type // annotation is read), and the labels it contains are also extracted one annotation at a // time. This assumes that type annotations are ordered by increasing bytecode offset. } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { invisibleTypeAnnotationOffsets = readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ false); // Same comment as above for the RuntimeVisibleTypeAnnotations attribute. } else if (Constants.STACK_MAP_TABLE.equals(attributeName)) { if ((context.parsingOptions & SKIP_FRAMES) == 0) { stackMapFrameOffset = currentOffset + 2; stackMapTableEndOffset = currentOffset + attributeLength; } // Here we do not extract the labels corresponding to the attribute content. This would // require a full parsing of the attribute, which would need to be repeated when parsing // the bytecode instructions (see below). Instead, the content of the attribute is read one // frame at a time (i.e. after a frame has been visited, the next frame is read), and the // labels it contains are also extracted one frame at a time. Thanks to the ordering of // frames, having only a "one frame lookahead" is not a problem, i.e. it is not possible to // see an offset smaller than the offset of the current instruction and for which no Label // exist. Except for UNINITIALIZED type offsets. We solve this by parsing the stack map // table without a full decoding (see below). } else if ("StackMap".equals(attributeName)) { if ((context.parsingOptions & SKIP_FRAMES) == 0) { stackMapFrameOffset = currentOffset + 2; stackMapTableEndOffset = currentOffset + attributeLength; compressedFrames = false; } // IMPORTANT! Here we assume that the frames are ordered, as in the StackMapTable attribute, // although this is not guaranteed by the attribute format. This allows an incremental // extraction of the labels corresponding to this attribute (see the comment above for the // StackMapTable attribute). } else { Attribute attribute = readAttribute( context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, codeOffset, labels); attribute.nextAttribute = attributes; attributes = attribute; } currentOffset += attributeLength; } // Initialize the context fields related to stack map frames, and generate the first // (implicit) stack map frame, if needed. final boolean expandFrames = (context.parsingOptions & EXPAND_FRAMES) != 0; if (stackMapFrameOffset != 0) { // The bytecode offset of the first explicit frame is not offset_delta + 1 but only // offset_delta. Setting the implicit frame offset to -1 allows us to use of the // "offset_delta + 1" rule in all cases. context.currentFrameOffset = -1; context.currentFrameType = 0; context.currentFrameLocalCount = 0; context.currentFrameLocalCountDelta = 0; context.currentFrameLocalTypes = new Object[maxLocals]; context.currentFrameStackCount = 0; context.currentFrameStackTypes = new Object[maxStack]; if (expandFrames) { computeImplicitFrame(context); } // Find the labels for UNINITIALIZED frame types. Instead of decoding each element of the // stack map table, we look for 3 consecutive bytes that "look like" an UNINITIALIZED type // (tag ITEM_Uninitialized, offset within bytecode bounds, NEW instruction at this offset). // We may find false positives (i.e. not real UNINITIALIZED types), but this should be rare, // and the only consequence will be the creation of an unneeded label. This is better than // creating a label for each NEW instruction, and faster than fully decoding the whole stack // map table. for (int offset = stackMapFrameOffset; offset < stackMapTableEndOffset - 2; ++offset) { if (classFileBuffer[offset] == Frame.ITEM_UNINITIALIZED) { int potentialBytecodeOffset = readUnsignedShort(offset + 1); if (potentialBytecodeOffset >= 0 && potentialBytecodeOffset < codeLength && (classFileBuffer[bytecodeStartOffset + potentialBytecodeOffset] & 0xFF) == Opcodes.NEW) { createLabel(potentialBytecodeOffset, labels); } } } } if (expandFrames && (context.parsingOptions & EXPAND_ASM_INSNS) != 0) { // Expanding the ASM specific instructions can introduce F_INSERT frames, even if the method // does not currently have any frame. These inserted frames must be computed by simulating the // effect of the bytecode instructions, one by one, starting from the implicit first frame. // For this, MethodWriter needs to know maxLocals before the first instruction is visited. To // ensure this, we visit the implicit first frame here (passing only maxLocals - the rest is // computed in MethodWriter). methodVisitor.visitFrame(Opcodes.F_NEW, maxLocals, null, 0, null); } // Visit the bytecode instructions. First, introduce state variables for the incremental parsing // of the type annotations. // Index of the next runtime visible type annotation to read (in the // visibleTypeAnnotationOffsets array). int currentVisibleTypeAnnotationIndex = 0; // The bytecode offset of the next runtime visible type annotation to read, or -1. int currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, 0); // Index of the next runtime invisible type annotation to read (in the // invisibleTypeAnnotationOffsets array). int currentInvisibleTypeAnnotationIndex = 0; // The bytecode offset of the next runtime invisible type annotation to read, or -1. int currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, 0); // Whether a F_INSERT stack map frame must be inserted before the current instruction. boolean insertFrame = false; // The delta to subtract from a goto_w or jsr_w opcode to get the corresponding goto or jsr // opcode, or 0 if goto_w and jsr_w must be left unchanged (i.e. when expanding ASM specific // instructions). final int wideJumpOpcodeDelta = (context.parsingOptions & EXPAND_ASM_INSNS) == 0 ? Constants.WIDE_JUMP_OPCODE_DELTA : 0; currentOffset = bytecodeStartOffset; while (currentOffset < bytecodeEndOffset) { final int currentBytecodeOffset = currentOffset - bytecodeStartOffset; // Visit the label and the line number(s) for this bytecode offset, if any. Label currentLabel = labels[currentBytecodeOffset]; if (currentLabel != null) { currentLabel.accept(methodVisitor, (context.parsingOptions & SKIP_DEBUG) == 0); } // Visit the stack map frame for this bytecode offset, if any. while (stackMapFrameOffset != 0 && (context.currentFrameOffset == currentBytecodeOffset || context.currentFrameOffset == -1)) { // If there is a stack map frame for this offset, make methodVisitor visit it, and read the // next stack map frame if there is one. if (context.currentFrameOffset != -1) { if (!compressedFrames || expandFrames) { methodVisitor.visitFrame( Opcodes.F_NEW, context.currentFrameLocalCount, context.currentFrameLocalTypes, context.currentFrameStackCount, context.currentFrameStackTypes); } else { methodVisitor.visitFrame( context.currentFrameType, context.currentFrameLocalCountDelta, context.currentFrameLocalTypes, context.currentFrameStackCount, context.currentFrameStackTypes); } // Since there is already a stack map frame for this bytecode offset, there is no need to // insert a new one. insertFrame = false; } if (stackMapFrameOffset < stackMapTableEndOffset) { stackMapFrameOffset = readStackMapFrame(stackMapFrameOffset, compressedFrames, expandFrames, context); } else { stackMapFrameOffset = 0; } } // Insert a stack map frame for this bytecode offset, if requested by setting insertFrame to // true during the previous iteration. The actual frame content is computed in MethodWriter. if (insertFrame) { if ((context.parsingOptions & EXPAND_FRAMES) != 0) { methodVisitor.visitFrame(Constants.F_INSERT, 0, null, 0, null); } insertFrame = false; } // Visit the instruction at this bytecode offset. int opcode = classFileBuffer[currentOffset] & 0xFF; switch (opcode) { case Constants.NOP: case Constants.ACONST_NULL: case Constants.ICONST_M1: case Constants.ICONST_0: case Constants.ICONST_1: case Constants.ICONST_2: case Constants.ICONST_3: case Constants.ICONST_4: case Constants.ICONST_5: case Constants.LCONST_0: case Constants.LCONST_1: case Constants.FCONST_0: case Constants.FCONST_1: case Constants.FCONST_2: case Constants.DCONST_0: case Constants.DCONST_1: case Constants.IALOAD: case Constants.LALOAD: case Constants.FALOAD: case Constants.DALOAD: case Constants.AALOAD: case Constants.BALOAD: case Constants.CALOAD: case Constants.SALOAD: case Constants.IASTORE: case Constants.LASTORE: case Constants.FASTORE: case Constants.DASTORE: case Constants.AASTORE: case Constants.BASTORE: case Constants.CASTORE: case Constants.SASTORE: case Constants.POP: case Constants.POP2: case Constants.DUP: case Constants.DUP_X1: case Constants.DUP_X2: case Constants.DUP2: case Constants.DUP2_X1: case Constants.DUP2_X2: case Constants.SWAP: case Constants.IADD: case Constants.LADD: case Constants.FADD: case Constants.DADD: case Constants.ISUB: case Constants.LSUB: case Constants.FSUB: case Constants.DSUB: case Constants.IMUL: case Constants.LMUL: case Constants.FMUL: case Constants.DMUL: case Constants.IDIV: case Constants.LDIV: case Constants.FDIV: case Constants.DDIV: case Constants.IREM: case Constants.LREM: case Constants.FREM: case Constants.DREM: case Constants.INEG: case Constants.LNEG: case Constants.FNEG: case Constants.DNEG: case Constants.ISHL: case Constants.LSHL: case Constants.ISHR: case Constants.LSHR: case Constants.IUSHR: case Constants.LUSHR: case Constants.IAND: case Constants.LAND: case Constants.IOR: case Constants.LOR: case Constants.IXOR: case Constants.LXOR: case Constants.I2L: case Constants.I2F: case Constants.I2D: case Constants.L2I: case Constants.L2F: case Constants.L2D: case Constants.F2I: case Constants.F2L: case Constants.F2D: case Constants.D2I: case Constants.D2L: case Constants.D2F: case Constants.I2B: case Constants.I2C: case Constants.I2S: case Constants.LCMP: case Constants.FCMPL: case Constants.FCMPG: case Constants.DCMPL: case Constants.DCMPG: case Constants.IRETURN: case Constants.LRETURN: case Constants.FRETURN: case Constants.DRETURN: case Constants.ARETURN: case Constants.RETURN: case Constants.ARRAYLENGTH: case Constants.ATHROW: case Constants.MONITORENTER: case Constants.MONITOREXIT: methodVisitor.visitInsn(opcode); currentOffset += 1; break; case Constants.ILOAD_0: case Constants.ILOAD_1: case Constants.ILOAD_2: case Constants.ILOAD_3: case Constants.LLOAD_0: case Constants.LLOAD_1: case Constants.LLOAD_2: case Constants.LLOAD_3: case Constants.FLOAD_0: case Constants.FLOAD_1: case Constants.FLOAD_2: case Constants.FLOAD_3: case Constants.DLOAD_0: case Constants.DLOAD_1: case Constants.DLOAD_2: case Constants.DLOAD_3: case Constants.ALOAD_0: case Constants.ALOAD_1: case Constants.ALOAD_2: case Constants.ALOAD_3: opcode -= Constants.ILOAD_0; methodVisitor.visitVarInsn(Opcodes.ILOAD + (opcode >> 2), opcode & 0x3); currentOffset += 1; break; case Constants.ISTORE_0: case Constants.ISTORE_1: case Constants.ISTORE_2: case Constants.ISTORE_3: case Constants.LSTORE_0: case Constants.LSTORE_1: case Constants.LSTORE_2: case Constants.LSTORE_3: case Constants.FSTORE_0: case Constants.FSTORE_1: case Constants.FSTORE_2: case Constants.FSTORE_3: case Constants.DSTORE_0: case Constants.DSTORE_1: case Constants.DSTORE_2: case Constants.DSTORE_3: case Constants.ASTORE_0: case Constants.ASTORE_1: case Constants.ASTORE_2: case Constants.ASTORE_3: opcode -= Constants.ISTORE_0; methodVisitor.visitVarInsn(Opcodes.ISTORE + (opcode >> 2), opcode & 0x3); currentOffset += 1; break; case Constants.IFEQ: case Constants.IFNE: case Constants.IFLT: case Constants.IFGE: case Constants.IFGT: case Constants.IFLE: case Constants.IF_ICMPEQ: case Constants.IF_ICMPNE: case Constants.IF_ICMPLT: case Constants.IF_ICMPGE: case Constants.IF_ICMPGT: case Constants.IF_ICMPLE: case Constants.IF_ACMPEQ: case Constants.IF_ACMPNE: case Constants.GOTO: case Constants.JSR: case Constants.IFNULL: case Constants.IFNONNULL: methodVisitor.visitJumpInsn( opcode, labels[currentBytecodeOffset + readShort(currentOffset + 1)]); currentOffset += 3; break; case Constants.GOTO_W: case Constants.JSR_W: methodVisitor.visitJumpInsn( opcode - wideJumpOpcodeDelta, labels[currentBytecodeOffset + readInt(currentOffset + 1)]); currentOffset += 5; break; case Constants.ASM_IFEQ: case Constants.ASM_IFNE: case Constants.ASM_IFLT: case Constants.ASM_IFGE: case Constants.ASM_IFGT: case Constants.ASM_IFLE: case Constants.ASM_IF_ICMPEQ: case Constants.ASM_IF_ICMPNE: case Constants.ASM_IF_ICMPLT: case Constants.ASM_IF_ICMPGE: case Constants.ASM_IF_ICMPGT: case Constants.ASM_IF_ICMPLE: case Constants.ASM_IF_ACMPEQ: case Constants.ASM_IF_ACMPNE: case Constants.ASM_GOTO: case Constants.ASM_JSR: case Constants.ASM_IFNULL: case Constants.ASM_IFNONNULL: { // A forward jump with an offset > 32767. In this case we automatically replace ASM_GOTO // with GOTO_W, ASM_JSR with JSR_W and ASM_IFxxx <l> with IFNOTxxx <L> GOTO_W <l> L:..., // where IFNOTxxx is the "opposite" opcode of ASMS_IFxxx (e.g. IFNE for ASM_IFEQ) and // where <L> designates the instruction just after the GOTO_W. // First, change the ASM specific opcodes ASM_IFEQ ... ASM_JSR, ASM_IFNULL and // ASM_IFNONNULL to IFEQ ... JSR, IFNULL and IFNONNULL. opcode = opcode < Constants.ASM_IFNULL ? opcode - Constants.ASM_OPCODE_DELTA : opcode - Constants.ASM_IFNULL_OPCODE_DELTA; Label target = labels[currentBytecodeOffset + readUnsignedShort(currentOffset + 1)]; if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // Replace GOTO with GOTO_W and JSR with JSR_W. methodVisitor.visitJumpInsn(opcode + Constants.WIDE_JUMP_OPCODE_DELTA, target); } else { // Compute the "opposite" of opcode. This can be done by flipping the least // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ // (with a pre and post offset by 1). opcode = opcode < Opcodes.GOTO ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1; Label endif = createLabel(currentBytecodeOffset + 3, labels); methodVisitor.visitJumpInsn(opcode, endif); methodVisitor.visitJumpInsn(Constants.GOTO_W, target); // endif designates the instruction just after GOTO_W, and is visited as part of the // next instruction. Since it is a jump target, we need to insert a frame here. insertFrame = true; } currentOffset += 3; break; } case Constants.ASM_GOTO_W: { // Replace ASM_GOTO_W with GOTO_W. methodVisitor.visitJumpInsn( Constants.GOTO_W, labels[currentBytecodeOffset + readInt(currentOffset + 1)]); // The instruction just after is a jump target (because ASM_GOTO_W is used in patterns // IFNOTxxx <L> ASM_GOTO_W <l> L:..., see MethodWriter), so we need to insert a frame // here. insertFrame = true; currentOffset += 5; break; } case Constants.WIDE: opcode = classFileBuffer[currentOffset + 1] & 0xFF; if (opcode == Opcodes.IINC) { methodVisitor.visitIincInsn( readUnsignedShort(currentOffset + 2), readShort(currentOffset + 4)); currentOffset += 6; } else { methodVisitor.visitVarInsn(opcode, readUnsignedShort(currentOffset + 2)); currentOffset += 4; } break; case Constants.TABLESWITCH: { // Skip 0 to 3 padding bytes. currentOffset += 4 - (currentBytecodeOffset & 3); // Read the instruction. Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)]; int low = readInt(currentOffset + 4); int high = readInt(currentOffset + 8); currentOffset += 12; Label[] table = new Label[high - low + 1]; for (int i = 0; i < table.length; ++i) { table[i] = labels[currentBytecodeOffset + readInt(currentOffset)]; currentOffset += 4; } methodVisitor.visitTableSwitchInsn(low, high, defaultLabel, table); break; } case Constants.LOOKUPSWITCH: { // Skip 0 to 3 padding bytes. currentOffset += 4 - (currentBytecodeOffset & 3); // Read the instruction. Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)]; int nPairs = readInt(currentOffset + 4); currentOffset += 8; int[] keys = new int[nPairs]; Label[] values = new Label[nPairs]; for (int i = 0; i < nPairs; ++i) { keys[i] = readInt(currentOffset); values[i] = labels[currentBytecodeOffset + readInt(currentOffset + 4)]; currentOffset += 8; } methodVisitor.visitLookupSwitchInsn(defaultLabel, keys, values); break; } case Constants.ILOAD: case Constants.LLOAD: case Constants.FLOAD: case Constants.DLOAD: case Constants.ALOAD: case Constants.ISTORE: case Constants.LSTORE: case Constants.FSTORE: case Constants.DSTORE: case Constants.ASTORE: case Constants.RET: methodVisitor.visitVarInsn(opcode, classFileBuffer[currentOffset + 1] & 0xFF); currentOffset += 2; break; case Constants.BIPUSH: case Constants.NEWARRAY: methodVisitor.visitIntInsn(opcode, classFileBuffer[currentOffset + 1]); currentOffset += 2; break; case Constants.SIPUSH: methodVisitor.visitIntInsn(opcode, readShort(currentOffset + 1)); currentOffset += 3; break; case Constants.LDC: methodVisitor.visitLdcInsn( readConst(classFileBuffer[currentOffset + 1] & 0xFF, charBuffer)); currentOffset += 2; break; case Constants.LDC_W: case Constants.LDC2_W: methodVisitor.visitLdcInsn(readConst(readUnsignedShort(currentOffset + 1), charBuffer)); currentOffset += 3; break; case Constants.GETSTATIC: case Constants.PUTSTATIC: case Constants.GETFIELD: case Constants.PUTFIELD: case Constants.INVOKEVIRTUAL: case Constants.INVOKESPECIAL: case Constants.INVOKESTATIC: case Constants.INVOKEINTERFACE: { int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)]; int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)]; String owner = readClass(cpInfoOffset, charBuffer); String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); if (opcode < Opcodes.INVOKEVIRTUAL) { methodVisitor.visitFieldInsn(opcode, owner, name, descriptor); } else { boolean isInterface = classFileBuffer[cpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG; methodVisitor.visitMethodInsn(opcode, owner, name, descriptor, isInterface); } if (opcode == Opcodes.INVOKEINTERFACE) { currentOffset += 5; } else { currentOffset += 3; } break; } case Constants.INVOKEDYNAMIC: { int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)]; int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)]; String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); int bootstrapMethodOffset = context.bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)]; Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); Object[] boostrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)]; bootstrapMethodOffset += 4; for (int i = 0; i < boostrapMethodArguments.length; i++) { boostrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); bootstrapMethodOffset += 2; } methodVisitor.visitInvokeDynamicInsn(name, descriptor, handle, boostrapMethodArguments); currentOffset += 5; break; } case Constants.NEW: case Constants.ANEWARRAY: case Constants.CHECKCAST: case Constants.INSTANCEOF: methodVisitor.visitTypeInsn(opcode, readClass(currentOffset + 1, charBuffer)); currentOffset += 3; break; case Constants.IINC: methodVisitor.visitIincInsn( classFileBuffer[currentOffset + 1] & 0xFF, classFileBuffer[currentOffset + 2]); currentOffset += 3; break; case Constants.MULTIANEWARRAY: methodVisitor.visitMultiANewArrayInsn( readClass(currentOffset + 1, charBuffer), classFileBuffer[currentOffset + 3] & 0xFF); currentOffset += 4; break; default: throw new AssertionError(); } // Visit the runtime visible instruction annotations, if any. while (visibleTypeAnnotationOffsets != null && currentVisibleTypeAnnotationIndex < visibleTypeAnnotationOffsets.length && currentVisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) { if (currentVisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) { // Parse the target_type, target_info and target_path fields. int currentAnnotationOffset = readTypeAnnotationTarget( context, visibleTypeAnnotationOffsets[currentVisibleTypeAnnotationIndex]); // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. readElementValues( methodVisitor.visitInsnAnnotation( context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor, /* visible = */ true), currentAnnotationOffset, /* named = */ true, charBuffer); } currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset( visibleTypeAnnotationOffsets, ++currentVisibleTypeAnnotationIndex); } // Visit the runtime invisible instruction annotations, if any. while (invisibleTypeAnnotationOffsets != null && currentInvisibleTypeAnnotationIndex < invisibleTypeAnnotationOffsets.length && currentInvisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) { if (currentInvisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) { // Parse the target_type, target_info and target_path fields. int currentAnnotationOffset = readTypeAnnotationTarget( context, invisibleTypeAnnotationOffsets[currentInvisibleTypeAnnotationIndex]); // Parse the type_index field. String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); currentAnnotationOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. readElementValues( methodVisitor.visitInsnAnnotation( context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor, /* visible = */ false), currentAnnotationOffset, /* named = */ true, charBuffer); } currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset( invisibleTypeAnnotationOffsets, ++currentInvisibleTypeAnnotationIndex); } } if (labels[codeLength] != null) { methodVisitor.visitLabel(labels[codeLength]); } // Visit LocalVariableTable and LocalVariableTypeTable attributes. if (localVariableTableOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) { // The (start_pc, index, signature_index) fields of each entry of the LocalVariableTypeTable. int[] typeTable = null; if (localVariableTypeTableOffset != 0) { typeTable = new int[readUnsignedShort(localVariableTypeTableOffset) * 3]; currentOffset = localVariableTypeTableOffset + 2; int typeTableIndex = typeTable.length; while (typeTableIndex > 0) { // Store the offset of 'signature_index', and the value of 'index' and 'start_pc'. typeTable[--typeTableIndex] = currentOffset + 6; typeTable[--typeTableIndex] = readUnsignedShort(currentOffset + 8); typeTable[--typeTableIndex] = readUnsignedShort(currentOffset); currentOffset += 10; } } int localVariableTableLength = readUnsignedShort(localVariableTableOffset); currentOffset = localVariableTableOffset + 2; while (localVariableTableLength-- > 0) { int startPc = readUnsignedShort(currentOffset); int length = readUnsignedShort(currentOffset + 2); String name = readUTF8(currentOffset + 4, charBuffer); String descriptor = readUTF8(currentOffset + 6, charBuffer); int index = readUnsignedShort(currentOffset + 8); currentOffset += 10; String signature = null; if (typeTable != null) { for (int i = 0; i < typeTable.length; i += 3) { if (typeTable[i] == startPc && typeTable[i + 1] == index) { signature = readUTF8(typeTable[i + 2], charBuffer); break; } } } methodVisitor.visitLocalVariable( name, descriptor, signature, labels[startPc], labels[startPc + length], index); } } // Visit the local variable type annotations of the RuntimeVisibleTypeAnnotations attribute. if (visibleTypeAnnotationOffsets != null) { for (int i = 0; i < visibleTypeAnnotationOffsets.length; ++i) { int targetType = readByte(visibleTypeAnnotationOffsets[i]); if (targetType == TypeReference.LOCAL_VARIABLE || targetType == TypeReference.RESOURCE_VARIABLE) { // Parse the target_type, target_info and target_path fields. currentOffset = readTypeAnnotationTarget(context, visibleTypeAnnotationOffsets[i]); // Parse the type_index field. String annotationDescriptor = readUTF8(currentOffset, charBuffer); currentOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. readElementValues( methodVisitor.visitLocalVariableAnnotation( context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, context.currentLocalVariableAnnotationRangeStarts, context.currentLocalVariableAnnotationRangeEnds, context.currentLocalVariableAnnotationRangeIndices, annotationDescriptor, /* visible = */ true), currentOffset, /* named = */ true, charBuffer); } } } // Visit the local variable type annotations of the RuntimeInvisibleTypeAnnotations attribute. if (invisibleTypeAnnotationOffsets != null) { for (int i = 0; i < invisibleTypeAnnotationOffsets.length; ++i) { int targetType = readByte(visibleTypeAnnotationOffsets[i]); if (targetType == TypeReference.LOCAL_VARIABLE || targetType == TypeReference.RESOURCE_VARIABLE) { // Parse the target_type, target_info and target_path fields. currentOffset = readTypeAnnotationTarget(context, invisibleTypeAnnotationOffsets[i]); // Parse the type_index field. String annotationDescriptor = readUTF8(currentOffset, charBuffer); currentOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. readElementValues( methodVisitor.visitLocalVariableAnnotation( context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, context.currentLocalVariableAnnotationRangeStarts, context.currentLocalVariableAnnotationRangeEnds, context.currentLocalVariableAnnotationRangeIndices, annotationDescriptor, /* visible = */ false), currentOffset, /* named = */ true, charBuffer); } } } // Visit the non standard attributes. while (attributes != null) { // Copy and reset the nextAttribute field so that it can also be used in MethodWriter. Attribute nextAttribute = attributes.nextAttribute; attributes.nextAttribute = null; methodVisitor.visitAttribute(attributes); attributes = nextAttribute; } // Visit the max stack and max locals values. methodVisitor.visitMaxs(maxStack, maxLocals); } /** * Returns the label corresponding to the given bytecode offset. The default implementation of * this method creates a label for the given offset if it has not been already created. * * @param bytecodeOffset a bytecode offset in a method. * @param labels the already created labels, indexed by their offset. If a label already exists * for bytecodeOffset this method must not create a new one. Otherwise it must store the new * label in this array. * @return a non null Label, which must be equal to labels[bytecodeOffset]. */ protected Label readLabel(final int bytecodeOffset, final Label[] labels) { if (labels[bytecodeOffset] == null) { labels[bytecodeOffset] = new Label(); } return labels[bytecodeOffset]; } /** * Creates a label without the {@link Label#FLAG_DEBUG_ONLY} flag set, for the given bytecode * offset. The label is created with a call to {@link #readLabel} and its {@link * Label#FLAG_DEBUG_ONLY} flag is cleared. * * @param bytecodeOffset a bytecode offset in a method. * @param labels the already created labels, indexed by their offset. * @return a Label without the {@link Label#FLAG_DEBUG_ONLY} flag set. */ private Label createLabel(final int bytecodeOffset, final Label[] labels) { Label label = readLabel(bytecodeOffset, labels); label.flags &= ~Label.FLAG_DEBUG_ONLY; return label; } /** * Creates a label with the {@link Label#FLAG_DEBUG_ONLY} flag set, if there is no already * existing label for the given bytecode offset (otherwise does nothing). The label is created * with a call to {@link #readLabel}. * * @param bytecodeOffset a bytecode offset in a method. * @param labels the already created labels, indexed by their offset. */ private void createDebugLabel(final int bytecodeOffset, final Label[] labels) { if (labels[bytecodeOffset] == null) { readLabel(bytecodeOffset, labels).flags |= Label.FLAG_DEBUG_ONLY; } } // ---------------------------------------------------------------------------------------------- // Methods to parse annotations, type annotations and parameter annotations // ---------------------------------------------------------------------------------------------- /** * Parses a Runtime[In]VisibleTypeAnnotations attribute to find the offset of each type_annotation * entry it contains, to find the corresponding labels, and to visit the try catch block * annotations. * * @param methodVisitor the method visitor to be used to visit the try catch block annotations. * @param context information about the class being parsed. * @param runtimeTypeAnnotationsOffset the start offset of a Runtime[In]VisibleTypeAnnotations * attribute, excluding the attribute_info's attribute_name_index and attribute_length fields. * @param visible true if the attribute to parse is a RuntimeVisibleTypeAnnotations attribute, * false it is a RuntimeInvisibleTypeAnnotations attribute. * @return the start offset of each entry of the Runtime[In]VisibleTypeAnnotations_attribute's * 'annotations' array field. */ private int[] readTypeAnnotations( final MethodVisitor methodVisitor, final Context context, final int runtimeTypeAnnotationsOffset, final boolean visible) { char[] charBuffer = context.charBuffer; int currentOffset = runtimeTypeAnnotationsOffset; // Read the num_annotations field and create an array to store the type_annotation offsets. int[] typeAnnotationsOffsets = new int[readUnsignedShort(currentOffset)]; currentOffset += 2; // Parse the 'annotations' array field. for (int i = 0; i < typeAnnotationsOffsets.length; ++i) { typeAnnotationsOffsets[i] = currentOffset; // Parse the type_annotation's target_type and the target_info fields. The size of the // target_info field depends on the value of target_type. int targetType = readInt(currentOffset); switch (targetType >>> 24) { case TypeReference.LOCAL_VARIABLE: case TypeReference.RESOURCE_VARIABLE: // A localvar_target has a variable size, which depends on the value of their table_length // field. It also references bytecode offsets, for which we need labels. int tableLength = readUnsignedShort(currentOffset + 1); currentOffset += 3; while (tableLength-- > 0) { int startPc = readUnsignedShort(currentOffset); int length = readUnsignedShort(currentOffset + 2); // Skip the index field (2 bytes). currentOffset += 6; createLabel(startPc, context.currentMethodLabels); createLabel(startPc + length, context.currentMethodLabels); } break; case TypeReference.CAST: case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: currentOffset += 4; break; case TypeReference.CLASS_EXTENDS: case TypeReference.CLASS_TYPE_PARAMETER_BOUND: case TypeReference.METHOD_TYPE_PARAMETER_BOUND: case TypeReference.THROWS: case TypeReference.EXCEPTION_PARAMETER: case TypeReference.INSTANCEOF: case TypeReference.NEW: case TypeReference.CONSTRUCTOR_REFERENCE: case TypeReference.METHOD_REFERENCE: currentOffset += 3; break; case TypeReference.CLASS_TYPE_PARAMETER: case TypeReference.METHOD_TYPE_PARAMETER: case TypeReference.METHOD_FORMAL_PARAMETER: case TypeReference.FIELD: case TypeReference.METHOD_RETURN: case TypeReference.METHOD_RECEIVER: default: // TypeReference type which can't be used in Code attribute, or which is unknown. throw new IllegalArgumentException(); } // Parse the rest of the type_annotation structure, starting with the target_path structure // (whose size depends on its path_length field). int pathLength = readByte(currentOffset); if ((targetType >>> 24) == TypeReference.EXCEPTION_PARAMETER) { // Parse the target_path structure and create a corresponding TypePath. TypePath path = pathLength == 0 ? null : new TypePath(b, currentOffset); currentOffset += 1 + 2 * pathLength; // Parse the type_index field. String annotationDescriptor = readUTF8(currentOffset, charBuffer); currentOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentOffset = readElementValues( methodVisitor.visitTryCatchAnnotation( targetType & 0xFFFFFF00, path, annotationDescriptor, visible), currentOffset, /* named = */ true, charBuffer); } else { // We don't want to visit the other target_type annotations, so we just skip them (which // requires some parsing because the element_value_pairs array has a variable size). First, // skip the target_path structure: currentOffset += 3 + 2 * pathLength; // Then skip the num_element_value_pairs and element_value_pairs fields (by reading them // with a null AnnotationVisitor). currentOffset = readElementValues( /* annotationVisitor = */ null, currentOffset, /* named = */ true, charBuffer); } } return typeAnnotationsOffsets; } /** * Returns the bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or * -1 if there is no such type_annotation of if it does not have a bytecode offset. * * @param typeAnnotationOffsets the offset of each 'type_annotation' entry in a * Runtime[In]VisibleTypeAnnotations attribute, or null. * @param typeAnnotationIndex the index a 'type_annotation' entry in typeAnnotationOffsets. * @return bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or -1 * if there is no such type_annotation of if it does not have a bytecode offset. */ private int getTypeAnnotationBytecodeOffset( final int[] typeAnnotationOffsets, final int typeAnnotationIndex) { if (typeAnnotationOffsets == null || typeAnnotationIndex >= typeAnnotationOffsets.length || readByte(typeAnnotationOffsets[typeAnnotationIndex]) < TypeReference.INSTANCEOF) { return -1; } return readUnsignedShort(typeAnnotationOffsets[typeAnnotationIndex] + 1); } /** * Parses the header of a JVMS type_annotation structure to extract its target_type, target_info * and target_path (the result is stored in the given context), and returns the start offset of * the rest of the type_annotation structure. * * @param context information about the class being parsed. This is where the extracted * target_type and target_path must be stored. * @param typeAnnotationOffset the start offset of a type_annotation structure. * @return the start offset of the rest of the type_annotation structure. */ private int readTypeAnnotationTarget(final Context context, final int typeAnnotationOffset) { int currentOffset = typeAnnotationOffset; // Parse and store the target_type structure. int targetType = readInt(typeAnnotationOffset); switch (targetType >>> 24) { case TypeReference.CLASS_TYPE_PARAMETER: case TypeReference.METHOD_TYPE_PARAMETER: case TypeReference.METHOD_FORMAL_PARAMETER: targetType &= 0xFFFF0000; currentOffset += 2; break; case TypeReference.FIELD: case TypeReference.METHOD_RETURN: case TypeReference.METHOD_RECEIVER: targetType &= 0xFF000000; currentOffset += 1; break; case TypeReference.LOCAL_VARIABLE: case TypeReference.RESOURCE_VARIABLE: targetType &= 0xFF000000; int tableLength = readUnsignedShort(currentOffset + 1); currentOffset += 3; context.currentLocalVariableAnnotationRangeStarts = new Label[tableLength]; context.currentLocalVariableAnnotationRangeEnds = new Label[tableLength]; context.currentLocalVariableAnnotationRangeIndices = new int[tableLength]; for (int i = 0; i < tableLength; ++i) { int startPc = readUnsignedShort(currentOffset); int length = readUnsignedShort(currentOffset + 2); int index = readUnsignedShort(currentOffset + 4); currentOffset += 6; context.currentLocalVariableAnnotationRangeStarts[i] = createLabel(startPc, context.currentMethodLabels); context.currentLocalVariableAnnotationRangeEnds[i] = createLabel(startPc + length, context.currentMethodLabels); context.currentLocalVariableAnnotationRangeIndices[i] = index; } break; case TypeReference.CAST: case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: targetType &= 0xFF0000FF; currentOffset += 4; break; case TypeReference.CLASS_EXTENDS: case TypeReference.CLASS_TYPE_PARAMETER_BOUND: case TypeReference.METHOD_TYPE_PARAMETER_BOUND: case TypeReference.THROWS: case TypeReference.EXCEPTION_PARAMETER: targetType &= 0xFFFFFF00; currentOffset += 3; break; case TypeReference.INSTANCEOF: case TypeReference.NEW: case TypeReference.CONSTRUCTOR_REFERENCE: case TypeReference.METHOD_REFERENCE: targetType &= 0xFF000000; currentOffset += 3; break; default: throw new IllegalArgumentException(); } context.currentTypeAnnotationTarget = targetType; // Parse and store the target_path structure. int pathLength = readByte(currentOffset); context.currentTypeAnnotationTargetPath = pathLength == 0 ? null : new TypePath(b, currentOffset); // Return the start offset of the rest of the type_annotation structure. return currentOffset + 1 + 2 * pathLength; } /** * Reads a Runtime[In]VisibleParameterAnnotations attribute and makes the given visitor visit it. * * @param methodVisitor the visitor that must visit the parameter annotations. * @param context information about the class being parsed. * @param runtimeParameterAnnotationsOffset the start offset of a * Runtime[In]VisibleParameterAnnotations attribute, excluding the attribute_info's * attribute_name_index and attribute_length fields. * @param visible true if the attribute to parse is a RuntimeVisibleParameterAnnotations * attribute, false it is a RuntimeInvisibleParameterAnnotations attribute. */ private void readParameterAnnotations( final MethodVisitor methodVisitor, final Context context, final int runtimeParameterAnnotationsOffset, final boolean visible) { int currentOffset = runtimeParameterAnnotationsOffset; int numParameters = b[currentOffset++] & 0xFF; methodVisitor.visitAnnotableParameterCount(numParameters, visible); char[] charBuffer = context.charBuffer; for (int i = 0; i < numParameters; ++i) { int numAnnotations = readUnsignedShort(currentOffset); currentOffset += 2; while (numAnnotations-- > 0) { // Parse the type_index field. String annotationDescriptor = readUTF8(currentOffset, charBuffer); currentOffset += 2; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentOffset = readElementValues( methodVisitor.visitParameterAnnotation(i, annotationDescriptor, visible), currentOffset, /* named = */ true, charBuffer); } } } /** * Reads the element values of a JVMS 'annotation' structure and makes the given visitor visit * them. This method can also be used to read the values of the JVMS 'array_value' field of an * annotation's 'element_value'. * * @param annotationVisitor the visitor that must visit the values. * @param annotationOffset the start offset of an 'annotation' structure (excluding its type_index * field) or of an 'array_value' structure. * @param named if the annotation values are named or not. This should be true to parse the values * of a JVMS 'annotation' structure, and false to parse the JVMS 'array_value' of an * annotation's element_value. * @param charBuffer the buffer used to read strings in the constant pool. * @return the end offset of the JVMS 'annotation' or 'array_value' structure. */ private int readElementValues( final AnnotationVisitor annotationVisitor, final int annotationOffset, final boolean named, final char[] charBuffer) { int currentOffset = annotationOffset; // Read the num_element_value_pairs field (or num_values field for an array_value). int numElementValuePairs = readUnsignedShort(currentOffset); currentOffset += 2; if (named) { // Parse the element_value_pairs array. while (numElementValuePairs-- > 0) { String elementName = readUTF8(currentOffset, charBuffer); currentOffset = readElementValue(annotationVisitor, currentOffset + 2, elementName, charBuffer); } } else { // Parse the array_value array. while (numElementValuePairs-- > 0) { currentOffset = readElementValue(annotationVisitor, currentOffset, /* named = */ null, charBuffer); } } if (annotationVisitor != null) { annotationVisitor.visitEnd(); } return currentOffset; } /** * Reads a JVMS 'element_value' structure and makes the given visitor visit it. * * @param annotationVisitor the visitor that must visit the element_value structure. * @param elementValueOffset the start offset in {@link #b} of the element_value structure to be * read. * @param elementName the name of the element_value structure to be read, or <tt>null</tt>. * @param charBuffer the buffer used to read strings in the constant pool. * @return the end offset of the JVMS 'element_value' structure. */ private int readElementValue( final AnnotationVisitor annotationVisitor, final int elementValueOffset, final String elementName, final char[] charBuffer) { int currentOffset = elementValueOffset; if (annotationVisitor == null) { switch (b[currentOffset] & 0xFF) { case 'e': // enum_const_value return currentOffset + 5; case '@': // annotation_value return readElementValues(null, currentOffset + 3, /* named = */ true, charBuffer); case '[': // array_value return readElementValues(null, currentOffset + 1, /* named = */ false, charBuffer); default: return currentOffset + 3; } } switch (b[currentOffset++] & 0xFF) { case 'B': // const_value_index, CONSTANT_Integer annotationVisitor.visit( elementName, (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); currentOffset += 2; break; case 'C': // const_value_index, CONSTANT_Integer annotationVisitor.visit( elementName, (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); currentOffset += 2; break; case 'D': // const_value_index, CONSTANT_Double case 'F': // const_value_index, CONSTANT_Float case 'I': // const_value_index, CONSTANT_Integer case 'J': // const_value_index, CONSTANT_Long annotationVisitor.visit( elementName, readConst(readUnsignedShort(currentOffset), charBuffer)); currentOffset += 2; break; case 'S': // const_value_index, CONSTANT_Integer annotationVisitor.visit( elementName, (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); currentOffset += 2; break; case 'Z': // const_value_index, CONSTANT_Integer annotationVisitor.visit( elementName, readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]) == 0 ? Boolean.FALSE : Boolean.TRUE); currentOffset += 2; break; case 's': // const_value_index, CONSTANT_Utf8 annotationVisitor.visit(elementName, readUTF8(currentOffset, charBuffer)); currentOffset += 2; break; case 'e': // enum_const_value annotationVisitor.visitEnum( elementName, readUTF8(currentOffset, charBuffer), readUTF8(currentOffset + 2, charBuffer)); currentOffset += 4; break; case 'c': // class_info annotationVisitor.visit(elementName, Type.getType(readUTF8(currentOffset, charBuffer))); currentOffset += 2; break; case '@': // annotation_value currentOffset = readElementValues( annotationVisitor.visitAnnotation(elementName, readUTF8(currentOffset, charBuffer)), currentOffset + 2, true, charBuffer); break; case '[': // array_value int numValues = readUnsignedShort(currentOffset); currentOffset += 2; if (numValues == 0) { return readElementValues( annotationVisitor.visitArray(elementName), currentOffset - 2, /* named = */ false, charBuffer); } switch (b[currentOffset] & 0xFF) { case 'B': byte[] byteValues = new byte[numValues]; for (int i = 0; i < numValues; i++) { byteValues[i] = (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); currentOffset += 3; } annotationVisitor.visit(elementName, byteValues); break; case 'Z': boolean[] booleanValues = new boolean[numValues]; for (int i = 0; i < numValues; i++) { booleanValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]) != 0; currentOffset += 3; } annotationVisitor.visit(elementName, booleanValues); break; case 'S': short[] shortValues = new short[numValues]; for (int i = 0; i < numValues; i++) { shortValues[i] = (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); currentOffset += 3; } annotationVisitor.visit(elementName, shortValues); break; case 'C': char[] charValues = new char[numValues]; for (int i = 0; i < numValues; i++) { charValues[i] = (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); currentOffset += 3; } annotationVisitor.visit(elementName, charValues); break; case 'I': int[] intValues = new int[numValues]; for (int i = 0; i < numValues; i++) { intValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); currentOffset += 3; } annotationVisitor.visit(elementName, intValues); break; case 'J': long[] longValues = new long[numValues]; for (int i = 0; i < numValues; i++) { longValues[i] = readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); currentOffset += 3; } annotationVisitor.visit(elementName, longValues); break; case 'F': float[] floatValues = new float[numValues]; for (int i = 0; i < numValues; i++) { floatValues[i] = Float.intBitsToFloat( readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)])); currentOffset += 3; } annotationVisitor.visit(elementName, floatValues); break; case 'D': double[] doubleValues = new double[numValues]; for (int i = 0; i < numValues; i++) { doubleValues[i] = Double.longBitsToDouble( readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)])); currentOffset += 3; } annotationVisitor.visit(elementName, doubleValues); break; default: currentOffset = readElementValues( annotationVisitor.visitArray(elementName), currentOffset - 2, /* named = */ false, charBuffer); break; } break; default: throw new IllegalArgumentException(); } return currentOffset; } // ---------------------------------------------------------------------------------------------- // Methods to parse stack map frames // ---------------------------------------------------------------------------------------------- /** * Computes the implicit frame of the method currently being parsed (as defined in the given * {@link Context}) and stores it in the given context. * * @param context information about the class being parsed. */ private void computeImplicitFrame(final Context context) { String methodDescriptor = context.currentMethodDescriptor; Object[] locals = context.currentFrameLocalTypes; int nLocal = 0; if ((context.currentMethodAccessFlags & Opcodes.ACC_STATIC) == 0) { if ("<init>".equals(context.currentMethodName)) { locals[nLocal++] = Opcodes.UNINITIALIZED_THIS; } else { locals[nLocal++] = readClass(header + 2, context.charBuffer); } } // Parse the method descriptor, one argument type descriptor at each iteration. Start by // skipping the first method descriptor character, which is always '('. int currentMethodDescritorOffset = 1; while (true) { int currentArgumentDescriptorStartOffset = currentMethodDescritorOffset; switch (methodDescriptor.charAt(currentMethodDescritorOffset++)) { case 'Z': case 'C': case 'B': case 'S': case 'I': locals[nLocal++] = Opcodes.INTEGER; break; case 'F': locals[nLocal++] = Opcodes.FLOAT; break; case 'J': locals[nLocal++] = Opcodes.LONG; break; case 'D': locals[nLocal++] = Opcodes.DOUBLE; break; case '[': while (methodDescriptor.charAt(currentMethodDescritorOffset) == '[') { ++currentMethodDescritorOffset; } if (methodDescriptor.charAt(currentMethodDescritorOffset) == 'L') { ++currentMethodDescritorOffset; while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') { ++currentMethodDescritorOffset; } } locals[nLocal++] = methodDescriptor.substring( currentArgumentDescriptorStartOffset, ++currentMethodDescritorOffset); break; case 'L': while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') { ++currentMethodDescritorOffset; } locals[nLocal++] = methodDescriptor.substring( currentArgumentDescriptorStartOffset + 1, currentMethodDescritorOffset++); break; default: context.currentFrameLocalCount = nLocal; return; } } } /** * Reads a JVMS 'stack_map_frame' structure and stores the result in the given {@link Context} * object. This method can also be used to read a full_frame structure, excluding its frame_type * field (this is used to parse the legacy StackMap attributes). * * @param stackMapFrameOffset the start offset in {@link #b} of the stack_map_frame_value * structure to be read, or the start offset of a full_frame structure (excluding its * frame_type field). * @param compressed true to read a 'stack_map_frame' structure, false to read a 'full_frame' * structure without its frame_type field. * @param expand if the stack map frame must be expanded. See {@link #EXPAND_FRAMES}. * @param context where the parsed stack map frame must be stored. * @return the end offset of the JVMS 'stack_map_frame' or 'full_frame' structure. */ private int readStackMapFrame( final int stackMapFrameOffset, final boolean compressed, final boolean expand, final Context context) { int currentOffset = stackMapFrameOffset; final char[] charBuffer = context.charBuffer; final Label[] labels = context.currentMethodLabels; int frameType; if (compressed) { // Read the frame_type field. frameType = b[currentOffset++] & 0xFF; } else { frameType = Frame.FULL_FRAME; context.currentFrameOffset = -1; } int offsetDelta; context.currentFrameLocalCountDelta = 0; if (frameType < Frame.SAME_LOCALS_1_STACK_ITEM_FRAME) { offsetDelta = frameType; context.currentFrameType = Opcodes.F_SAME; context.currentFrameStackCount = 0; } else if (frameType < Frame.RESERVED) { offsetDelta = frameType - Frame.SAME_LOCALS_1_STACK_ITEM_FRAME; currentOffset = readVerificationTypeInfo( currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels); context.currentFrameType = Opcodes.F_SAME1; context.currentFrameStackCount = 1; } else if (frameType >= Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { offsetDelta = readUnsignedShort(currentOffset); currentOffset += 2; if (frameType == Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { currentOffset = readVerificationTypeInfo( currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels); context.currentFrameType = Opcodes.F_SAME1; context.currentFrameStackCount = 1; } else if (frameType >= Frame.CHOP_FRAME && frameType < Frame.SAME_FRAME_EXTENDED) { context.currentFrameType = Opcodes.F_CHOP; context.currentFrameLocalCountDelta = Frame.SAME_FRAME_EXTENDED - frameType; context.currentFrameLocalCount -= context.currentFrameLocalCountDelta; context.currentFrameStackCount = 0; } else if (frameType == Frame.SAME_FRAME_EXTENDED) { context.currentFrameType = Opcodes.F_SAME; context.currentFrameStackCount = 0; } else if (frameType < Frame.FULL_FRAME) { int local = expand ? context.currentFrameLocalCount : 0; for (int k = frameType - Frame.SAME_FRAME_EXTENDED; k > 0; k--) { currentOffset = readVerificationTypeInfo( currentOffset, context.currentFrameLocalTypes, local++, charBuffer, labels); } context.currentFrameType = Opcodes.F_APPEND; context.currentFrameLocalCountDelta = frameType - Frame.SAME_FRAME_EXTENDED; context.currentFrameLocalCount += context.currentFrameLocalCountDelta; context.currentFrameStackCount = 0; } else { final int numberOfLocals = readUnsignedShort(currentOffset); currentOffset += 2; context.currentFrameType = Opcodes.F_FULL; context.currentFrameLocalCountDelta = numberOfLocals; context.currentFrameLocalCount = numberOfLocals; for (int local = 0; local < numberOfLocals; ++local) { currentOffset = readVerificationTypeInfo( currentOffset, context.currentFrameLocalTypes, local, charBuffer, labels); } final int numberOfStackItems = readUnsignedShort(currentOffset); currentOffset += 2; context.currentFrameStackCount = numberOfStackItems; for (int stack = 0; stack < numberOfStackItems; ++stack) { currentOffset = readVerificationTypeInfo( currentOffset, context.currentFrameStackTypes, stack, charBuffer, labels); } } } else { throw new IllegalArgumentException(); } context.currentFrameOffset += offsetDelta + 1; createLabel(context.currentFrameOffset, labels); return currentOffset; } /** * Reads a JVMS 'verification_type_info' structure and stores it at the given index in the given * array. * * @param verificationTypeInfoOffset the start offset of the 'verification_type_info' structure to * read. * @param frame the array where the parsed type must be stored. * @param index the index in 'frame' where the parsed type must be stored. * @param charBuffer the buffer used to read strings in the constant pool. * @param labels the labels of the method currently being parsed, indexed by their offset. If the * parsed type is an ITEM_Uninitialized, a new label for the corresponding NEW instruction is * stored in this array if it does not already exist. * @return the end offset of the JVMS 'verification_type_info' structure. */ private int readVerificationTypeInfo( final int verificationTypeInfoOffset, final Object[] frame, final int index, final char[] charBuffer, final Label[] labels) { int currentOffset = verificationTypeInfoOffset; int tag = b[currentOffset++] & 0xFF; switch (tag) { case Frame.ITEM_TOP: frame[index] = Opcodes.TOP; break; case Frame.ITEM_INTEGER: frame[index] = Opcodes.INTEGER; break; case Frame.ITEM_FLOAT: frame[index] = Opcodes.FLOAT; break; case Frame.ITEM_DOUBLE: frame[index] = Opcodes.DOUBLE; break; case Frame.ITEM_LONG: frame[index] = Opcodes.LONG; break; case Frame.ITEM_NULL: frame[index] = Opcodes.NULL; break; case Frame.ITEM_UNINITIALIZED_THIS: frame[index] = Opcodes.UNINITIALIZED_THIS; break; case Frame.ITEM_OBJECT: frame[index] = readClass(currentOffset, charBuffer); currentOffset += 2; break; case Frame.ITEM_UNINITIALIZED: frame[index] = createLabel(readUnsignedShort(currentOffset), labels); currentOffset += 2; break; default: throw new IllegalArgumentException(); } return currentOffset; } // ---------------------------------------------------------------------------------------------- // Methods to parse attributes // ---------------------------------------------------------------------------------------------- /** * @return the offset in {@link #b} of the first ClassFile's 'attributes' array field entry. */ final int getFirstAttributeOffset() { // Skip the access_flags, this_class, super_class, and interfaces_count fields (using 2 bytes // each), as well as the interfaces array field (2 bytes per interface). int currentOffset = header + 8 + readUnsignedShort(header + 6) * 2; // Read the fields_count field. int fieldsCount = readUnsignedShort(currentOffset); currentOffset += 2; // Skip the 'fields' array field. while (fieldsCount-- > 0) { // Invariant: currentOffset is the offset of a field_info structure. // Skip the access_flags, name_index and descriptor_index fields (2 bytes each), and read the // attributes_count field. int attributesCount = readUnsignedShort(currentOffset + 6); currentOffset += 8; // Skip the 'attributes' array field. while (attributesCount-- > 0) { // Invariant: currentOffset is the offset of an attribute_info structure. // Read the attribute_length field (2 bytes after the start of the attribute_info) and skip // this many bytes, plus 6 for the attribute_name_index and attribute_length fields // (yielding the total size of the attribute_info structure). currentOffset += 6 + readInt(currentOffset + 2); } } // Skip the methods_count and 'methods' fields, using the same method as above. int methodsCount = readUnsignedShort(currentOffset); currentOffset += 2; while (methodsCount-- > 0) { int attributesCount = readUnsignedShort(currentOffset + 6); currentOffset += 8; while (attributesCount-- > 0) { currentOffset += 6 + readInt(currentOffset + 2); } } // Skip the ClassFile's attributes_count field. return currentOffset + 2; } /** * Reads a non standard JVMS 'attribute' structure in {@link #b}. * * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of * the class. Any attribute whose type is not equal to the type of one the prototypes will not * be parsed: its byte array value will be passed unchanged to the ClassWriter. * @param type the type of the attribute. * @param offset the start offset of the JVMS 'attribute' structure in {@link #b}. The 6 attribute * header bytes (attribute_name_index and attribute_length) are not taken into account here. * @param length the length of the attribute's content (excluding the 6 attribute header bytes). * @param charBuffer the buffer to be used to read strings in the constant pool. * @param codeAttributeOffset the start offset of the enclosing Code attribute in {@link #b}, or * -1 if the attribute to be read is not a code attribute. The 6 attribute header bytes * (attribute_name_index and attribute_length) are not taken into account here. * @param labels the labels of the method's code, or <tt>null</tt> if the attribute to be read is * not a code attribute. * @return the attribute that has been read. */ private Attribute readAttribute( final Attribute[] attributePrototypes, final String type, final int offset, final int length, final char[] charBuffer, final int codeAttributeOffset, final Label[] labels) { for (int i = 0; i < attributePrototypes.length; ++i) { if (attributePrototypes[i].type.equals(type)) { return attributePrototypes[i].read( this, offset, length, charBuffer, codeAttributeOffset, labels); } } return new Attribute(type).read(this, offset, length, null, -1, null); } // ----------------------------------------------------------------------------------------------- // Utility methods: low level parsing // ----------------------------------------------------------------------------------------------- /** * Returns the number of entries in the class's constant pool table. * * @return the number of entries in the class's constant pool table. */ public int getItemCount() { return cpInfoOffsets.length; } /** * Returns the start offset in {@link #b} of a JVMS 'cp_info' structure (i.e. a constant pool * entry), plus one. <i>This method is intended for {@link Attribute} sub classes, and is normally * not needed by class generators or adapters.</i> * * @param constantPoolEntryIndex the index a constant pool entry in the class's constant pool * table. * @return the start offset in {@link #b} of the corresponding JVMS 'cp_info' structure, plus one. */ public int getItem(final int constantPoolEntryIndex) { return cpInfoOffsets[constantPoolEntryIndex]; } /** * Returns a conservative estimate of the maximum length of the strings contained in the class's * constant pool table. * * @return a conservative estimate of the maximum length of the strings contained in the class's * constant pool table. */ public int getMaxStringLength() { return maxStringLength; } /** * Reads a byte value in {@link #b}. <i>This method is intended for {@link Attribute} sub classes, * and is normally not needed by class generators or adapters.</i> * * @param offset the start offset of the value to be read in {@link #b}. * @return the read value. */ public int readByte(final int offset) { return b[offset] & 0xFF; } /** * Reads an unsigned short value in {@link #b}. <i>This method is intended for {@link Attribute} * sub classes, and is normally not needed by class generators or adapters.</i> * * @param offset the start index of the value to be read in {@link #b}. * @return the read value. */ public int readUnsignedShort(final int offset) { byte[] classFileBuffer = b; return ((classFileBuffer[offset] & 0xFF) << 8) | (classFileBuffer[offset + 1] & 0xFF); } /** * Reads a signed short value in {@link #b}. <i>This method is intended for {@link Attribute} sub * classes, and is normally not needed by class generators or adapters.</i> * * @param offset the start offset of the value to be read in {@link #b}. * @return the read value. */ public short readShort(final int offset) { byte[] classFileBuffer = b; return (short) (((classFileBuffer[offset] & 0xFF) << 8) | (classFileBuffer[offset + 1] & 0xFF)); } /** * Reads a signed int value in {@link #b}. <i>This method is intended for {@link Attribute} sub * classes, and is normally not needed by class generators or adapters.</i> * * @param offset the start offset of the value to be read in {@link #b}. * @return the read value. */ public int readInt(final int offset) { byte[] classFileBuffer = b; return ((classFileBuffer[offset] & 0xFF) << 24) | ((classFileBuffer[offset + 1] & 0xFF) << 16) | ((classFileBuffer[offset + 2] & 0xFF) << 8) | (classFileBuffer[offset + 3] & 0xFF); } /** * Reads a signed long value in {@link #b}. <i>This method is intended for {@link Attribute} sub * classes, and is normally not needed by class generators or adapters.</i> * * @param offset the start offset of the value to be read in {@link #b}. * @return the read value. */ public long readLong(final int offset) { long l1 = readInt(offset); long l0 = readInt(offset + 4) & 0xFFFFFFFFL; return (l1 << 32) | l0; } /** * Reads a CONSTANT_Utf8 constant pool entry in {@link #b}. <i>This method is intended for {@link * Attribute} sub classes, and is normally not needed by class generators or adapters.</i> * * @param offset the start offset of an unsigned short value in {@link #b}, whose value is the * index of a CONSTANT_Utf8 entry in the class's constant pool table. * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently * large. It is not automatically resized. * @return the String corresponding to the specified CONSTANT_Utf8 entry. */ public String readUTF8(final int offset, final char[] charBuffer) { int constantPoolEntryIndex = readUnsignedShort(offset); if (offset == 0 || constantPoolEntryIndex == 0) { return null; } return readUTF(constantPoolEntryIndex, charBuffer); } /** * Reads a CONSTANT_Utf8 constant pool entry in {@link #b}. * * @param constantPoolEntryIndex the index of a CONSTANT_Utf8 entry in the class's constant pool * table. * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently * large. It is not automatically resized. * @return the String corresponding to the specified CONSTANT_Utf8 entry. */ final String readUTF(final int constantPoolEntryIndex, final char[] charBuffer) { String value = constantUtf8Values[constantPoolEntryIndex]; if (value != null) { return value; } int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex]; return constantUtf8Values[constantPoolEntryIndex] = readUTF(cpInfoOffset + 2, readUnsignedShort(cpInfoOffset), charBuffer); } /** * Reads an UTF8 string in {@link #b}. * * @param utfOffset the start offset of the UTF8 string to be read. * @param utfLength the length of the UTF8 string to be read. * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently * large. It is not automatically resized. * @return the String corresponding to the specified UTF8 string. */ private String readUTF(final int utfOffset, final int utfLength, final char[] charBuffer) { int currentOffset = utfOffset; int endOffset = currentOffset + utfLength; int strLength = 0; byte[] classFileBuffer = b; while (currentOffset < endOffset) { int currentByte = classFileBuffer[currentOffset++]; if ((currentByte & 0x80) == 0) { charBuffer[strLength++] = (char) (currentByte & 0x7F); } else if ((currentByte & 0xE0) == 0xC0) { charBuffer[strLength++] = (char) (((currentByte & 0x1F) << 6) + (classFileBuffer[currentOffset++] & 0x3F)); } else { charBuffer[strLength++] = (char) (((currentByte & 0xF) << 12) + ((classFileBuffer[currentOffset++] & 0x3F) << 6) + (classFileBuffer[currentOffset++] & 0x3F)); } } return new String(charBuffer, 0, strLength); } /** * Reads a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, CONSTANT_Module or * CONSTANT_Package constant pool entry in {@link #b}. <i>This method is intended for {@link * Attribute} sub classes, and is normally not needed by class generators or adapters.</i> * * @param offset the start offset of an unsigned short value in {@link #b}, whose value is the * index of a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, CONSTANT_Module or * CONSTANT_Package entry in class's constant pool table. * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently * large. It is not automatically resized. * @return the String corresponding to the specified constant pool entry. */ private String readStringish(final int offset, final char[] charBuffer) { // Get the start offset of the cp_info structure (plus one), and read the CONSTANT_Utf8 entry // designated by the first two bytes of this cp_info. return readUTF8(cpInfoOffsets[readUnsignedShort(offset)], charBuffer); } /** * Reads a CONSTANT_Class constant pool entry in {@link #b}. <i>This method is intended for {@link * Attribute} sub classes, and is normally not needed by class generators or adapters.</i> * * @param offset the start offset of an unsigned short value in {@link #b}, whose value is the * index of a CONSTANT_Class entry in class's constant pool table. * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently * large. It is not automatically resized. * @return the String corresponding to the specified CONSTANT_Class entry. */ public String readClass(final int offset, final char[] charBuffer) { return readStringish(offset, charBuffer); } /** * Reads a CONSTANT_Module constant pool entry in {@link #b}. <i>This method is intended for * {@link Attribute} sub classes, and is normally not needed by class generators or adapters.</i> * * @param offset the start offset of an unsigned short value in {@link #b}, whose value is the * index of a CONSTANT_Module entry in class's constant pool table. * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently * large. It is not automatically resized. * @return the String corresponding to the specified CONSTANT_Module entry. */ public String readModule(final int offset, final char[] charBuffer) { return readStringish(offset, charBuffer); } /** * Reads a CONSTANT_Package constant pool entry in {@link #b}. <i>This method is intended for * {@link Attribute} sub classes, and is normally not needed by class generators or adapters.</i> * * @param offset the start offset of an unsigned short value in {@link #b}, whose value is the * index of a CONSTANT_Package entry in class's constant pool table. * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently * large. It is not automatically resized. * @return the String corresponding to the specified CONSTANT_Package entry. */ public String readPackage(final int offset, final char[] charBuffer) { return readStringish(offset, charBuffer); } /** * Reads a numeric or string constant pool entry in {@link #b}. <i>This method is intended for * {@link Attribute} sub classes, and is normally not needed by class generators or adapters.</i> * * @param constantPoolEntryIndex the index of a CONSTANT_Integer, CONSTANT_Float, CONSTANT_Long, * CONSTANT_Double, CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType or * CONSTANT_MethodHandle entry in the class's constant pool. * @param charBuffer the buffer to be used to read strings. This buffer must be sufficiently * large. It is not automatically resized. * @return the {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String}, * {@link Type} or {@link Handle} corresponding to the specified constant pool entry. */ public Object readConst(final int constantPoolEntryIndex, final char[] charBuffer) { int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex]; switch (b[cpInfoOffset - 1]) { case Symbol.CONSTANT_INTEGER_TAG: return readInt(cpInfoOffset); case Symbol.CONSTANT_FLOAT_TAG: return Float.intBitsToFloat(readInt(cpInfoOffset)); case Symbol.CONSTANT_LONG_TAG: return readLong(cpInfoOffset); case Symbol.CONSTANT_DOUBLE_TAG: return Double.longBitsToDouble(readLong(cpInfoOffset)); case Symbol.CONSTANT_CLASS_TAG: return Type.getObjectType(readUTF8(cpInfoOffset, charBuffer)); case Symbol.CONSTANT_STRING_TAG: return readUTF8(cpInfoOffset, charBuffer); case Symbol.CONSTANT_METHOD_TYPE_TAG: return Type.getMethodType(readUTF8(cpInfoOffset, charBuffer)); case Symbol.CONSTANT_METHOD_HANDLE_TAG: int referenceKind = readByte(cpInfoOffset); int referenceCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 1)]; int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(referenceCpInfoOffset + 2)]; String owner = readClass(referenceCpInfoOffset, charBuffer); String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); boolean isInterface = b[referenceCpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG; return new Handle(referenceKind, owner, name, descriptor, isInterface); default: throw new IllegalArgumentException(); } } }
2aff025ad17cbfaa368f1e4ac9645c7baaafe3ef
1a4106be6527079cbbf410ca30b9a66bc93763b7
/fix-engine/src/main/java/me/kolek/fix/engine/FixEngineCallback.java
f9227aaf75a852d73c8b4cb31966f3a431ded811
[]
no_license
Sudarsan-Sridharan/java-fix
34597c359a730769f8d092735784c5ac0854cf8f
136b702aeb61d104b013e3ffa7d9aa807c59fd6a
refs/heads/master
2020-07-06T19:06:52.681992
2018-02-14T20:08:36
2018-02-14T20:08:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
218
java
package me.kolek.fix.engine; import java.rmi.Remote; import java.rmi.RemoteException; public interface FixEngineCallback extends Remote { void onSessionAvailable(FixSessionId sessionId) throws RemoteException; }
1c1191076609a453d190d53a9803b993156bea90
51934a954934c21cae6a8482a6f5e6c3b3bd5c5a
/output/995379540b8b4bb09ee2f34de7f3105b.java
0259d2c4cfb9d5080a8c35bd5148307fa16c88a3
[ "MIT", "Apache-2.0" ]
permissive
comprakt/comprakt-fuzz-tests
e8c954d94b4f4615c856fd3108010011610a5f73
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
refs/heads/master
2021-09-25T15:29:58.589346
2018-10-23T17:33:46
2018-10-23T17:33:46
154,370,249
0
0
null
null
null
null
UTF-8
Java
false
false
23,075
java
class g { } class v2LdAB { public static void _t_Jmxx (String[] MglEqp3uDgyx) throws Sk { void nJWv = !new tnqCld81PiaS()[ null._rOriy65mdUfr6()] = !082335.T56uBOR; void[] zoDPVy1eWVB = !-mqGqF4gBbsKn_Q[ !vuTn0.Nfp0]; void eLb8f = S8aRsjVs[ -new qOeSv().XspF()] = !false.yO2(); } } class LoSfUaPh { public static void u9kY56RhX2mbk (String[] BsG) throws PU { void[][] EZZys = uLNuFp().tc() = new xsJp[ --new DFO11RVQLw4S8[ !( -this.LtA)[ -!false[ null[ new xfHcTR48WtWNfb().Hm2G4()]]]].myFRRv1a].RwkJxpw2JDTxu; ; ; if ( --!tJigrHhCb_tp().JiJc159Tts4ll9()) { return; } !!fL().cpoed8ux4; { return; boolean liQsRgIlLkaByY; if ( ( !true.ewUP())[ !-!!-false.Cx9j7wNN()]) if ( !86620.N()) return; o3OoAr().EZWdmtgY5Uku1; while ( null[ -this.fD0JLRRk()]) 270[ ( new lnL().GFnfPgXqaQn()).wd()]; return; fn[] ze6; if ( !-new gcI8().keA8LU4xE) !!!new int[ new eqfLUcyJTFMLI6().wRsqBZzednlc()][ -!!new wLKJgiQL908MF0()[ afU1R[ tRRJP30hHxHw.SbpL0ntPEmG()]]]; return; ; void[] Dg; ( null.QAZ).V3IWrqXQmZNv(); !!IPW2Z.duVKmA5aMkx; return; { if ( 65277.FhaVHoEr8) { ; } } ; while ( !!this[ !!7200703[ VM2cNF9zS.YrrW6()]]) if ( !false.ewPw) if ( W9Kn.f_d1fTXZKGI7CL) ; null.MsLejIs(); int VX; } { void EwTuNjWG; void VpcT9Dcgsi; { null[ !-new void[ new int[ !!true[ !-!hNHsUPiqN().iNsnyUdJh()]].dVeWbPDTuSOV].v2alu30yahOjtx()]; } if ( -332487.slpIVPAyf()) return; boolean[] j_Pv5eE0DnEYTU; void[][][][] wivG; if ( new B9M8IMn6LAfOG[ !!null.aC3qEwcyoJr][ RWeMlGa().RTq72fds()]) ---true[ !--oXvw_AW7TDT[ !!true.o743O()]]; { void sxI4t1ErCWee; } while ( this[ this[ true.HWNTZ_XP8L]]) if ( ENyUVusjwu4tHp.k_P4wVw) ; ; } 694983.aQyKW_6Vd; int[] x; } public static void eY4ukT_0T9 (String[] gXHo871L510) { int[][][][] CcaajZaE; zpQy_QV32pr Ny0FPZLikThwS4; boolean ljGRDOcv_jYk = -8422[ itlWdnnzN93LV()[ -!-!yhKFM9MzZd().iytIH]] = 342838345.b76l_wjkNT6(); boolean y4yOKZGpbQQvy; int[][] vk4IUYmq; while ( null.xe()) ; int CU = this.V3; return !--!null.MobzRLD59AjU(); while ( new dKwzGYP[ true.PpD()].F3i7hXPckf()) if ( ( this[ --true.EsFbixN]).BC) if ( FqQf().r()) { ; } void[] HkH = J9ejdFT().jlYMwNjF() = -new void[ -true.ReiruEA()][ ( new boolean[ egv3BVJtP.uBe9yk6rUYN].T3()).I()]; int vW8a; int zfCGRGI0J_lLe = ffY1I3nzA()[ ( null.A4xBOz1Y())[ qv()[ -new s1DKqn[ new boolean[ -( false[ new Gn5y().y6CYLu8Py()])[ new M3JdBtX().bsNkjb]].g][ !-new boolean[ ( -tcFf().BBnKaHQ4ae8MJ).Ieqoek5dM6ELv][ this[ jxvMp77x().RIDouCr1iobM75]]]]]]; -!null[ false.b7]; return; jJVn3 bp = -!!false.NGE; while ( new int[ this._7Y0T6S3cSso][ D8UhXExu._]) { rebJeAHWvRd S1uCleHc; } } public int[] w99ilT; public boolean[] VH () throws BP3EFIUO { Fdr9o3JvFT SMb15mhD; tV3[][] DPD3wIc; while ( -new V_XsUS4El().PWHB9Cpsa()) !!!-np[ !-!QQD981m()[ j62tiBBBKSI.QawYGNKaM()]]; while ( -false.zYoim4q59Ms) !!95673691.f; int M0Mr; FcDJxo[] YsAeHNi5AVgKD3; Q[] t9KhqkiSp75; void dA = null.CbFtwj; if ( ( !-!--new int[ false.yc7l1eNE_yaE][ !-null.v])[ true.zSaf5KsbR3Iqf()]) if ( !zEZ44xEkM6rV().yOVPY8) ;else { boolean[][] gIDcb2bXH0CZN0; } int lbEl17Mr = 73.Di_aB(); if ( this[ true.MLqTGV()]) { void WxpPu7P2w; } return -!!!true.yie5QDVF(); void ofV8MIkeLfu; while ( 31[ -!-!this.e_B4NE9]) return; } public static void Ozh2MV46mv6nG2 (String[] spRJZjhBLM0tH) { return -true.LSI; ; while ( new boolean[ -!4444243[ ( true[ 75[ ff.NhHC5EiI]])[ mqNhmOvDRixas.eypL35whW()]]][ true.Kl_K1LiO8KS]) { ; } { -!-true.xv1; G8[][][][] CL3kdd2jF4f; } -new t().e9dL7qf; if ( true.XM6Jy5I1zc()) if ( this.wAktRVh()) ;else ; if ( null.c()) -new mqYBA().oFoPoew();else if ( -!!-_u9K9qxXV.BHg3F7()) if ( null[ --null[ --!!!( false[ !!( ( !--!-!-2836.P9_uDQRF71ii()).NGO1bvLb2).rlk()]).x78bhoUDvWo]]) ( ----28104[ TlZ9DJ4iQnSR1().Js6rXR2M()]).Dti3M88beP; RKx[][][] JWnNcXGZU; return; while ( !!--null[ 77075.A8p]) while ( -new O9mQ()[ -!!( !-!-false.jEtQoAnJXR()).PcOuKLnbu1HlUj()]) while ( false.H8saWrghR9Cn()) ; int[][][][][][][][][] vzXXOmEuRMLi = ( -null.FbuOIDWB4Zbe()).dxQK = O3JjpBBcovIYIQ.uV; } public cx5_afr8WK[] GNXfy () { boolean[][] L6WmKuoOySKu1 = !---( false.xDkQCJf1).Q; boolean[][] Ywbynz9B8q7 = !!MvqDA0UzvVN.G5QyU(); int CBrKZJ8klEI = -57448[ VW4jCkOsEwUbSZ()[ 78161.qnNN9Y0QpIDqFe]]; return; void bF11; return !this.MJD4(); jkeObE7kfP0r S; boolean XaDuCKya = ( false._aIMbJdzgZ1S()).Wt6njUIE; } public kdvEoklgq[] sUVaPsN; public void[][][] F; public pK6dgv[] S3nMVPE () throws FthJM9rxizyYc { !!this.xybxMd(); BFZXdZ3uWGtBQD[] kvgc3CN_CrCo = false[ -null.e] = !-this.Y(); { qpQb().tXvRW9mBF(); { WibBAAmJ TZbAi3d; } void qc; void VHrUAphGCIRb; return; ; } void Jxj6Q2sK = KOdYe4.EEu2ls() = true.SJGBSFFc9jjxe(); Wie3xj5[] xYe2Uu_vp; boolean juihv3rB = --new boolean[ !!false.d_y].Yf3J; boolean F85e; int[][] X = null[ -this[ Kxc.ZMK0()]]; { boolean[][] Ck_ms; void[][] Y3J; return; } int[] ncoAqhXF1NbMas; return new void[ new int[ !--true[ !null[ qFe[ !true.U5()]]]].yWf5].M4s; boolean tQc = G4kM3().b7OLCm3DP; ( -true.v7ipJXuKKg())[ -!false.A54izhBs]; --this.c8gU(); void I; while ( V7()[ !-!VBPndJ4kd1hT.j8rJYENK]) if ( --gLkptmpx.fD0Xkx) while ( !true.U95MvHFGjzLU1()) ; void[][][] pgJW; boolean BTYP8PaX3ph3Q; } public s14j LOraLv; public static void tyHlR (String[] ZKzVIRk) throws o { z0j().G05QC(); --new ZPuQWi942iREt[ ( !ZeY.eRUff).BrKCQnSMv()][ !D0jYL[ !true.PI()]]; false[ ---new int[ Ipcd4K_XnWyKO()[ -!-true.dlBw()]].sMQ6v5V]; int[] iKqeP1AKTgM = 63.hfIZm4Z4t1 = !true.mer9_At; ; if ( new XFvfZdfxyEMjB()[ !true.hY]) if ( !!( !false.FZ3oJfwJ()).ym8P3afxv()) ;else while ( !478[ -true[ !false.Flyn()]]) { int IdkHjSGuJH; } !p_.Rg(); if ( -!new boolean[ !new MKmXZcE6ir().kvP7m()][ -( !!EtpFwp0rg().x6jKx4a())[ !!!!!-!!true[ !5[ new PWBHV()[ 86546[ Fbyy1aP()[ --x[ new du2[ jGA7SAWs7z().FxJUT].SxM8jqhO8ei()]]]]]]]]) while ( -new void[ --Cc29nYsJxXmmgw.ceMGLPzgaxl4()][ !!--false.QVWts54DLBulwi()]) if ( -sZ().vA) return;else while ( !-null.gGOfQVHn) return; ; -jCEI3WBkO1WCpT.sMJy3ugWUGvM; void[][][][] l4xkiN_ = -null.vD37FLk5() = !-!!!642.HP7zxpiz31hzsE(); } public int Iz264yEdwrCt (int fN0NuYKOdc, A[][] u9qmhxVa0cSOm1, void[] Df, boolean BEeCV, void A, QFXlXa_hCo6pls[][] i) throws _88F { new void[ this[ this.GL0QsNN()]].J(); return; CtAIr ht; void[][] MsyI6JPLRSF = !iUlhiFYi9mjg1F.jry6JYrA7kU7Om = !!( this.pRv7byOJ).krU6Z6cR46(); int mBBlSinc; Po22ZK0 JQrQ5XY8_b4 = -this.saCRSwDpTWzO = -600687885.Hjg4Z_7yRz6p; { ; while ( -true[ ( -!this.k50m()).pchg]) while ( !!!true[ !!5.miia_Uh]) { if ( EllT4z3().oCNqnz4MyxlTqQ) if ( true.f6) { boolean[][] XpAGpbS7VwYt; } } boolean[][] S; void U9jiVmBmEm; void Uk7rcdgZ7; boolean gtsJOyA; while ( M3Kx_w.PwORNtB()) while ( this.HsD()) -!null.m_JaoZ; void[] QGFV4_J6jzwf; if ( !-true.A()) ; { while ( -!OHsey().eOy8buQD()) return; } iVHCsEWfORgTO5[][] _JRiGD9wkIL; int[] BtYe; boolean[][] dqVB3H4Djb; boolean[][] sO3qFXMDbAkfmO; int X0DuqpTyxLi; ; --!-pIPR5SczvyTf().ffZz; v F8HL6xjlzsY3N; if ( --!( new gIV9yGqw2oq()[ -U97NmvNO()[ null.Kw_kJL()]]).Pd9fq) { while ( !!new int[ false.bzG6cj_Gd2()][ -new Bs1Oyb[ null.TrRvBFETs0Inzh()][ !this[ true.bfL5A()]]]) { int[] ItGmKVtdwyO; } } } { void[][] n; void aaHh; while ( false.d_H1f()) while ( null.V3R8cgK) { { boolean[] n3DcqMR1iUL3nR; } } mWmxxOSRUuY().D_OQYQTeZ3Et; if ( -new boolean[ true.Nubjx7OB].anONI) if ( HQrjbGEzQtjnk().XFtBY()) while ( !-new boolean[ RB()[ !LIIUd1clF3M().X()]].bsnoWrVi) { return; } void[][][] j8sC3qhHLsq; if ( !-LVrd()[ ---true.Lv]) -SY[ new boolean[ 8633614.HAe2eCMqRvAS8].xcs]; boolean AnXElKreqzh; if ( false.ARxHMfyX4ALRc()) -!( ----new RVg1deO2[ -835[ !kJ4P.tR6hi()]].cE6ps9BU)[ !false.g70YHCiztT0Wt]; boolean p2_tNv; } boolean[][] QeDI; cMI De6LT99CD = true.Q9RODBuWPCLIN() = --null[ --true.XUA()]; } public boolean[][] X9 () throws Mm_o6NOEJeD2 { true.i3gp24R_; zqe4v1ygNJ()[ new int[ -new ZHGbVZ[ new void[ null[ -!7421215.RoYvkHM]][ !-( ( -vo041mlM3zL1c.lQuIzLlQZP6Rx3()).nFG).vhVP6at]].cXliUeic][ -( false[ new Lo().yuHHmLqChbOGoS]).vIJvlmaoK2()]]; iYVchb[] kcFT = -new VL4Zcg_e7PAL2().bE4(); { { -( qv9rJZ4advMqh()[ new lU().LlpSraChlrkRbq]).TzxHmZWpI7zl; } boolean pzhP_VE; int JS78DOv3PPA; e5[] UmtKzcJ2z9; { boolean p; } while ( null.xg1rBJ()) return; ; if ( !!true.bffQl6C) ; IAPlI yax; if ( !!!true.HV8ywd_aHft) return; } SbB35UrRh[] lo4T = QJLgTzlD0ZU[ --!false.qZNxXLOR] = !D9NLD2B6yd().RvhDswrQ83O; while ( new Qj()[ !( ( null[ !8639918[ -true.eGEq3JvFq]])[ !-!!-this.nEWqklnMeIPG()]).OuUZuL]) true.KZQFIW8D8P(); return; int zyKu5obNUTd1 = new void[ !-new ret9()[ -!-8750[ this.u2]]].rRueVHkWyGk(); } public static void v4ZFxAKMZ7cR6 (String[] rhBA0yq9) { int dnDApQaogvdZr = new T[ EnW4f3S0mGe.jA()].gNAfh = -t8_MbYx().e3UN6KGDG; return !this[ -new RY71DN()[ -true.Rh4KUWD_FZ]]; new kwNTY5k[ 3233393[ -!-this.iLFcVc()]][ !!null.o]; if ( tICfb8g0Dr[ !!8271152.UUviE351Q]) { boolean[] gRHFuo; } boolean[] TpjOr0mPwuj = !true.yMRML8ZMbfM; ; void[][] zxF2DPi; int y4v7ibxZNquGm8; while ( -!!!!-( --this.a4T5STiW9Y2tq)[ 792221.dQRKL3n1exBS()]) { void[] QhzXPDtRVV; } ; int[][] Z66B49ZehkwgK; while ( !null.PbKmw()) if ( !wXG9.Q8qLjLl) -false.eClWYrWh62e; int[] gyNcMonLT448P6; EsaL9 i5iuZOyW = !null[ !-null[ RGVHTf_i0d[ ( -!!!this.tiKPsEIT()).s_()]]]; return !this.fdxqcGQZ5SW_M(); d9m[] JkYU29Hyvd = -!!new A3iDnfssgzh().gnc() = !-!!null.kHfT; } } class P5gx { public static void Njz (String[] X0L) { return; void Lke_kz; } public static void cB (String[] lsAg) throws v3mRjLMDWr { ; MAlceU6RtWF TJ = !this.HJsep(); x[] N; } public eIXOdLwKaM KjT; public lqxz5qfC2duea[] B8I6RWcvIPz; public static void sSD (String[] B3cc8) { return; int[] oK9ndvllXhDb1 = -MMmwwisnuAcJQ().cMjihrnChdU = -!!!!3.gLJiN0RGhRww6l(); int WaEFeG2 = 41379.nAbDEb = -this[ false.u]; void[] GPKc4k8 = _hmG.IfTef() = ---true.PjDuErd; if ( !1[ LXV().cp8src()]) return; while ( null.g16mVJbq9j()) { while ( ---!true.D()) ; } int[][] eddBylLl8CufR = !new PJxbTwPlfCXSx()[ true[ !new boolean[ 66374[ -mRg02MnHAN5W8()[ -!!new Q5x_WuGH5bv0MG().LS]]].NCVDujyyIRhRs4]]; int etcPxFjmE = ( -7607440.fH3BHS6cj3dneZ).y57e0dXP4buTr() = this[ !-yO6Hbk9jZIvI().TXi0u0fA]; pO9y0w()[ new boolean[ --false[ true.gtz()]].MQ]; true.rPavmha(); while ( -new d2haJ[ new x4C95Tw9Rs4()[ -new R1Mh1JuE08().R5R02XfU]].wa()) { int[] p2J; } if ( !TND.HiIBehB()) null.OjFe0t();else while ( true.ETjy4grCqQ) this[ ( true.hEhkSf9WhRSZZ).KQzPFZ_Ioam]; void[] Z5vHlxs4ebs; return ( 573743[ new Y4BN4fN_DqrhX()[ null[ -new boolean[ 32851.R1WO()].cjVkpLfNw()]]]).JTJNUzGb9HCGs; boolean[][] pV1BZv1ldVmjL; int[][][] DOV5RfRgAao7; } public void _ub; public static void VfPIzoEs (String[] EIop4nStn) throws WYT8w_VKhu { yc_sncel32s75[][] gakhX; } public static void Cy391Yj (String[] IICF7) throws oH9HZg { { boolean[] BnLm; HeAYfxCjY9hkV j6XG4F4; new boolean[ -01016.Q0u82CO7Xb()].Z14ud0(); if ( new boolean[ --!34963[ -O_9yL_2tgSCbYu.ynroA9yB0k1T()]][ -!false[ this.e()]]) return; ; return; return; boolean TKFLYxC; int[] UjubIvQvTo; ; ; void qNbdzyNI4Wi; ; return; void[][][][] xe; if ( !!!!-true.MJPLB0jY()) { if ( Mpns()[ !--false.TFq()]) return; } return; while ( ( -true[ 6042.g5tyCiQd]).vEbA8rv_no()) return; } boolean o0ndZ; boolean[] mKuZ9Ni; int VngB3A_LbgsZfs = !6336278.NC4oV7V() = ---!-!false.fdwJrQ; void Ms1r60j9gn6nu_ = --8874[ -044502[ -!this.boC()]]; int DfF_Tnj; return; { { QN9_tBIBqKXv ysH8usIC6Tc; } { DjG7YmJ6LxLF yswbYneL_x; } int j2UyaEeW; if ( -new Z6mb0KgzbU[ this.iYdKH].PzLaFhU96G) if ( -!--k7qh7b8()[ this[ HaDT8boi.S]]) while ( !!new k67()._306XEqTIIiJ()) while ( true[ 0677005.Jd()]) while ( !null.teCx()) ; { return; } int iHRot3QJgeMRy; ; int JayNQIl; if ( --new bruyRnQ().SH6X8GC90Z()) 83308.Rr5Mfq44; while ( !!sl07_3XcvGsB.x9()) if ( ( null[ !( ( ( false.j2Q3f())[ ( !!!this.Pt3zCe)[ new void[ this.LtMElq7MU1TwiR].gB]])[ -this[ ---false.HtkZ_5]]).iVZpAXNq1miTC]).PGPhV7dIXMHoU()) new Zs().euBnxfO1vkoL; } TQrKPxcaT[][] UYrNHJ8WKiE69; boolean[][][][][] lMnJYoH7Gq = -true[ false[ !new zVv1bxl4EhQq().Z()]]; boolean pw0HWHc; return; int A1YwN1nRxEvih; } public void[][] hZZSXHS86u (int jfvfiCOc3, int[] X3CNLWXzxf, boolean[] L2VQEiyIvjHPD, Zb[] Y7EqjecRqQLyv, void VueMWAU6EQH5k, void NMiYvA4) throws i6piU0n { if ( true.Wn5_MYG_B()) -!( -true.z())[ !!true.Khw()]; void[] l; boolean dI0TKAV0PT; int mUYEUYJR3IZ80; if ( !-!-this.HkV) if ( -new zVCV_VKnl8().HWT8zh) ---!-!!!o[ -new fzd_().Wd_JV3MNZKsm7]; if ( -this.SyJ4WiWFOkWK()) 3972.vaoCKgHrbLb7C; } public boolean[] _LVyp5W; public mnsP[][][][] OJ95; public void KLarTmKpPYRbz () throws QMYx6 { new int[ !new void[ --!-true.ghpwDrFx()].f()][ !-!false.qAc_5]; if ( !!new U7eBbEhvzG().l1gVuVQEx2YEw7) return; void[][] b8EJKbHkEYNI5; return; { !-new int[ this[ !-85960[ -true[ gZ5t44n_.yds]]]][ new IKzsbt7s2D().yMf_q()]; while ( !!FMvWmpp15b().QBA()) return; return; while ( null.TRSIlcEYG6M39) while ( -!!this[ true.ZL9q0O]) if ( !!-Ol73QyWXF1AJ().fehKD4DrkF()) ; return; { while ( true[ --!-null[ !!--!false[ new gOIKUYm()[ this[ false[ null.W]]]]]]) if ( !-null[ -new void[ !true.BFHvGZhT()][ --g4fir2h5()[ -adUnSx[ null.FrY]]]]) if ( !!false[ eKK9().Olk4XPaEK6TL()]) ; } return; void[] uY_0Xt7rJ2Rxdl; dRrjXB A; ; void[] yBr0atp3nTN8; void O; boolean[] cyK6S; { { return; } } void D3U1YS; } { !new qnM[ 712908.NVxRZIAv4r4k()].NjKPfnQnsSd; int[] S1mcTSyvC; while ( --true.G5TeF) return; { !---new XixTdR()[ false.MbPkOS4wNgRAFi()]; } boolean LWvs64mQvYB; void[][][] CkajcRsO_ENX2b; this[ -null.Pzg]; return; } void uRO51 = new nHq8hOJnNR()[ true.Uu2R1DVrd]; return; AHa9jkm2fAHIh[] F5_4QMwkU; int FXg = true.tieN() = !new LHEzc().xrPVhnJKU; } public static void n (String[] CqxqX3GamY) throws DQ9NNhE { int[] MUZbMZhESQTZ; return; int[] kYBYEh9x = -true[ new boolean[ ( 6[ false.jCvbDv_MU()]).MY061].iNejdJzz()] = !!tx.Rh(); void[][][] cUMKTpStXTGt; this[ !!false.BVj]; void[][] ldMOwyfsEl32I; void[] JZXjx7IHvC = RO[ new gO9OiGRnV()[ -( U_wZl.bw6nlJVBin())[ -!--false.p559X()]]]; } public void[] h (void wZ262_a, boolean[][] L1SOfp, boolean[] k6cQ, _[] lWYcPu3ZbLlL8, boolean Aq2sn, dGH6No3bVtk[][] Xw7wd, boolean Al5w3) throws XkKp { void[] jOhpT8aIpmQUe = !this[ 7.ME5UCWjEV] = false[ new gIlQls2kQ[ -!new rG35bsSm().jASZ].h7R94d]; int V = -!s[ true.V1xdVDUIW()] = -139954[ -Op1BUqoNfyTyoQ.W7oHUhs]; int CVpMVA5 = true.iO2bvZb5QEDn5e; { void[] Amlzbj8i6; if ( Umr2q.pP3KsjEv) while ( !-new z()[ !-new FDmmxBRN1Jjo().mKInLYjhrVVZ]) while ( -!!-KRfKgUYOTMH.q4F09_Z()) null.CfCVvRx5P9yZUQ(); } if ( !pI().TnhZ4QRNH()) !!--null.D0lH8J73D7m75();else if ( new RbzetaknWG().qsNLt()) while ( vnCtVkDEg4W().zKrB) ; void[] YwJkQFHqmtUdS3; void js08Q = -!!PoPVb.q2wEq78p(); int ziZ6nMRw7WqoU = -!null.RIrQ51zPNJ_N9W(); void BRilQla = !true[ qlEZel[ !null[ this.Llc7]]]; int[] Du_jfFb7qw; int[][][] PgL8e = !new T().RqbDmAXjaq(); GdO AMCz8EyNBGz = -new boolean[ -4070[ G9.zCQ5o]].fb11gq(); if ( -new LgvUT().b2cCQW9N) if ( null.V()) return;else { while ( !--!new p4[ !new Ho9lL().nToP1iTHew1KzJ].MbVD6Z18UqQ()) if ( new E9TiO1kUGppQ().tg2xcj) return; } { SYKqKhBij Br1gWFgDiGDgr; boolean fAfod; int ep533hu8fWBN; void[] zDZgYub; boolean[] mLe; boolean kd; void CQWOgD3amTL; } } public int RfnPTp9G (boolean[] zEiyFWVsbdwk, int[][] Zf, boolean[][][] BocP8H77yWQi, void[][][][][] cR0, void[] jjZpl7RCoU4x8, void[][] ZGOzOJtr) throws GbbO1_ { if ( --true[ --null.gB3QCIeFn9]) return;else pIkmlPHOw().Q; _HhM[] iInKlAejC = 868240169.s0dXarY = !!145353505.CfuA0iJUqG; if ( !null.wmiTQVzbgkGug) -true.JXC0O();else if ( null.oi()) ; if ( !!-!!-V3NSpi7P().Z13TaS0r4MwlTF()) 2877.Aw2zMVppnowf7t; O8jDDW().RwDKLE(); } } class lO { } class N7KP40JaSoJIgQ { public y6sZFAXS7VifiY[][][] tJodjHIHSk () { boolean[] j; void FEcRyUyH; void[][] M9Uh8Zoym_ = ( !false[ !!--false.IgaRBVJpY()]).T_() = true.NnU(); BMir vDDWkH; if ( -true[ -( -!oE8Pt()[ !--new void[ 5652403[ this[ ( -false[ !new lrV().sxLZEXbJnyH]).DfV26dQwq6()]]].mqC1tD4TA]).JhuHZB]) return;else while ( 03977.zF_Kcx) ; while ( this.xdRrwTJOFP2mMa()) while ( -new GG30Vd().WmmWH) { void mJndOvNq1PXaV; } while ( H_puDVy7b().PrjgO53) ; boolean iyhN_Kc4jJ = --!!new Zl3WaikZ3().OW; int[][][][] ocNh = this[ ( ( 51553723.LT()).MdGqKeD())[ null[ new void[ !-!-( !null.z())[ -false.u3OM3]].eoLdfTiiYvGu54()]]]; int[][][] oFxi68QNWnFDv9 = true[ new boolean[ !pJVt90T1HYpJK().qCt6oCIf2()][ !---this[ new N8()[ hSKRrS[ !null.zduxo0R_YBes()]]]]] = 54239620.bIpijBFXxe; ADr7uf3a6Ykl[] W; boolean vvGWE1IXgkeGo0; } public static void vxk (String[] IdQf) throws b0 { int[][] nN7W; if ( 97232.qnqx0epiwnRE) ;else return; boolean[] gSKv = new void[ !-COaXbNlT8XUhVB[ !mu()[ -new void[ new void[ this.hFK0YVLL1tyRb()].g7UUoSH5()].GAhiVgvS]]][ ---!-this.ScFgjPTvIo1x()]; if ( HA().Gg8Rm) while ( 793[ null[ true.XpXXYH_UTFuU]]) OZNtj2UnRy_.MOq2AfsH; ; qteRqYHGdwrf Z0QWBrK8Y_ruVI; int[][][][][][][] KG; { void EhFDCKVDEmd; boolean K; return; -false[ -( this.kH0Sjjnc15M).AX147LRd]; -!null.cwsXN3I; boolean[] CZhYf; return; boolean[] kZDfXUdOpsmweT; ; zaKmmVrV Z; int[] AWf00T1aq6I9; } while ( -58.U8jV3N4g_LS) { while ( false[ !false[ -29.le_Vn]]) oGq().HBw; } --false.mqcg1Tjb(); } public void[] kRK; public static void BgZwk (String[] RXrONJ) throws k { new F6GTaFPVG().m1oUqoBJOcCytz; { if ( new a58[ true.kv9Nkuu9()].aF) { { void nBtvE0LdTUjEQ; } } if ( false.BmSv()) -( !false.jsEKibfripbw()).tXNyPH2g(); while ( null[ ( false.JKQzxZUizM4).ChMptnI6fjdVPO]) return; if ( !!z5lXIeC.BSmGLMzS) this[ !new isJudc()._]; int[] OdpLYy; void[][][] cawwJJlpB3SaE; void[] R; ; void yhj3; return; ; if ( new int[ true.IkIRMUlVYJ9()].VvmmFHRc()) while ( ( this[ -new int[ -( Y5tCIdLn_1.Tac()).ZCmcFVRS][ -Iy6VWnVCR_1R().rRO9]]).Tx9NU()) { { if ( new WlPsRL3mDm()[ null.yj0v90SlZTpOQY()]) if ( !new boolean[ -new void[ uDy0Mc1uI7b()[ !true.Pf7Kg1sCY_cwxV()]].bDOqVS1ON()].Nj) { R0dE30ll9X().iY9lcnDSM; } } } } true[ -!!W37oklaNB3qolp.PR7Y5]; while ( -!Ku()[ null[ -!--!810199.PrpRi()]]) return; } }
3e211552ea0afab24460f919c068caa5afeaef12
9b48da12e8d70fb3d633b988b9c7d63a954434bf
/ECC8.1/ECC/ecc_ZZB/ecc/src/com/siteview/ecc/treeview/DefaultViewTreeModel.java
a7035bca5352a4e9ed6e7949863da42f0501a2d8
[]
no_license
SiteView/ECC8.1.3
446e222e33f37f0bb6b67a9799e1353db6308095
7d7d8c7e7d7e7e03fa14f9f0e3ce5e04aacdb033
refs/heads/master
2021-01-01T18:07:05.104362
2012-08-30T08:58:28
2012-08-30T08:58:28
4,735,167
1
3
null
null
null
null
WINDOWS-1252
Java
false
false
2,017
java
package com.siteview.ecc.treeview; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.servlet.http.HttpSession; import org.zkoss.zk.ui.Desktop; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.Session; import org.zkoss.zul.AbstractTreeModel; import org.zkoss.zul.Treechildren; import org.zkoss.zul.Treeitem; import org.zkoss.zul.event.TreeDataEvent; import com.siteview.base.data.VirtualItem; import com.siteview.base.data.VirtualView; import com.siteview.base.manage.Manager; import com.siteview.base.manage.View; import com.siteview.base.queue.ChangeDetailEvent; import com.siteview.base.queue.IQueueEvent; import com.siteview.base.tree.IForkNode; import com.siteview.base.tree.INode; import com.siteview.ecc.timer.TimerListener; import com.siteview.ecc.util.Toolkit; import com.siteview.svecc.zk.test.SVDBViewFactory; public class DefaultViewTreeModel extends EccTreeModel { public DefaultViewTreeModel(EccTreeItem root) { super(root); } public static void removeInstance(Session session) { session.removeAttribute("DefaultViewTreeModelForVirtualViewEdditting_"+VirtualView.DefaultView); } public static void removeInstance(Session session,String rootid) { session.removeAttribute("DefaultViewTreeModelForVirtualViewEdditting_"+rootid); } public static DefaultViewTreeModel getInstance(Session session) { return getInstance(session,VirtualView.DefaultView); } public static DefaultViewTreeModel getInstance(Session session,String rootid) { DefaultViewTreeModel model=(DefaultViewTreeModel)session.getAttribute("DefaultViewTreeModelForVirtualViewEdditting_"+rootid); if(model==null) { model = new DefaultViewTreeModel(new EccTreeItem(null,rootid,"ÕûÌåÊ÷","")); // session.setAttribute("DefaultViewTreeModelForVirtualViewEdditting_"+rootid, model); } return model; } }
c8293dbc31fad3166944349a34e1771c9f76f316
9c67584c97552d0f9bd5256d0659ce0c4b593e2b
/Android Sample Code/SimpleMusicPlayer/app/src/main/java/com/mkdutton/labfour/fragments/MainFragment.java
5df3f3c3090399d71adab3c4739afc02bc8cfdae
[]
no_license
mduttondev/sourcecode
80536ce15e6347cecc07ab155c18f2e0ccc93f2a
b99f84ae253d63fa295adc6e33573be4279893fd
refs/heads/master
2021-01-10T21:46:58.803015
2015-11-17T14:59:49
2015-11-17T14:59:49
24,869,776
0
0
null
null
null
null
UTF-8
Java
false
false
9,810
java
package com.mkdutton.labfour.fragments; import android.app.Activity; import android.app.Fragment; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.TextView; import com.mkdutton.labfour.MusicService; import com.mkdutton.labfour.R; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Matt on 10/7/14. */ public class MainFragment extends Fragment implements ServiceConnection, View.OnClickListener, RadioGroup.OnCheckedChangeListener, SeekBar.OnSeekBarChangeListener { public static final String TAG = "MAIN_FRAG"; public static final String ACTION_UPDATE_DETAILS = "com.mkdutton.labfour.ACTION_UPDATE_DETAILS"; public static final String EXTRA_TITLE_UPDATE = "com.mkdutton.labfour.EXTRA_TITLE_UPDATE"; public static final String EXTRA_COVER_UPDATE = "com.mkdutton.labfour.EXTRA_COVER_UPDATE"; public static final String EXTRA_ARTIST_UPDATE = "com.mkdutton.labfour.EXTRA_ARTIST_UPDATE"; public static final String EXTRA_SONG_DURATION = "com.mkdutton.labfour.EXTRA_SONG_DURATION"; MusicService mMusicService; Handler mMusicHandler; Runnable mMusicRunnable; boolean mIsBound; IntentFilter mFilter; boolean mNewSong = false; Intent musicIntent; RadioGroup group; SeekBar seekbar; public static MainFragment newInstance() { return new MainFragment(); } public static MainFragment newInstance(Bundle _extras) { MainFragment frag = new MainFragment(); frag.setArguments( _extras ); return frag; } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mIsBound = false; Button button = (Button) getActivity().findViewById(R.id.rewindMedia); button.setOnClickListener(this); button = (Button) getActivity().findViewById(R.id.playMedia); button.setOnClickListener(this); button = (Button) getActivity().findViewById(R.id.pauseMedia); button.setOnClickListener(this); button = (Button) getActivity().findViewById(R.id.stopMedia); button.setOnClickListener(this); button = (Button) getActivity().findViewById(R.id.fastforwardMedia); button.setOnClickListener(this); group = (RadioGroup) getActivity().findViewById(R.id.radioGroup); group.setOnCheckedChangeListener(this); seekbar = (SeekBar) getActivity().findViewById(R.id.seekBar); seekbar.setOnSeekBarChangeListener(this); musicIntent = new Intent(getActivity(), MusicService.class); ((RadioButton)getActivity().findViewById(R.id.shuffleModifier)).setChecked(true); mFilter = new IntentFilter(); mFilter.addAction(ACTION_UPDATE_DETAILS); getActivity().registerReceiver(receiver, mFilter); if (savedInstanceState != null){ Bundle args = savedInstanceState.getBundle("key"); if (args != null) { Intent detailsIntent = new Intent(ACTION_UPDATE_DETAILS); detailsIntent.putExtras(args); getActivity().sendBroadcast(detailsIntent); } } else { Bundle args = getArguments(); if (args != null) { Intent detailsIntent = new Intent(ACTION_UPDATE_DETAILS); detailsIntent.putExtras(args); getActivity().sendBroadcast(detailsIntent); } } } @Override public void onResume() { super.onResume(); getActivity().registerReceiver(receiver, mFilter); if ( !mIsBound ) { getActivity().startService(musicIntent); getActivity().bindService(musicIntent, this, Context.BIND_AUTO_CREATE); setHandlerAndRunnable(); } } @Override public void onPause() { super.onPause(); mIsBound = false; getActivity().unbindService(this); mMusicHandler.removeCallbacks(mMusicRunnable); getActivity().unregisterReceiver(receiver); } @Override public void onDestroy() { super.onDestroy(); if ( !getActivity().isChangingConfigurations()){ getActivity().stopService(musicIntent); } } private void setHandlerAndRunnable() { mMusicHandler = new Handler(); mMusicRunnable = new Runnable() { int totalTime; int currentPos; @Override public void run() { if(mIsBound){ if (mMusicService.mPlayer.isPlaying()){ if (mNewSong) { totalTime = mMusicService.mPlayer.getDuration(); seekbar.setMax( totalTime ); ((TextView)getActivity().findViewById(R.id.totalTime)).setText( (new SimpleDateFormat("mm:ss")).format(new Date(totalTime)) ); } currentPos = mMusicService.mPlayer.getCurrentPosition(); seekbar.setProgress(currentPos); ((TextView)getActivity().findViewById(R.id.currentTime)).setText((new SimpleDateFormat("mm:ss")).format(new Date(currentPos))) ; } } else { Log.i(TAG, "Not Bound yet"); } mMusicHandler.postDelayed(this, 250); } }; mMusicHandler.postDelayed(mMusicRunnable, 250); } public void onServiceConnected(ComponentName name, IBinder service) { mIsBound = true; MusicService.MusicBinder binder = (MusicService.MusicBinder) service; mMusicService = binder.getService(); } @Override public void onServiceDisconnected(ComponentName componentName) { mIsBound = false; } @Override public void onClick(View view) { int id = view.getId(); switch (id) { case R.id.rewindMedia: mMusicService.musicControl(MusicService.REW); break; case R.id.playMedia: mMusicService.musicControl(MusicService.PLAY); break; case R.id.pauseMedia: mMusicService.musicControl(MusicService.PAUSE); break; case R.id.stopMedia: mMusicService.musicControl(MusicService.STOP); break; case R.id.fastforwardMedia: mMusicService.musicControl(MusicService.FF); break; } } @Override public void onCheckedChanged(RadioGroup radioGroup, int id) { if (mMusicService != null) { switch (id) { case R.id.repeatModifier: mMusicService.selectedModifier(MusicService.REPEAT_MOD); break; case R.id.shuffleModifier: mMusicService.selectedModifier(MusicService.SHUFFLE_MOD); break; } } } BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ACTION_UPDATE_DETAILS)) { mNewSong = true; String title = intent.getStringExtra(EXTRA_TITLE_UPDATE); String artist = intent.getStringExtra(EXTRA_ARTIST_UPDATE); int cover = intent.getIntExtra(EXTRA_COVER_UPDATE, 7); ((TextView)getActivity().findViewById(R.id.songTitle)).setText(title); ((TextView)getActivity().findViewById(R.id.songArtist)).setText(artist); ((ImageView)getActivity().findViewById(R.id.coverArt)).setImageResource( cover ); (getActivity().findViewById(R.id.coverArt)).setTag( cover ); } } }; @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Bundle extras = new Bundle(); String title = ((TextView)getActivity().findViewById(R.id.songTitle)).getText().toString(); String artist = ((TextView) getActivity().findViewById(R.id.songArtist)).getText().toString(); int cover = ((Integer) (getActivity().findViewById(R.id.coverArt)).getTag()); extras.putString( EXTRA_TITLE_UPDATE, title ) ; extras.putString(EXTRA_ARTIST_UPDATE, artist ); extras.putInt(EXTRA_COVER_UPDATE, cover ); outState.putBundle("key", extras); } @Override public void onProgressChanged(SeekBar seekBar, int i, boolean fromUser) { if (fromUser){ mMusicService.userSeekTo( i ); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }
678a24c59dfb40d82437e4ba3a33c6c554259355
ece47b1632210f66a28ea83b5f9c9e7ecc782806
/core/src/main/java/com/adobe/media/publication/core/servlets/SimpleServlet.java
7ea5c86349e5ad3b68ca7a54e890bc154a5d73dc
[]
no_license
prasanna-shah/aem-media-publication
318b1522c712b9093171f563495d4baa941162a1
eea67e87a65f007a36a323539d22ae43b9eb273e
refs/heads/master
2022-07-25T16:33:26.068224
2019-11-29T09:09:11
2019-11-29T09:09:11
220,802,601
0
0
null
2022-07-06T20:18:48
2019-11-10T14:36:20
Java
UTF-8
Java
false
false
1,919
java
/* * Copyright 2015 Adobe Systems Incorporated * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.adobe.media.publication.core.servlets; import org.apache.felix.scr.annotations.sling.SlingServlet; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import javax.servlet.ServletException; import java.io.IOException; /** * Servlet that writes some sample content into the response. It is mounted for * all resources of a specific Sling resource type. The * {@link SlingSafeMethodsServlet} shall be used for HTTP methods that are * idempotent. For write operations use the {@link SlingAllMethodsServlet}. */ @SuppressWarnings("serial") @SlingServlet(resourceTypes = "mediaPublication/structure/page") public class SimpleServlet extends SlingSafeMethodsServlet { @Override protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws ServletException, IOException { final Resource resource = req.getResource(); resp.getOutputStream().println(resource.toString()); resp.getOutputStream().println( "This content is generated by the SimpleServlet"); } }
be1cf62fbdd26ef9a8914b22f2c941d5accf46e5
11546ca48d8d0836771861fdafaf216ab80c7941
/src/test/java/com/vinsguru/webfluxdemo/Lec04HeadersTest.java
eaf5ab2926e830c2a2de66be1931faeaf78ac1ad
[]
no_license
learnwiththamhv/webflux-demo
afe8e940d2d6469f34d1188bff4974fb3cace1f0
8e930a0ff18d1292964ef45c16646a2cdde8cb01
refs/heads/master
2023-07-30T00:08:46.803902
2021-09-10T23:38:42
2021-09-10T23:38:42
405,237,913
0
0
null
null
null
null
UTF-8
Java
false
false
1,304
java
package com.vinsguru.webfluxdemo; import com.vinsguru.webfluxdemo.dto.MultiplyRequestDto; import com.vinsguru.webfluxdemo.dto.Response; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; public class Lec04HeadersTest extends BaseTest { @Autowired private WebClient webClient; @Test public void headersTest(){ Mono<Response> responseMono = this.webClient .post() .uri("reactive-math/multiply") .bodyValue(buildRequestDto(5, 2)) .headers(h -> h.set("someKey", "someVal")) .retrieve() .bodyToMono(Response.class) .doOnNext(System.out::println); StepVerifier.create(responseMono) .expectNextCount(1) .verifyComplete(); StepVerifier.create(responseMono) .expectNextCount(1) .verifyComplete(); } private MultiplyRequestDto buildRequestDto(int a, int b){ MultiplyRequestDto dto = new MultiplyRequestDto(); dto.setFirst(a); dto.setSecond(b); return dto; } }
c3a3e745092abb9738a22c70d426225f7de603ee
07ce7fb956e05a1596c1b51fee9604fcc7df4e5c
/StarArrangements.java
42f50dd66f8dc13baf36b46f1426d000b3d12403
[]
no_license
ECannon/Kattis
9fccd750e16e3751b3a4959695f62b5151c842fe
79d1f9ba25dab5018f7a24028180eec9cad74844
refs/heads/master
2021-06-16T23:57:44.109171
2019-10-28T19:08:00
2019-10-28T19:08:00
148,221,318
4
0
null
null
null
null
UTF-8
Java
false
false
636
java
import java.util.*; public class StarArrangements { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println(n+":"); for(int i = 2; i < n; i++) { boolean flag = false; for(int j = i-1; j <= i; j++) { int total = 0; while(total <= n) { total +=i; if(total == n) { System.out.println(i+","+j); break; } else { total+=j; if(total == n) { System.out.println(i+","+j); break; } } } } } } }
29d6b65316d53c94d758e7e2306e999f302ef7e1
98368deb114a0ade0f2314271846efb58810e317
/trust_rnt/src/main/java/com/trust/entity/ArticleDetail.java
af5f4e6bf78ad20851b484cdd60a90b1e42a4c7f
[]
no_license
bestchendong/psychic-winner
9ef35089c718e81a8cd4735662f0169bed25e3ff
a089b454697075072c2ac2edbf14455e32d65e69
refs/heads/master
2020-03-14T01:37:13.590340
2018-04-28T08:12:40
2018-04-28T08:12:40
131,381,425
0
1
null
null
null
null
UTF-8
Java
false
false
12,931
java
package com.trust.entity; import com.fasterxml.jackson.annotation.JsonProperty; import com.trust.utils.DateUtil; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * ArticleDetail */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-12-15T03:06:26.991Z") public class ArticleDetail implements Serializable { @JsonProperty("carticleId") private Long carticleId = null; @JsonProperty("carticleCategoryId") private Long carticleCategoryId = null; @JsonProperty("carticleCreator") private Long carticleCreator = null; @JsonProperty("carticleCreatorName") private String carticleCreatorName = null; @JsonProperty("siteCode") private String siteCode = null; @JsonProperty("carticleTitle") private String carticleTitle = null; @JsonProperty("carticlePoster") private String carticlePoster = null; @JsonProperty("carticleAuthor") private String carticleAuthor = null; @JsonProperty("carticleCreatetime") private String carticleCreatetime = null; @JsonProperty("carticleUpdatetime") private String carticleUpdatetime = null; @JsonProperty("carticleReleaseid") private Long carticleReleaseid = null; @JsonProperty("carticleReleaseTime") private String carticleReleaseTime = null; @JsonProperty("carticleStatus") private Integer carticleStatus = null; @JsonProperty("carticleAmount") private Integer carticleAmount = null; @JsonProperty("carticleResource") private String carticleResource = null; @JsonProperty("carticleResourceUrl") private String carticleResourceUrl = null; @JsonProperty("carticleSubtitle") private String carticleSubtitle = null; @JsonProperty("carticleDes") private String carticleDes = null; @JsonProperty("carticleCategoryCode") private String carticleCategoryCode = null; @JsonProperty("articleContents") private List<ArticleDetailArticleContents> articleContents = null; public ArticleDetail carticleId(Long cArticleId) { this.carticleId = carticleId; return this; } /** * 文章ID * @return cArticleId **/ @ApiModelProperty(value = "文章ID") public Long getCarticleId() { return carticleId; } public void setCArticleId(Long carticleId) { this.carticleId = carticleId; } public ArticleDetail carticleCategoryId(Long carticleCategoryId) { this.carticleCategoryId = carticleCategoryId; return this; } /** * 分类ID * @return cArticleCategoryId **/ @ApiModelProperty(value = "分类ID") public Long getCarticleCategoryId() { return carticleCategoryId; } public void setCarticleCategoryId(Long carticleCategoryId) { this.carticleCategoryId = carticleCategoryId; } public ArticleDetail carticleCreator(Long carticleCreator) { this.carticleCreator = carticleCreator; return this; } /** * 创建人ID * @return cArticleCreator **/ @ApiModelProperty(value = "创建人ID") public Long getCarticleCreator() { return carticleCreator; } public void setCarticleCreator(Long carticleCreator) { this.carticleCreator = carticleCreator; } public ArticleDetail siteCode(String siteCode) { this.siteCode = siteCode; return this; } /** * 创建人名字 * @return */ public String getcarticleCreatorName() { return carticleCreatorName; } public void setcarticleCreatorName(String carticleCreatorName) { this.carticleCreatorName = carticleCreatorName; } /** * 站点编码 * @return siteCode **/ @ApiModelProperty(value = "站点编码") public String getSiteCode() { return siteCode; } public void setSiteCode(String siteCode) { this.siteCode = siteCode; } public ArticleDetail carticleTitle(String carticleTitle) { this.carticleTitle = carticleTitle; return this; } /** * 标题 * @return cArticleTitle **/ @ApiModelProperty(value = "标题") public String getCarticleTitle() { return carticleTitle; } public void setCarticleTitle(String carticleTitle) { this.carticleTitle = carticleTitle; } public ArticleDetail carticlePoster(String carticlePoster) { this.carticlePoster = carticlePoster; return this; } /** * 海报 * @return cArticlePoster **/ @ApiModelProperty(value = "海报") public String getCarticlePoster() { return carticlePoster; } public void setCarticlePoster(String carticlePoster) { this.carticlePoster = carticlePoster; } public ArticleDetail carticleAuthor(String carticleAuthor) { this.carticleAuthor = carticleAuthor; return this; } /** * 作者 * @return cArticleAuthor **/ @ApiModelProperty(value = "作者") public String getCarticleAuthor() { return carticleAuthor; } public void setCarticleAuthor(String cArticleAuthor) { this.carticleAuthor = carticleAuthor; } public ArticleDetail carticleCreatetime(Date carticleCreatetime) { this.carticleCreatetime = DateUtil.formatDateTime(carticleCreatetime); return this; } /** * 创建时间 * @return cArticleCreatetime **/ @ApiModelProperty(value = "创建时间") @Valid public String getCarticleCreatetime() { return carticleCreatetime; } public void setCarticleCreatetime(Date carticleCreatetime) { this.carticleCreatetime = DateUtil.formatDateTime(carticleCreatetime); } public ArticleDetail carticleUpdatetime(Date carticleUpdatetime) { this.carticleUpdatetime = DateUtil.formatDateTime(carticleUpdatetime); return this; } /** * 修改时间 * @return cArticleUpdatetime **/ @ApiModelProperty(value = "修改时间") @Valid public String getCarticleUpdatetime() { return carticleUpdatetime; } public void setCarticleUpdatetime(Date carticleUpdatetime) { this.carticleUpdatetime = DateUtil.formatDateTime(carticleUpdatetime); } public ArticleDetail carticleReleaseid(Long carticleReleaseid) { this.carticleReleaseid = carticleReleaseid; return this; } /** * 发布人ID * @return cArticleReleaseid **/ @ApiModelProperty(value = "发布人ID") public Long getCarticleReleaseid() { return carticleReleaseid; } public void setCaArticleReleaseid(Long carticleReleaseid) { this.carticleReleaseid = carticleReleaseid; } public ArticleDetail carticleReleaseTime(Date carticleReleaseTime) { this.carticleReleaseTime = DateUtil.formatDateTime(carticleReleaseTime); return this; } /** * 发布时间 * @return cArticleReleaseTime **/ @ApiModelProperty(value = "发布时间") @Valid public String getCarticleReleaseTime() { return carticleReleaseTime; } public void setCarticleReleaseTime(Date carticleReleaseTime) { this.carticleReleaseTime = DateUtil.formatDateTime(carticleReleaseTime); } public ArticleDetail carticleStatus(Integer carticleStatus) { this.carticleStatus = carticleStatus; return this; } /** * 状态 * @return cArticleStatus **/ @ApiModelProperty(value = "状态") public Integer getCarticleStatus() { return carticleStatus; } public void setCarticleStatus(Integer carticleStatus) { this.carticleStatus = carticleStatus; } public ArticleDetail carticleAmount(Integer carticleAmount) { this.carticleAmount = carticleAmount; return this; } /** * 浏览量 * @return cArticleAmount **/ @ApiModelProperty(value = "浏览量") public Integer getCarticleAmount() { return carticleAmount; } public void setCarticleAmount(Integer carticleAmount) { this.carticleAmount = carticleAmount; } public ArticleDetail cArticleResource(String carticleResource) { this.carticleResource = carticleResource; return this; } /** * 来源 * @return cArticleResource **/ @ApiModelProperty(value = "来源") public String getCarticleResource() { return carticleResource; } public void setCarticleResource(String carticleResource) { this.carticleResource = carticleResource; } public ArticleDetail carticleResourceUrl(String carticleResourceUrl) { this.carticleResourceUrl = carticleResourceUrl; return this; } /** * 来源链接 * @return cArticleResourceUrl **/ @ApiModelProperty(value = "来源链接") public String getCarticleResourceUrl() { return carticleResourceUrl; } public void setCarticleResourceUrl(String carticleResourceUrl) { this.carticleResourceUrl = carticleResourceUrl; } public ArticleDetail carticleSubtitle(String carticleSubtitle) { this.carticleSubtitle = carticleSubtitle; return this; } /** * 副标题 * @return cArticleSubtitle **/ @ApiModelProperty(value = "副标题") public String getCarticleSubtitle() { return carticleSubtitle; } public void setCarticleSubtitle(String carticleSubtitle) { this.carticleSubtitle = carticleSubtitle; } public ArticleDetail carticleDes(String carticleDes) { this.carticleDes = carticleDes; return this; } /** * 描述 * @return cArticleDes **/ @ApiModelProperty(value = "描述") public String getCarticleDes() { return carticleDes; } public void setCarticleDes(String cArticleDes) { this.carticleDes = carticleDes; } public ArticleDetail carticleCategoryCode(String carticleCategoryCode) { this.carticleCategoryCode = carticleCategoryCode; return this; } /** * 分类code * @return cArticleCategoryCode **/ @ApiModelProperty(value = "分类code") public String getCarticleCategoryCode() { return carticleCategoryCode; } public ArticleDetail(Long cArticleId, Long cArticleCategoryId, Long cArticleCreator, String cArticleCreatorName, String siteCode, String cArticleTitle, String cArticlePoster, String cArticleAuthor, Date cArticleCreatetime, Date cArticleUpdatetime, Long cArticleReleaseid, Date cArticleReleaseTime, Integer cArticleStatus, Integer cArticleAmount, String cArticleResource, String cArticleResourceUrl, String cArticleSubtitle, String cArticleDes, String cArticleCategoryCode) { this.carticleId = cArticleId; this.carticleCategoryId = cArticleCategoryId; this.carticleCreator = cArticleCreator; this.carticleCreatorName = cArticleCreatorName; this.siteCode = siteCode; this.carticleTitle = cArticleTitle; this.carticlePoster = cArticlePoster; this.carticleAuthor = cArticleAuthor; if(cArticleCreatetime!=null){ this.carticleCreatetime = DateUtil.formatDateTime(cArticleCreatetime); } if(cArticleUpdatetime!=null){ this.carticleUpdatetime = DateUtil.formatDateTime(cArticleUpdatetime); } this.carticleReleaseid = cArticleReleaseid; if(cArticleReleaseTime!=null) { this.carticleReleaseTime = DateUtil.formatDateTime(cArticleReleaseTime); } this.carticleStatus = cArticleStatus; this.carticleAmount = cArticleAmount; this.carticleResource = cArticleResource; this.carticleResourceUrl = cArticleResourceUrl; this.carticleSubtitle = cArticleSubtitle; this.carticleDes = cArticleDes; this.carticleCategoryCode = cArticleCategoryCode; } public void setCArticleCategoryCode(String cArticleCategoryCode) { this.carticleCategoryCode = carticleCategoryCode; } public ArticleDetail articleContents(List<ArticleDetailArticleContents> articleContents) { this.articleContents = articleContents; return this; } public ArticleDetail addArticleContentsItem(ArticleDetailArticleContents articleContentsItem) { if (this.articleContents == null) { this.articleContents = new ArrayList<ArticleDetailArticleContents>(); } this.articleContents.add(articleContentsItem); return this; } /** * Get articleContents * @return articleContents **/ @ApiModelProperty(value = "") @Valid public List<ArticleDetailArticleContents> getArticleContents() { return articleContents; } public void setArticleContents(List<ArticleDetailArticleContents> articleContents) { this.articleContents = articleContents; } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
81d489544f0bf806e4486acf517d75c20a98903f
4f8819e8ab71109df48e7601d0d52ee6d968b42e
/src/com/erdk/ABotanJNI1/JavaCrypto.java
7a9456821f0ded5cc41bfba5a916d7bee2486395
[]
no_license
ShivaniGandhi/ABotanJNI1
ceb19ffa599a24f07fc94bff7a4bc89bb9adaa64
9e95b89bc549b74fe4442ba3a44116d47e242d3e
refs/heads/master
2021-01-21T03:14:23.876691
2013-03-26T08:21:39
2013-03-26T08:21:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,679
java
package com.erdk.ABotanJNI1; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; public class JavaCrypto { public static void main(String[] argv) { byte[] salt = new byte[8]; String key; for (int i = 0; i < 5; i++) { key = JavaCrypto.pbkdf2Demo(Constants.password, salt, 4096, 32); System.out.print("RSA priv key ->" + key + "\n"); } } public static String pbkdf2Demo(char[] password, byte[] salt, int iterations, int keyLength) { Key key = null; SecretKeyFactory secretKeyFactory; try { secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec keySpec = new PBEKeySpec(password, salt, iterations, keyLength); key = secretKeyFactory.generateSecret(keySpec); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return bytesToHex(key.getEncoded()); } public static String bytesToHex(byte[] bytes) { final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; char[] hexChars = new char[bytes.length * 2]; int v; for ( int j = 0; j < bytes.length; j++ ) { v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } }
d2d7c7a69cb20ebc902d0e5f94bda8e48c36ddd7
7d75b42bd7176ceac8926c956de8dc485bdd58e3
/projeto-imc/src/model/Paciente.java
18502d47dfdc588ac229d72c04afa8a3509c0614
[]
no_license
ubiratantavares/orientacao_a_objetos_com_java
f6ce2c8ec1c94ec0c4dad8439d7a80fc2574e9d9
13526b64318d4b45adfb15e9e27f273aa81521f3
refs/heads/main
2023-07-07T16:46:58.874535
2021-08-12T20:40:58
2021-08-12T20:40:58
391,995,857
0
0
null
null
null
null
ISO-8859-2
Java
false
false
900
java
package model; import static java.lang.Math.pow; public class Paciente { private double peso; private double altura; public Paciente(double peso, double altura) { this.peso = peso; this.altura = altura; } public double getPeso() { return peso; } public double getAltura() { return altura; } public double calcularIMC() { return (peso / pow(altura, 2.0)); } public String diagnostico() { double imc = this.calcularIMC(); if (imc < 16) { return "Baixo peso muito grave"; } else if (imc < 17) { return "Baixo peso grave"; } else if (imc < 18.50) { return "Baixo peso"; } else if (imc < 25) { return "Peso normal"; } else if (imc < 30) { return "Sobrepeso"; } else if (imc < 35) { return "Obesidade grau I"; } else if (imc < 40) { return "Obesidade grau II"; } else { return "Obesidade grau III (obesidade mórbida)"; } } }
20c757fa5aabf5594b1c821c92546f94831932cb
c034379ec680e2d661d0afe20cbded70bf97d379
/sira/src/main/java/mx/com/sira/front/ServletInitializer.java
e6d1b2a217a080fbb478f51a4de0c88989aec9c8
[]
no_license
olal8/sira
3a1e6ca51e1e3eb22fb00d04c12189ac0fc55fa5
746fc501fa85cf71af3ffd9fd4cdfdad707e2b33
refs/heads/master
2020-03-29T14:57:54.744321
2018-11-21T08:11:16
2018-11-21T08:11:16
150,038,871
0
0
null
null
null
null
UTF-8
Java
false
false
405
java
package mx.com.sira.front; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SiraApplication.class); } }
ac5a143ed4349f57f81b83facc321383e64af59e
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/JetBrains--intellij-community/bc594a1133c71105025d9e312dfafeaf6bf80dc0/before/MavenProjectsTreeTestCase.java
739e97bc7c0cc4c32c632ece492cdf45f2ec1b86
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
55,672
java
package org.jetbrains.idea.maven.project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.idea.maven.MavenImportingTestCase; import org.jetbrains.idea.maven.embedder.MavenConsole; import java.io.IOException; import java.util.Arrays; import static java.util.Arrays.asList; import java.util.Collections; import java.util.List; public abstract class MavenProjectsTreeTestCase extends MavenImportingTestCase { private static final MavenConsole NULL_CONSOLE = NULL_MAVEN_CONSOLE; private boolean isQuick; protected MavenEmbeddersManager myEmbeddersManager; protected MavenProjectsTree myTree = new MavenProjectsTree(); protected MavenProjectsTreeTestCase(boolean quick) { isQuick = quick; } @Override protected void setUp() throws Exception { super.setUp(); myEmbeddersManager = new MavenEmbeddersManager(getMavenGeneralSettings()); } @Override protected void tearDown() throws Exception { myEmbeddersManager.release(); super.tearDown(); } public void testTwoRootProjects() throws Exception { VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); readModel(m1, m2); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(2, roots.size()); assertEquals(m1, roots.get(0).getFile()); assertEquals(m2, roots.get(1).getFile()); } public void testDoNotImportChildAsRootProject() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>"); readModel(myProjectPom, m); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(m, myTree.getModules(roots.get(0)).get(0).getFile()); } public void testSameProjectAsModuleOfSeveralProjects() throws Exception { VirtualFile p1 = createModulePom("project1", "<groupId>test</groupId>" + "<artifactId>project1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>../module</module>" + "</modules>"); VirtualFile p2 = createModulePom("project2", "<groupId>test</groupId>" + "<artifactId>project2</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>../module</module>" + "</modules>"); VirtualFile m = createModulePom("module", "<groupId>test</groupId>" + "<artifactId>module</artifactId>" + "<version>1</version>"); readModel(p1, p2); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(2, roots.size()); assertEquals(p1, roots.get(0).getFile()); assertEquals(p2, roots.get(1).getFile()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(m, myTree.getModules(roots.get(0)).get(0).getFile()); assertEquals(0, myTree.getModules(roots.get(1)).size()); } public void testSameProjectAsModuleOfSeveralProjectsInHierarchy() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>module1</module>" + " <module>module1/module2</module>" + "</modules>"); VirtualFile m1 = createModulePom("module1", "<groupId>test</groupId>" + "<artifactId>module1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>module2</module>" + "</modules>"); VirtualFile m2 = createModulePom("module1/module2", "<groupId>test</groupId>" + "<artifactId>module2</artifactId>" + "<version>1</version>"); readModel(myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(m1, myTree.getModules(roots.get(0)).get(0).getFile()); assertEquals(1, myTree.getModules(myTree.getModules(roots.get(0)).get(0)).size()); assertEquals(m2, myTree.getModules(myTree.getModules(roots.get(0)).get(0)).get(0).getFile()); } public void testRemovingChildProjectFromRootProjects() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>"); // all projects are processed in the specified order // if we have imported a child project as a root one, // we have to correct ourselves and to remove it from roots. readModel(m, myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(m, myTree.getModules(roots.get(0)).get(0).getFile()); } public void testUpdatingWholeModel() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>"); readModel(myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); MavenProject parentNode = roots.get(0); MavenProject childNode = myTree.getModules(roots.get(0)).get(0); createProjectPom("<groupId>test</groupId>" + "<artifactId>project1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>"); readModel(myProjectPom); roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(1, myTree.getModules(roots.get(0)).size()); MavenProject parentNode1 = roots.get(0); MavenProject childNode1 = myTree.getModules(roots.get(0)).get(0); assertSame(parentNode, parentNode1); assertSame(childNode, childNode1); assertEquals("project1", parentNode1.getMavenId().artifactId); assertEquals("m1", childNode1.getMavenId().artifactId); } public void testUpdatingModelWithNewProfiles() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<profiles>" + " <profile>" + " <id>one</id>" + " <modules>" + " <module>m1</module>" + " </modules>" + " </profile>" + " <profile>" + " <id>two</id>" + " <modules>" + " <module>m2</module>" + " </modules>" + " </profile>" + "</profiles>"); VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); readModel(Collections.singletonList("one"), myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(m1, myTree.getModules(roots.get(0)).get(0).getFile()); readModel(Collections.singletonList("two"), myProjectPom); roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(m2, myTree.getModules(roots.get(0)).get(0).getFile()); } public void testUpdatingParticularProject() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>"); readModel(myProjectPom); createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>"); update(m); MavenProject n = myTree.findProject(m); assertEquals("m1", n.getMavenId().artifactId); } public void testUpdatingInheritance() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<properties>" + " <childName>child</childName>" + "</properties>"); VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>${childName}</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>"); readModel(myProjectPom, child); assertEquals("child", myTree.findProject(child).getMavenId().artifactId); createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<properties>" + " <childName>child2</childName>" + "</properties>"); update(myProjectPom); assertEquals("child2", myTree.findProject(child).getMavenId().artifactId); } public void testUpdatingInheritanceHierarhically() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<properties>" + " <subChildName>subChild</subChildName>" + "</properties>"); VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>child</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>"); VirtualFile subChild = createModulePom("subChild", "<groupId>test</groupId>" + "<artifactId>${subChildName}</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>child</artifactId>" + " <version>1</version>" + "</parent>"); readModel(myProjectPom, child, subChild); assertEquals("subChild", myTree.findProject(subChild).getMavenId().artifactId); createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<properties>" + " <subChildName>subChild2</subChildName>" + "</properties>"); update(myProjectPom); assertEquals("subChild2", myTree.findProject(subChild).getMavenId().artifactId); } public void testAddingInheritanceParent() throws Exception { VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>${childName}</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>"); readModel(child); assertEquals("${childName}", myTree.findProject(child).getMavenId().artifactId); VirtualFile parent = createModulePom("parent", "<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<properties>" + " <childName>child</childName>" + "</properties>"); update(parent); assertEquals("child", myTree.findProject(child).getMavenId().artifactId); } public void testAddingInheritanceChild() throws Exception { VirtualFile parent = createModulePom("parent", "<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<properties>" + " <childName>child</childName>" + "</properties>"); readModel(parent); VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>${childName}</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>"); update(child); assertEquals("child", myTree.findProject(child).getMavenId().artifactId); } public void testAddingInheritanceChildOnParentUpdate() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<properties>" + " <childName>child</childName>" + "</properties>" + "<modules>" + " <module>child</module>" + "</modules>"); readModel(myProjectPom); VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>${childName}</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>"); update(myProjectPom); assertEquals("child", myTree.findProject(child).getMavenId().artifactId); } public void testDoNotReAddInheritanceChildOnParentModulesRemoval() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<modules>" + " <module>child</module>" + "</modules>"); VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>child</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>"); readModel(myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(child, myTree.getModules(roots.get(0)).get(0).getFile()); createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>"); update(myProjectPom); roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(0, myTree.getModules(roots.get(0)).size()); } public void testChangingInheritance() throws Exception { VirtualFile parent1 = createModulePom("parent1", "<groupId>test</groupId>" + "<artifactId>parent1</artifactId>" + "<version>1</version>" + "<properties>" + " <childName>child1</childName>" + "</properties>"); VirtualFile parent2 = createModulePom("parent2", "<groupId>test</groupId>" + "<artifactId>parent2</artifactId>" + "<version>1</version>" + "<properties>" + " <childName>child2</childName>" + "</properties>"); VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>${childName}</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent1</artifactId>" + " <version>1</version>" + "</parent>"); readModel(parent1, parent2, child); assertEquals("child1", myTree.findProject(child).getMavenId().artifactId); createModulePom("child", "<groupId>test</groupId>" + "<artifactId>${childName}</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent2</artifactId>" + " <version>1</version>" + "</parent>"); update(child); assertEquals("child2", myTree.findProject(child).getMavenId().artifactId); } public void testChangingInheritanceParentId() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<properties>" + " <childName>child</childName>" + "</properties>"); VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>${childName}</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>"); readModel(myProjectPom, child); assertEquals("child", myTree.findProject(child).getMavenId().artifactId); createProjectPom("<groupId>test</groupId>" + "<artifactId>parent2</artifactId>" + "<version>1</version>" + "<properties>" + " <childName>child</childName>" + "</properties>"); update(myProjectPom); assertEquals("${childName}", myTree.findProject(child).getMavenId().artifactId); } public void testHandlingSelfInheritance() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>"); readModel(myProjectPom); // shouldn't hang updateTimestamps(myProjectPom); update(myProjectPom); // shouldn't hang updateTimestamps(myProjectPom); readModel(myProjectPom); // shouldn't hang } public void testHandlingRecursiveInheritance() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>child</artifactId>" + " <version>1</version>" + "</parent>" + "<modules>" + " <module>child</module>" + "</properties>"); VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>child</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>"); readModel(myProjectPom, child); // shouldn't hang updateTimestamps(myProjectPom, child); update(myProjectPom); // shouldn't hang updateTimestamps(myProjectPom, child); update(child); // shouldn't hang updateTimestamps(myProjectPom, child); readModel(myProjectPom, child); // shouldn't hang } public void testDeletingInheritanceParent() throws Exception { VirtualFile parent = createModulePom("parent", "<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<properties>" + " <childName>child</childName>" + "</properties>"); VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>${childName}</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>"); readModel(parent, child); assertEquals("child", myTree.findProject(child).getMavenId().artifactId); deleteProject(parent); assertEquals("${childName}", myTree.findProject(child).getMavenId().artifactId); } public void testDeletingInheritanceChild() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<properties>" + " <subChildName>subChild</subChildName>" + "</properties>"); VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>child</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>"); VirtualFile subChild = createModulePom("subChild", "<groupId>test</groupId>" + "<artifactId>${subChildName}</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>child</artifactId>" + " <version>1</version>" + "</parent>"); readModel(myProjectPom, child, subChild); assertEquals("subChild", myTree.findProject(subChild).getMavenId().artifactId); deleteProject(child); assertEquals("${subChildName}", myTree.findProject(subChild).getMavenId().artifactId); } public void testRecursiveInheritanceAndAggregation() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>child</artifactId>" + " <version>1</version>" + "</parent>" + "<modules>" + " <module>child</module>" + "</modules>"); VirtualFile child = createModulePom("child", "<groupId>test</groupId>" + "<artifactId>child</artifactId>" + "<version>1</version>"); readModel(myProjectPom); // should not recurse updateTimestamps(myProjectPom, child); readModel(child); // should not recurse } public void testUpdatingAddsModules() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>"); VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>"); readModel(myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(0, myTree.getModules(roots.get(0)).size()); createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); update(myProjectPom); roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(m, myTree.getModules(roots.get(0)).get(0).getFile()); } public void testUpdatingDoesNotUpdateModules() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>"); readModel(myProjectPom); assertEquals("m", myTree.findProject(m).getMavenId().artifactId); createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); update(myProjectPom); // did not change assertEquals("m", myTree.findProject(m).getMavenId().artifactId); } public void testAddingProjectAsModuleToExistingOne() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); readModel(myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(0, myTree.getModules(roots.get(0)).size()); VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>"); update(m); roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(m, myTree.getModules(roots.get(0)).get(0).getFile()); } public void testAddingProjectAsAggregatorForExistingOne() throws Exception { VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>"); readModel(m); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(m, roots.get(0).getFile()); assertEquals(0, myTree.getModules(roots.get(0)).size()); createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); update(myProjectPom); roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(m, myTree.getModules(roots.get(0)).get(0).getFile()); } public void testAddingProjectWithModules() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>"); readModel(myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(0, myTree.getModules(roots.get(0)).size()); VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m2</module>" + "</modules>"); VirtualFile m2 = createModulePom("m1/m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); update(m1); roots = myTree.getRootProjects(); assertEquals(2, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(m1, roots.get(1).getFile()); assertEquals(1, myTree.getModules(roots.get(1)).size()); assertEquals(m2, myTree.getModules(roots.get(1)).get(0).getFile()); } public void testUpdatingAddsModulesFromRootProjects() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>"); VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>"); readModel(myProjectPom, m); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(2, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(m, roots.get(1).getFile()); assertEquals("m", roots.get(1).getMavenId().artifactId); assertEquals(0, myTree.getModules(roots.get(0)).size()); createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); update(myProjectPom); roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(m, myTree.getModules(roots.get(0)).get(0).getFile()); } public void testMovingModuleToRootsWhenAggregationChanged() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>"); readModel(myProjectPom, m); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(1, myTree.getModules(roots.get(0)).size()); createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>"); update(myProjectPom); roots = myTree.getRootProjects(); assertEquals(2, roots.size()); assertTrue(myTree.getModules(roots.get(0)).isEmpty()); assertTrue(myTree.getModules(roots.get(1)).isEmpty()); } public void testDeletingProject() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>"); readModel(myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(1, myTree.getModules(roots.get(0)).size()); deleteProject(m); roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(0, myTree.getModules(roots.get(0)).size()); } public void testDeletingProjectWithModules() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m1</module>" + "</modules>"); VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m2</module>" + "</modules>"); createModulePom("m1/m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); readModel(myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(1, myTree.getModules(roots.get(0)).size()); assertEquals(1, myTree.getModules(myTree.getModules(roots.get(0)).get(0)).size()); deleteProject(m1); roots = myTree.getRootProjects(); assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); assertEquals(0, myTree.getModules(roots.get(0)).size()); } public void testUpdatingModelWhenActiveProfilesChange() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<profiles>" + " <profile>" + " <id>one</id>" + " <properties>" + " <prop>value1</prop>" + " </properties>" + " </profile>" + " <profile>" + " <id>two</id>" + " <properties>" + " <prop>value2</prop>" + " </properties>" + " </profile>" + "</profiles>" + "<modules>" + " <module>m</module>" + "</modules>" + "<build>" + " <sourceDirectory>${prop}</sourceDirectory>" + "</build>"); createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>project</artifactId>" + " <version>1</version>" + "</parent>" + "<build>" + " <sourceDirectory>${prop}</sourceDirectory>" + "</build>"); readModel(Arrays.asList("one"), myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); MavenProject parentNode = roots.get(0); MavenProject childNode = myTree.getModules(roots.get(0)).get(0); assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); readModel(Arrays.asList("two"), myProjectPom); assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); } public void testUpdatingModelWhenProfilesXmlChange() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<build>" + " <sourceDirectory>${prop}</sourceDirectory>" + "</build>"); createProfilesXml("<profile>" + " <id>one</id>" + " <activation>" + " <activeByDefault>true</activeByDefault>" + " </activation>" + " <properties>" + " <prop>value1</prop>" + " </properties>" + "</profile>"); readModel(myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); MavenProject project = roots.get(0); assertUnorderedElementsAreEqual(project.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); createProfilesXml("<profile>" + " <id>one</id>" + " <activation>" + " <activeByDefault>true</activeByDefault>" + " </activation>" + " <properties>" + " <prop>value2</prop>" + " </properties>" + "</profile>"); readModel(myProjectPom); assertUnorderedElementsAreEqual(project.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); } public void testUpdatingModelWhenParentProfilesXmlChange() throws Exception { VirtualFile parent = createModulePom("parent", "<groupId>test</groupId>" + "<artifactId>parent</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>"); createProfilesXml("parent", "<profile>" + " <id>one</id>" + " <activation>" + " <activeByDefault>true</activeByDefault>" + " </activation>" + " <properties>" + " <prop>value1</prop>" + " </properties>" + "</profile>"); VirtualFile child = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>parent</artifactId>" + " <version>1</version>" + "</parent>" + "<build>" + " <sourceDirectory>${prop}</sourceDirectory>" + "</build>"); readModel(parent, child); List<MavenProject> roots = myTree.getRootProjects(); MavenProject childProject = roots.get(1); assertUnorderedElementsAreEqual(childProject.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); createProfilesXml("parent", "<profile>" + " <id>one</id>" + " <activation>" + " <activeByDefault>true</activeByDefault>" + " </activation>" + " <properties>" + " <prop>value2</prop>" + " </properties>" + "</profile>"); update(parent); assertUnorderedElementsAreEqual(childProject.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); } public void testUpdatingModelWhenParentProfilesXmlChangeAndItIsAModuleAlso() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>"); createProfilesXml("<profile>" + " <id>one</id>" + " <activation>" + " <activeByDefault>true</activeByDefault>" + " </activation>" + " <properties>" + " <prop>value1</prop>" + " </properties>" + "</profile>"); createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>project</artifactId>" + " <version>1</version>" + "</parent>" + "<build>" + " <sourceDirectory>${prop}</sourceDirectory>" + "</build>"); readModel(myProjectPom); MavenProject childNode = myTree.getModules(myTree.getRootProjects().get(0)).get(0); assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); createProfilesXml("<profile>" + " <id>one</id>" + " <activation>" + " <activeByDefault>true</activeByDefault>" + " </activation>" + " <properties>" + " <prop>value2</prop>" + " </properties>" + "</profile>"); readModel(myProjectPom); assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); } public void testUpdatingModelWhenSettingXmlChange() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<packaging>pom</packaging>" + "<modules>" + " <module>m</module>" + "</modules>" + "<build>" + " <sourceDirectory>${prop}</sourceDirectory>" + "</build>"); createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>" + "<parent>" + " <groupId>test</groupId>" + " <artifactId>project</artifactId>" + " <version>1</version>" + "</parent>" + "<build>" + " <sourceDirectory>${prop}</sourceDirectory>" + "</build>"); updateSettingsXml("<profiles>" + " <profile>" + " <id>one</id>" + " <activation>" + " <activeByDefault>true</activeByDefault>" + " </activation>" + " <properties>" + " <prop>value1</prop>" + " </properties>" + " </profile>" + "</profiles>"); readModel(myProjectPom); List<MavenProject> roots = myTree.getRootProjects(); MavenProject parentNode = roots.get(0); MavenProject childNode = myTree.getModules(roots.get(0)).get(0); assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); updateSettingsXml("<profiles>" + " <profile>" + " <id>one</id>" + " <activation>" + " <activeByDefault>true</activeByDefault>" + " </activation>" + " <properties>" + " <prop>value2</prop>" + " </properties>" + " </profile>" + "</profiles>"); myEmbeddersManager.reset(); // emulate watcher readModel(myProjectPom); assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); } protected void readModel(VirtualFile... files) throws MavenProcessCanceledException, MavenException { readModel(Collections.<String>emptyList(), files); } protected void readModel(List<String> profiles, VirtualFile... files) throws MavenProcessCanceledException, MavenException { myTree.setManagedFiles(asList(files)); myTree.setActiveProfiles(profiles); myTree.updateAll(isQuick, myEmbeddersManager, getMavenGeneralSettings(), NULL_CONSOLE, EMPTY_MAVEN_PROCESS); } protected void update(VirtualFile file) throws MavenProcessCanceledException { myTree.update(asList(file), isQuick, myEmbeddersManager, getMavenGeneralSettings(), NULL_CONSOLE, EMPTY_MAVEN_PROCESS); } protected void deleteProject(VirtualFile file) throws MavenProcessCanceledException { myTree.delete(asList(file), isQuick, myEmbeddersManager, getMavenGeneralSettings(), NULL_CONSOLE, EMPTY_MAVEN_PROCESS); } private void updateTimestamps(VirtualFile... files) throws IOException { for (VirtualFile each : files) { each.setBinaryContent(each.contentsToByteArray()); } } protected static class MyLoggingListener implements MavenProjectsTree.Listener { String log = ""; public void projectsReadQuickly(List<MavenProject> projects) { log += "projectsReadQuickly "; } public void projectRead(MavenProject project, org.apache.maven.project.MavenProject nativeMavenProject) { log += "read " + project.getMavenId().artifactId + " "; } public void projectAggregatorChanged(MavenProject project) { log += "reconnected " + project.getMavenId().artifactId + " "; } public void projectResolved(MavenProject project) { log += "resolved " + project.getMavenId().artifactId + " "; } public void projectRemoved(MavenProject project) { log += "removed " + project.getMavenId().artifactId + " "; } } }
fe766ef90f56e83a135bc13c690b77e2b13dc146
9c31941e42baa82f2bde1ca9bb2870e96afbdfac
/src/com/doubleshoot/motion/IMotion.java
83b03ddb35f2380c02243a39f1d83f81716d5569
[]
no_license
etnlGD/Double-Shoot
17f92514337c757775dc703c55e53e9e1487fb3e
3cefe80e2e0e1f25d0972419f602340d210cc6ff
refs/heads/master
2021-01-17T05:29:11.916761
2014-08-21T14:20:32
2014-08-21T14:20:32
21,231,567
3
1
null
null
null
null
UTF-8
Java
false
false
221
java
package com.doubleshoot.motion; import org.andengine.engine.handler.IUpdateHandler; import com.doubleshoot.movable.IMovable; public interface IMotion { public IUpdateHandler createMotionModifier(IMovable pMovable); }
834196ba30807660eb3f029e7032fe162383482e
fa664925fe27cfd6fc1b18a67f58446fc88b9728
/Chapter2/exercises/Exercise2_18.java
8a7c6ab39d2eefa8d1b76674b7bab4e55686b152
[]
no_license
mariemueller-codes/Java-How-to-Program11E
23fd5e10ac5f7a42e000571d8fb125debc1a2ff9
bf7fa06410d1456e4d536e165dbae219874080dc
refs/heads/master
2022-11-27T02:49:18.095824
2022-11-06T16:11:07
2022-11-06T16:11:07
199,364,765
0
0
null
2019-07-29T03:54:57
2019-07-29T02:35:42
null
ISO-8859-1
Java
false
false
1,224
java
package chapter2Exercises; /*Write an application that displays a box, * an oval, * an arrow * and a diamond using asterisks (*) */ public class Exercise2_18 { public static void main(String[] args) { System.out.println ("This Application Displays A Box, An Oval, An Arrow" + " And A Diamond Using Asterisks (*)\n"); System.out.print ("*********      ***        *          * \n"); System.out.print ("*       *    *     *     ***        * * \n"); System.out.print ("*       *   *       *   *****      *   * \n"); System.out.print ("*       *   *       *     *       *     * \n"); System.out.print ("*       *   *       *     *      *       * \n"); System.out.print ("*       *   *       *     *       *     * \n"); System.out.print ("*       *   *       *     *        *   * \n"); System.out.print ("*       *    *     *      *         * * \n"); System.out.print ("*********      ***        *          * \n"); } // end main method } // end class Exercise2_18
029238cf8f7e293e51163b26745b0352cc2aef36
369ef013fbd2a81d8037b7e51e52d1845aad9209
/springboot-activiti2-master/src/main/java/com/example/demo/activiti/web/management/ProcessEngineInfoController.java
ad1c2afd36e1642a183880a865c13362b5b6d35d
[]
no_license
flycross/activit-springboot-mutli-source
f06317f32e1d2cb60c0a73edf44973fe7861c4d5
0f23352fafe9737c21cdcbe4ffcf014f1e21d13a
refs/heads/master
2021-04-26T22:04:23.125984
2018-03-07T06:11:27
2018-03-07T06:11:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,349
java
package com.example.demo.activiti.web.management; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Set; import org.activiti.engine.ManagementService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * 作业控制器 * User: henryyan */ @Controller @RequestMapping(value = "/management/engine") public class ProcessEngineInfoController { @Autowired ManagementService managementService; @RequestMapping("") public ModelAndView info() { ModelAndView mav = new ModelAndView("management/engine-info"); Map<String,String> engineProperties = managementService.getProperties(); mav.addObject("engineProperties", engineProperties); Map<String,String> systemProperties = new HashMap<String, String>(); Properties systemProperties11 = System.getProperties(); Set<Object> objects = systemProperties11.keySet(); for (Object object : objects) { systemProperties.put(object.toString(), systemProperties11.get(object.toString()).toString()); } mav.addObject("systemProperties", systemProperties); return mav; } }
f99a018c86b5878d0fe9acc033d86f6a46a8afc6
a150d03a87a28af74abae0f9b2cbfef164e69a8f
/src/org/dmd/mvw/client/mvwselection/generated/mvw/events/SingleDMOSelectedEventHandler.java
e99cc681ca2de34fc1e0b5ed4dcd2383a85f375e
[]
no_license
dark-matter-org/dark-matter-mvw
4d25454cdf9225c4dffb684b9f2c95be565ac874
88b1aea221571c080292fe7f28c9f8a0b0fc6eb1
refs/heads/master
2021-07-19T20:39:50.448942
2019-12-07T20:04:11
2019-12-07T20:04:11
46,194,408
0
0
null
2021-06-07T18:05:21
2015-11-14T22:21:05
Java
UTF-8
Java
false
false
614
java
package org.dmd.mvw.client.mvwselection.generated.mvw.events; // Generated from: org.dmd.util.codegen.ImportManager.getFormattedImportsStatic(ImportManager.java:37) // Called from: org.dmd.mvw.tools.mvwgenerator.util.GwtEventFormatter.dumpHandler(GwtEventFormatter.java:182) import com.google.gwt.event.shared.EventHandler; // The marker interface // Generated from: org.dmd.mvw.tools.mvwgenerator.util.GwtEventFormatter.dumpHandler(GwtEventFormatter.java:184) public interface SingleDMOSelectedEventHandler extends EventHandler { void handleSingleDMOSelectedEvent(SingleDMOSelectedEvent event); }
[ "pstrong99@c0aa5241-de7e-54de-0197-666b8cbfb6a2" ]
pstrong99@c0aa5241-de7e-54de-0197-666b8cbfb6a2
2a9caf6c58f99fdf02f90d7b09fb51800ff50a53
994bc43f551b4e595e7abd41b89c2eefff758e29
/ApplicationsCoding/gen/org/uzero/android/crope/Manifest.java
69c33c26e4c575b86433b086bbfa85930a0f47f1
[]
no_license
ThariqS/ScreenLockApp
97f9bacc7a72589e99cfc14898f033c086d6aa05
d2860d6a8ae108d75a31daa5b4ae25dea43f65de
refs/heads/master
2021-03-27T16:12:35.158468
2013-08-13T17:54:36
2013-08-13T17:54:36
11,083,172
0
0
null
null
null
null
UTF-8
Java
false
false
392
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package org.uzero.android.crope; public final class Manifest { public static final class permission { public static final String MAPS_RECEIVE="com.example.mapdemo.permission.MAPS_RECEIVE"; } }
194000908831f24e3ad29e4c21d713d7b91f0d56
5d7c8d78e72ae3ea6e61154711fdd23248c19614
/sources/com/uc/webview/export/internal/c/a/a.java
33c1a61f409ba0272ce13d0b5883b16a5b278c10
[]
no_license
activeliang/tv.taobao.android
8058497bbb45a6090313e8445107d987d676aff6
bb741de1cca9a6281f4c84a6d384333b6630113c
refs/heads/master
2022-11-28T10:12:53.137874
2020-08-06T05:43:15
2020-08-06T05:43:15
285,483,760
7
6
null
null
null
null
UTF-8
Java
false
false
62,414
java
package com.uc.webview.export.internal.c.a; import android.content.Context; import android.content.pm.PackageInfo; import android.os.Handler; import android.os.HandlerThread; import com.ali.auth.third.core.model.KernelMessageConstants; import com.bftv.fui.constantplugin.Constant; import com.uc.webview.export.cyclone.UCCyclone; import com.uc.webview.export.internal.d; import com.uc.webview.export.internal.utility.Log; import com.uc.webview.export.utility.Utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; /* compiled from: ProGuard */ public final class a { public static a a; Context b; public Handler c; public Map<String, C0009a> d; public List<b> e; public SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd"); public SimpleDateFormat g = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public Object h = new Object(); private HandlerThread i = new HandlerThread("SDKWaStatThread", 0); static /* synthetic */ byte[] a(a aVar, String[] strArr) { ArrayList<String[]> arrayList; Object[] b2 = aVar.b(); if (b2 == null) { return null; } StringBuilder sb = new StringBuilder(); sb.append("lt=uc"); Map map = (Map) b2[0]; List<b> list = (List) b2[1]; List<PackageInfo> installedPackages = aVar.b.getPackageManager().getInstalledPackages(0); List<String[]> a2 = aVar.a(installedPackages); strArr[0] = b(map, list); for (Map.Entry entry : map.entrySet()) { String str = ((C0009a) entry.getValue()).b.get("tm"); String substring = (str == null || str.length() <= 10) ? null : str.substring(0, 10); sb.append("\n"); for (String[] next : a2) { sb.append(next[0]).append("=").append(next[1]).append("`"); } if (substring.equals(strArr[0])) { String str2 = strArr[0]; if (str2 == null) { arrayList = new ArrayList<>(0); } else { arrayList = new ArrayList<>(); String string = aVar.b.getSharedPreferences("UC_WA_STAT", 0).getString("4", (String) null); if (string == null || !string.equals(str2)) { arrayList.add(new String[]{"sdk_3rdappf", b(installedPackages)}); } } for (String[] strArr2 : arrayList) { sb.append(strArr2[0]).append("=").append(strArr2[1]).append("`"); } } for (Map.Entry next2 : ((C0009a) entry.getValue()).a.entrySet()) { sb.append((String) next2.getKey()).append("=").append(String.valueOf(next2.getValue())).append("`"); } for (Map.Entry next3 : ((C0009a) entry.getValue()).b.entrySet()) { sb.append((String) next3.getKey()).append("=").append((String) next3.getValue()).append("`"); } for (Map.Entry next4 : d.v.entrySet()) { sb.append((String) next4.getKey()).append("=").append(String.valueOf(((Integer) next4.getValue()).intValue())).append("`"); } } for (b bVar : list) { sb.append("\n"); for (String[] next5 : a2) { sb.append(next5[0]).append("=").append(next5[1]).append("`"); } for (Map.Entry next6 : bVar.b.entrySet()) { sb.append((String) next6.getKey()).append("=").append((String) next6.getValue()).append("`"); } } if (Utils.sWAPrintLog) { Log.i("SDKWaStat", "getUploadData:\n" + sb.toString()); } return sb.toString().getBytes(); } /* renamed from: com.uc.webview.export.internal.c.a.a$a reason: collision with other inner class name */ /* compiled from: ProGuard */ private class C0009a { public Map<String, Integer> a; public Map<String, String> b; private C0009a() { this.a = new HashMap(); this.b = new HashMap(); } public /* synthetic */ C0009a(a aVar, byte b2) { this(); } } /* compiled from: ProGuard */ private class b { String a; Map<String, String> b; public b(String str, Map<String, String> map) { this.a = str; this.b = map; } } private a() { this.i.start(); this.c = new Handler(this.i.getLooper()); } public static synchronized void a(Context context) { synchronized (a.class) { if (!d.f) { if (a == null) { a = new a(); } a.b = context.getApplicationContext(); } } } /* JADX ERROR: IndexOutOfBoundsException in pass: RegionMakerVisitor java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:657) at java.util.ArrayList.get(ArrayList.java:433) at jadx.core.dex.nodes.InsnNode.getArg(InsnNode.java:101) at jadx.core.dex.visitors.regions.RegionMaker.traverseMonitorExits(RegionMaker.java:611) at jadx.core.dex.visitors.regions.RegionMaker.traverseMonitorExits(RegionMaker.java:619) at jadx.core.dex.visitors.regions.RegionMaker.traverseMonitorExits(RegionMaker.java:619) at jadx.core.dex.visitors.regions.RegionMaker.traverseMonitorExits(RegionMaker.java:619) at jadx.core.dex.visitors.regions.RegionMaker.traverseMonitorExits(RegionMaker.java:619) at jadx.core.dex.visitors.regions.RegionMaker.traverseMonitorExits(RegionMaker.java:619) at jadx.core.dex.visitors.regions.RegionMaker.traverseMonitorExits(RegionMaker.java:619) at jadx.core.dex.visitors.regions.RegionMaker.traverseMonitorExits(RegionMaker.java:619) at jadx.core.dex.visitors.regions.RegionMaker.traverseMonitorExits(RegionMaker.java:619) at jadx.core.dex.visitors.regions.RegionMaker.traverseMonitorExits(RegionMaker.java:619) at jadx.core.dex.visitors.regions.RegionMaker.processMonitorEnter(RegionMaker.java:561) at jadx.core.dex.visitors.regions.RegionMaker.traverse(RegionMaker.java:133) at jadx.core.dex.visitors.regions.RegionMaker.makeRegion(RegionMaker.java:86) at jadx.core.dex.visitors.regions.RegionMaker.processIf(RegionMaker.java:693) at jadx.core.dex.visitors.regions.RegionMaker.traverse(RegionMaker.java:123) at jadx.core.dex.visitors.regions.RegionMaker.makeRegion(RegionMaker.java:86) at jadx.core.dex.visitors.regions.RegionMaker.processIf(RegionMaker.java:693) at jadx.core.dex.visitors.regions.RegionMaker.traverse(RegionMaker.java:123) at jadx.core.dex.visitors.regions.RegionMaker.makeRegion(RegionMaker.java:86) at jadx.core.dex.visitors.regions.RegionMaker.processMonitorEnter(RegionMaker.java:598) at jadx.core.dex.visitors.regions.RegionMaker.traverse(RegionMaker.java:133) at jadx.core.dex.visitors.regions.RegionMaker.makeRegion(RegionMaker.java:86) at jadx.core.dex.visitors.regions.RegionMakerVisitor.visit(RegionMakerVisitor.java:49) */ final synchronized void a() { /* r7 = this; r2 = 1 r1 = 0 monitor-enter(r7) boolean r0 = com.uc.webview.export.internal.d.f // Catch:{ all -> 0x008f } if (r0 != 0) goto L_0x0026 r0 = 10006(0x2716, float:1.4021E-41) r3 = 2 java.lang.Object[] r3 = new java.lang.Object[r3] // Catch:{ all -> 0x008f } r4 = 0 java.lang.String r5 = "stat" r3[r4] = r5 // Catch:{ all -> 0x008f } r4 = 1 r5 = 1 java.lang.Boolean r5 = java.lang.Boolean.valueOf(r5) // Catch:{ all -> 0x008f } r3[r4] = r5 // Catch:{ all -> 0x008f } java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r0, (java.lang.Object[]) r3) // Catch:{ all -> 0x008f } java.lang.Boolean r0 = (java.lang.Boolean) r0 // Catch:{ all -> 0x008f } boolean r0 = r0.booleanValue() // Catch:{ all -> 0x008f } if (r0 != 0) goto L_0x0028 L_0x0026: monitor-exit(r7) return L_0x0028: boolean r0 = com.uc.webview.export.utility.Utils.sWAPrintLog // Catch:{ Exception -> 0x0086 } if (r0 == 0) goto L_0x0035 java.lang.String r0 = "SDKWaStat" java.lang.String r3 = "saveData" com.uc.webview.export.internal.utility.Log.d(r0, r3) // Catch:{ Exception -> 0x0086 } L_0x0035: java.util.HashMap r3 = new java.util.HashMap // Catch:{ Exception -> 0x0086 } r3.<init>() // Catch:{ Exception -> 0x0086 } java.util.ArrayList r4 = new java.util.ArrayList // Catch:{ Exception -> 0x0086 } r4.<init>() // Catch:{ Exception -> 0x0086 } java.lang.Object r5 = r7.h // Catch:{ Exception -> 0x0086 } monitor-enter(r5) // Catch:{ Exception -> 0x0086 } r0 = 10010(0x271a, float:1.4027E-41) r6 = 0 java.lang.Object[] r6 = new java.lang.Object[r6] // Catch:{ all -> 0x008c } java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r0, (java.lang.Object[]) r6) // Catch:{ all -> 0x008c } java.lang.Boolean r0 = (java.lang.Boolean) r0 // Catch:{ all -> 0x008c } boolean r0 = r0.booleanValue() // Catch:{ all -> 0x008c } if (r0 == 0) goto L_0x006a java.util.Map<java.lang.String, com.uc.webview.export.internal.c.a.a$a> r0 = r7.d // Catch:{ all -> 0x008c } if (r0 == 0) goto L_0x005d int r0 = r0.size() // Catch:{ all -> 0x008c } if (r0 != 0) goto L_0x0088 L_0x005d: r0 = r2 L_0x005e: if (r0 != 0) goto L_0x006a java.util.Map<java.lang.String, com.uc.webview.export.internal.c.a.a$a> r0 = r7.d // Catch:{ all -> 0x008c } r3.putAll(r0) // Catch:{ all -> 0x008c } java.util.Map<java.lang.String, com.uc.webview.export.internal.c.a.a$a> r0 = r7.d // Catch:{ all -> 0x008c } r0.clear() // Catch:{ all -> 0x008c } L_0x006a: java.util.List<com.uc.webview.export.internal.c.a.a$b> r0 = r7.e // Catch:{ all -> 0x008c } if (r0 == 0) goto L_0x0074 int r0 = r0.size() // Catch:{ all -> 0x008c } if (r0 != 0) goto L_0x008a L_0x0074: r0 = r2 L_0x0075: if (r0 != 0) goto L_0x0081 java.util.List<com.uc.webview.export.internal.c.a.a$b> r0 = r7.e // Catch:{ all -> 0x008c } r4.addAll(r0) // Catch:{ all -> 0x008c } java.util.List<com.uc.webview.export.internal.c.a.a$b> r0 = r7.e // Catch:{ all -> 0x008c } r0.clear() // Catch:{ all -> 0x008c } L_0x0081: monitor-exit(r5) // Catch:{ all -> 0x008c } r7.a((java.util.Map<java.lang.String, com.uc.webview.export.internal.c.a.a.C0009a>) r3, (java.util.List<com.uc.webview.export.internal.c.a.a.b>) r4) // Catch:{ Exception -> 0x0086 } goto L_0x0026 L_0x0086: r0 = move-exception goto L_0x0026 L_0x0088: r0 = r1 goto L_0x005e L_0x008a: r0 = r1 goto L_0x0075 L_0x008c: r0 = move-exception monitor-exit(r5) // Catch:{ all -> 0x008c } throw r0 // Catch:{ Exception -> 0x0086 } L_0x008f: r0 = move-exception monitor-exit(r7) throw r0 */ throw new UnsupportedOperationException("Method not decompiled: com.uc.webview.export.internal.c.a.a.a():void"); } private void a(Map<String, C0009a> map, List<b> list) { boolean z; FileWriter fileWriter; FileWriter fileWriter2; BufferedWriter bufferedWriter; Throwable th; BufferedWriter bufferedWriter2 = null; boolean z2 = true; if (map.size() == 0) { z = true; } else { z = false; } if (z) { if (list.size() != 0) { z2 = false; } if (z2) { return; } } String str = this.b.getApplicationContext().getApplicationInfo().dataDir + "/ucwa"; File file = new File(str); if (!file.exists()) { file.mkdir(); } File file2 = new File(str, "wa_upload_new.wa"); if (Utils.sWAPrintLog) { Log.d("SDKWaStat", "savePVToFile:" + file2); } try { fileWriter2 = new FileWriter(file2, true); try { bufferedWriter = new BufferedWriter(fileWriter2, 1024); } catch (Exception e2) { fileWriter = fileWriter2; UCCyclone.close(bufferedWriter2); UCCyclone.close(fileWriter); } catch (Throwable th2) { bufferedWriter = null; th = th2; UCCyclone.close(bufferedWriter); UCCyclone.close(fileWriter2); throw th; } try { for (Map.Entry next : map.entrySet()) { bufferedWriter.write("@0"); bufferedWriter.write("@k@"); String str2 = (String) next.getKey(); String[] split = str2.split("~"); if (split[1].equals("0")) { int intValue = ((Integer) d.a((int) KernelMessageConstants.PARAM_ERROR, new Object[0])).intValue(); if (intValue != 2) { intValue = (intValue * 10) + d.l; } str2 = split[0] + "~" + intValue; } bufferedWriter.write(str2); bufferedWriter.write("@d@"); a(bufferedWriter, ((C0009a) next.getValue()).a, 0); a(bufferedWriter, ((C0009a) next.getValue()).b, 1); bufferedWriter.newLine(); } for (int i2 = 0; i2 < 10; i2++) { if (i2 >= list.size()) { break; } b bVar = list.get(i2); bufferedWriter.write("@1"); bufferedWriter.write("@k@"); bufferedWriter.write(bVar.a); bufferedWriter.write("@d@"); a(bufferedWriter, bVar.b, 1); bufferedWriter.newLine(); } UCCyclone.close(bufferedWriter); UCCyclone.close(fileWriter2); } catch (Exception e3) { bufferedWriter2 = bufferedWriter; fileWriter = fileWriter2; UCCyclone.close(bufferedWriter2); UCCyclone.close(fileWriter); } catch (Throwable th3) { th = th3; UCCyclone.close(bufferedWriter); UCCyclone.close(fileWriter2); throw th; } } catch (Exception e4) { fileWriter = null; UCCyclone.close(bufferedWriter2); UCCyclone.close(fileWriter); } catch (Throwable th4) { bufferedWriter = null; fileWriter2 = null; th = th4; UCCyclone.close(bufferedWriter); UCCyclone.close(fileWriter2); throw th; } } private static <T> void a(BufferedWriter bufferedWriter, Map<String, T> map, int i2) { if (!(map == null || map.size() == 0)) { for (Map.Entry next : map.entrySet()) { bufferedWriter.write((String) next.getKey()); bufferedWriter.write("="); bufferedWriter.write(Constant.INTENT_JSON_MARK + i2); bufferedWriter.write(next.getValue() + "`"); } } } private Object[] b() { FileReader fileReader; BufferedReader bufferedReader; Throwable th; C0009a aVar; String str = this.b.getApplicationContext().getApplicationInfo().dataDir + "/ucwa"; File file = new File(str); if (!file.exists()) { file.mkdir(); } File file2 = new File(str, "wa_upload_new.wa"); if (Utils.sWAPrintLog) { Log.d("SDKWaStat", "getPVFromFile:" + file2 + " exists:" + file2.exists()); } if (!file2.exists()) { return null; } FileReader fileReader2 = null; BufferedReader bufferedReader2 = null; HashMap hashMap = new HashMap(); ArrayList arrayList = new ArrayList(); try { fileReader = new FileReader(file2); try { bufferedReader = new BufferedReader(fileReader, 1024); while (true) { try { String readLine = bufferedReader.readLine(); if (readLine == null) { break; } if (Utils.sWAPrintLog) { Log.d("SDKWaStat", readLine); } if (!(readLine == null || readLine.trim().length() == 0)) { String trim = readLine.trim(); if (trim.startsWith("@0") || trim.startsWith("@1")) { int indexOf = trim.indexOf("@k@"); int indexOf2 = trim.indexOf("@d@"); if (indexOf >= 0 && indexOf2 >= 0) { String substring = trim.substring(indexOf + 3, indexOf2); String[] split = trim.substring(indexOf2 + 3).split("`"); if (trim.startsWith("@0")) { String[] split2 = substring.split("~"); if (split2.length == 2 && split2[0].length() == 8 && split2[1].length() <= 2) { C0009a aVar2 = (C0009a) hashMap.get(substring); if (aVar2 != null) { aVar = aVar2; } else if (hashMap.size() != 8) { C0009a aVar3 = new C0009a(this, (byte) 0); hashMap.put(substring, aVar3); aVar = aVar3; } else if (arrayList.size() == 10) { break; } for (String split3 : split) { String[] split4 = split3.split("="); if (split4.length == 2 && split4[1].length() > 2) { String substring2 = split4[1].substring(2); if (split4[1].startsWith("#0")) { Integer num = aVar.a.get(split4[0]); if (num == null) { aVar.a.put(split4[0], Integer.valueOf(Integer.parseInt(substring2))); } else { aVar.a.put(split4[0], Integer.valueOf(num.intValue() + Integer.parseInt(substring2))); } } else if (split4[1].startsWith("#1")) { aVar.b.put(split4[0], substring2); } } } aVar.b.put("core_t", split2[1]); } } else if (arrayList.size() != 10) { HashMap hashMap2 = new HashMap(split.length); for (String split5 : split) { String[] split6 = split5.split("="); if (split6.length == 2) { hashMap2.put(split6[0], split6[1].substring(2)); } } hashMap2.put("ev_ac", substring); arrayList.add(new b(substring, hashMap2)); } } } } } catch (Exception e2) { bufferedReader2 = bufferedReader; fileReader2 = fileReader; UCCyclone.close(bufferedReader2); UCCyclone.close(fileReader2); return null; } catch (Throwable th2) { th = th2; UCCyclone.close(bufferedReader); UCCyclone.close(fileReader); throw th; } } if (hashMap.size() > 0 || arrayList.size() > 0) { Object[] objArr = {hashMap, arrayList}; UCCyclone.close(bufferedReader); UCCyclone.close(fileReader); return objArr; } UCCyclone.close(bufferedReader); UCCyclone.close(fileReader); return null; } catch (Exception e3) { fileReader2 = fileReader; UCCyclone.close(bufferedReader2); UCCyclone.close(fileReader2); return null; } catch (Throwable th3) { Throwable th4 = th3; bufferedReader = null; th = th4; UCCyclone.close(bufferedReader); UCCyclone.close(fileReader); throw th; } } catch (Exception e4) { UCCyclone.close(bufferedReader2); UCCyclone.close(fileReader2); return null; } catch (Throwable th5) { Throwable th6 = th5; fileReader = null; bufferedReader = null; th = th6; UCCyclone.close(bufferedReader); UCCyclone.close(fileReader); throw th; } } /* JADX WARNING: Removed duplicated region for block: B:109:0x03e8 */ /* JADX WARNING: Removed duplicated region for block: B:110:0x03ed */ /* JADX WARNING: Removed duplicated region for block: B:111:0x03f2 */ /* JADX WARNING: Removed duplicated region for block: B:112:0x03f7 */ /* JADX WARNING: Removed duplicated region for block: B:113:0x03fc */ /* JADX WARNING: Removed duplicated region for block: B:114:0x0401 */ /* JADX WARNING: Removed duplicated region for block: B:115:0x0406 */ /* JADX WARNING: Removed duplicated region for block: B:116:0x040b */ /* JADX WARNING: Removed duplicated region for block: B:117:0x0410 */ /* JADX WARNING: Removed duplicated region for block: B:118:0x0415 */ /* JADX WARNING: Removed duplicated region for block: B:119:0x041a */ /* JADX WARNING: Removed duplicated region for block: B:120:0x041f */ /* JADX WARNING: Removed duplicated region for block: B:121:0x0424 */ /* JADX WARNING: Removed duplicated region for block: B:122:0x0429 */ /* JADX WARNING: Removed duplicated region for block: B:123:0x042e */ /* JADX WARNING: Removed duplicated region for block: B:124:0x0433 */ /* JADX WARNING: Removed duplicated region for block: B:125:0x0438 */ /* JADX WARNING: Removed duplicated region for block: B:126:0x043d */ /* JADX WARNING: Removed duplicated region for block: B:127:0x0442 */ /* JADX WARNING: Removed duplicated region for block: B:128:0x0447 */ /* JADX WARNING: Removed duplicated region for block: B:129:0x044c */ /* JADX WARNING: Removed duplicated region for block: B:130:0x044f */ /* JADX WARNING: Removed duplicated region for block: B:131:0x0461 */ /* JADX WARNING: Removed duplicated region for block: B:133:0x0469 */ /* JADX WARNING: Removed duplicated region for block: B:20:0x00e0 */ /* JADX WARNING: Removed duplicated region for block: B:23:0x00eb */ /* JADX WARNING: Removed duplicated region for block: B:26:0x0108 */ /* JADX WARNING: Removed duplicated region for block: B:29:0x0125 */ /* JADX WARNING: Removed duplicated region for block: B:32:0x0142 */ /* JADX WARNING: Removed duplicated region for block: B:35:0x015f */ /* JADX WARNING: Removed duplicated region for block: B:38:0x017c */ /* JADX WARNING: Removed duplicated region for block: B:41:0x0199 */ /* JADX WARNING: Removed duplicated region for block: B:44:0x01b6 */ /* JADX WARNING: Removed duplicated region for block: B:47:0x01d3 */ /* JADX WARNING: Removed duplicated region for block: B:50:0x01f0 */ /* JADX WARNING: Removed duplicated region for block: B:53:0x020d */ /* JADX WARNING: Removed duplicated region for block: B:56:0x022a */ /* JADX WARNING: Removed duplicated region for block: B:59:0x0247 */ /* JADX WARNING: Removed duplicated region for block: B:62:0x0264 */ /* JADX WARNING: Removed duplicated region for block: B:65:0x0281 */ /* JADX WARNING: Removed duplicated region for block: B:68:0x029f */ /* JADX WARNING: Removed duplicated region for block: B:71:0x02bd */ /* JADX WARNING: Removed duplicated region for block: B:74:0x02db */ /* JADX WARNING: Removed duplicated region for block: B:77:0x02f9 */ /* JADX WARNING: Removed duplicated region for block: B:82:0x032d */ /* JADX WARNING: Removed duplicated region for block: B:84:0x0330 */ /* JADX WARNING: Removed duplicated region for block: B:89:0x0362 */ /* JADX WARNING: Removed duplicated region for block: B:91:0x0365 */ /* JADX WARNING: Removed duplicated region for block: B:93:0x0379 */ /* JADX WARNING: Removed duplicated region for block: B:99:0x03b4 */ /* Code decompiled incorrectly, please refer to instructions dump. */ private java.util.List<java.lang.String[]> a(java.util.List<android.content.pm.PackageInfo> r14) { /* r13 = this; r3 = 2 r12 = 10003(0x2713, float:1.4017E-41) r2 = 1 r4 = 0 java.util.Iterator r1 = r14.iterator() L_0x0009: boolean r0 = r1.hasNext() if (r0 == 0) goto L_0x03cb java.lang.Object r0 = r1.next() android.content.pm.PackageInfo r0 = (android.content.pm.PackageInfo) r0 java.lang.String r5 = r0.packageName java.lang.String r6 = "com.UCMobile" boolean r5 = r5.equals(r6) if (r5 == 0) goto L_0x03bd r1 = r2 L_0x0021: java.util.ArrayList r5 = new java.util.ArrayList r5.<init>() java.lang.String[] r0 = new java.lang.String[r3] java.lang.String r6 = "lt" r0[r4] = r6 java.lang.String r6 = "ev" r0[r2] = r6 r5.add(r0) java.lang.String[] r0 = new java.lang.String[r3] java.lang.String r6 = "ct" r0[r4] = r6 java.lang.String r6 = "corepv" r0[r2] = r6 r5.add(r0) java.lang.String[] r0 = new java.lang.String[r3] java.lang.String r6 = "ver" r0[r4] = r6 java.lang.String r6 = com.uc.webview.export.Build.Version.NAME r0[r2] = r6 r5.add(r0) java.lang.String[] r0 = new java.lang.String[r3] java.lang.String r6 = "pkg" r0[r4] = r6 android.content.Context r6 = r13.b java.lang.String r6 = r6.getPackageName() r0[r2] = r6 r5.add(r0) java.lang.String[] r0 = new java.lang.String[r3] java.lang.String r6 = "sdk_sn" r0[r4] = r6 java.lang.String r6 = com.uc.webview.export.Build.TIME r0[r2] = r6 r5.add(r0) java.lang.String[] r6 = new java.lang.String[r3] java.lang.String r0 = "sdk_pm" r6[r4] = r0 java.lang.String r0 = android.os.Build.MODEL if (r0 == 0) goto L_0x0087 java.lang.String r0 = r0.trim() int r0 = r0.length() if (r0 != 0) goto L_0x03ce L_0x0087: r0 = r2 L_0x0088: if (r0 == 0) goto L_0x03d1 java.lang.String r0 = "unknown" L_0x008d: r6[r2] = r0 r5.add(r6) java.lang.String[] r6 = new java.lang.String[r3] java.lang.String r0 = "sdk_f" r6[r4] = r0 java.lang.StringBuilder r7 = new java.lang.StringBuilder r7.<init>() java.lang.Object[] r0 = new java.lang.Object[r2] r8 = 524288(0x80000, double:2.590327E-318) java.lang.Long r8 = java.lang.Long.valueOf(r8) r0[r4] = r8 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 != 0) goto L_0x00c3 r0 = 10036(0x2734, float:1.4063E-41) java.lang.Object[] r8 = new java.lang.Object[r2] android.content.Context r9 = r13.b r8[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r0, (java.lang.Object[]) r8) if (r0 != 0) goto L_0x03e3 L_0x00c3: java.lang.String r0 = "0" L_0x00c6: java.lang.StringBuilder r8 = r7.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 1 java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x03e8 java.lang.String r0 = "1" L_0x00e3: java.lang.StringBuilder r8 = r8.append(r0) boolean r0 = com.uc.webview.export.internal.d.j if (r0 == 0) goto L_0x03ed java.lang.String r0 = "1" L_0x00ee: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 2 java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x03f2 java.lang.String r0 = "1" L_0x010b: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 4 java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x03f7 java.lang.String r0 = "1" L_0x0128: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 8 java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x03fc java.lang.String r0 = "1" L_0x0145: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 16 java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x0401 java.lang.String r0 = "1" L_0x0162: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 32 java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x0406 java.lang.String r0 = "1" L_0x017f: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 64 java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x040b java.lang.String r0 = "1" L_0x019c: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 128(0x80, double:6.32E-322) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x0410 java.lang.String r0 = "1" L_0x01b9: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 256(0x100, double:1.265E-321) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x0415 java.lang.String r0 = "1" L_0x01d6: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 512(0x200, double:2.53E-321) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x041a java.lang.String r0 = "1" L_0x01f3: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 1024(0x400, double:5.06E-321) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x041f java.lang.String r0 = "1" L_0x0210: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 2048(0x800, double:1.0118E-320) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x0424 java.lang.String r0 = "1" L_0x022d: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 4096(0x1000, double:2.0237E-320) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x0429 java.lang.String r0 = "1" L_0x024a: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 8192(0x2000, double:4.0474E-320) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x042e java.lang.String r0 = "1" L_0x0267: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 16384(0x4000, double:8.0948E-320) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x0433 java.lang.String r0 = "1" L_0x0284: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 32768(0x8000, double:1.61895E-319) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x0438 java.lang.String r0 = "1" L_0x02a2: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 65536(0x10000, double:3.2379E-319) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x043d java.lang.String r0 = "1" L_0x02c0: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 131072(0x20000, double:6.47582E-319) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x0442 java.lang.String r0 = "1" L_0x02de: java.lang.StringBuilder r8 = r8.append(r0) java.lang.Object[] r0 = new java.lang.Object[r2] r10 = 262144(0x40000, double:1.295163E-318) java.lang.Long r9 = java.lang.Long.valueOf(r10) r0[r4] = r9 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x0447 java.lang.String r0 = "1" L_0x02fc: r8.append(r0) java.lang.String r0 = r7.toString() r6[r2] = r0 r5.add(r6) java.lang.String[] r0 = new java.lang.String[r3] java.lang.String r6 = "sdk_uf" r0[r4] = r6 java.lang.String r6 = java.lang.String.valueOf(r1) r0[r2] = r6 r5.add(r0) java.lang.String[] r6 = new java.lang.String[r3] java.lang.String r0 = "sdk_bd" r6[r4] = r0 java.lang.String r0 = android.os.Build.BRAND if (r0 == 0) goto L_0x032d java.lang.String r0 = r0.trim() int r0 = r0.length() if (r0 != 0) goto L_0x044c L_0x032d: r0 = r2 L_0x032e: if (r0 == 0) goto L_0x044f java.lang.String r0 = "unknown" L_0x0333: r6[r2] = r0 r5.add(r6) java.lang.String[] r0 = new java.lang.String[r3] java.lang.String r6 = "sdk_osv" r0[r4] = r6 java.lang.String r6 = android.os.Build.VERSION.RELEASE r0[r2] = r6 r5.add(r0) java.lang.String[] r0 = new java.lang.String[r3] java.lang.String r6 = "sdk_prd" r0[r4] = r6 java.lang.String r6 = com.uc.webview.export.Build.SDK_PRD r0[r2] = r6 r5.add(r0) java.lang.String r0 = com.uc.webview.export.Build.CORE_VERSION if (r0 == 0) goto L_0x0362 java.lang.String r0 = r0.trim() int r0 = r0.length() if (r0 != 0) goto L_0x0461 L_0x0362: r0 = r2 L_0x0363: if (r0 != 0) goto L_0x0377 java.lang.String[] r0 = new java.lang.String[r3] java.lang.String r6 = "sdk_sdk_cv" r0[r4] = r6 java.lang.String r6 = com.uc.webview.export.Build.CORE_VERSION java.lang.String r6 = r6.trim() r0[r2] = r6 r5.add(r0) L_0x0377: if (r1 != 0) goto L_0x0396 java.lang.String[] r1 = new java.lang.String[r3] java.lang.String r0 = "sdk_ucbackup" r1[r4] = r0 java.io.File r0 = new java.io.File java.lang.String r6 = "/sdcard/Backucup/com.UCMobile" r0.<init>(r6) boolean r0 = r0.exists() if (r0 == 0) goto L_0x0464 java.lang.String r0 = "1" L_0x0391: r1[r2] = r0 r5.add(r1) L_0x0396: java.lang.String[] r1 = new java.lang.String[r3] java.lang.String r0 = "sdk_vac" r1[r4] = r0 java.lang.Object[] r0 = new java.lang.Object[r2] r6 = 1048576(0x100000, double:5.180654E-318) java.lang.Long r3 = java.lang.Long.valueOf(r6) r0[r4] = r3 java.lang.Object r0 = com.uc.webview.export.internal.d.a((int) r12, (java.lang.Object[]) r0) java.lang.Boolean r0 = (java.lang.Boolean) r0 boolean r0 = r0.booleanValue() if (r0 == 0) goto L_0x0469 java.lang.String r0 = "1" L_0x03b7: r1[r2] = r0 r5.add(r1) return r5 L_0x03bd: java.lang.String r0 = r0.packageName java.lang.String r5 = "com.UCMobile.intl" boolean r0 = r0.equals(r5) if (r0 == 0) goto L_0x0009 r1 = r3 goto L_0x0021 L_0x03cb: r1 = r4 goto L_0x0021 L_0x03ce: r0 = r4 goto L_0x0088 L_0x03d1: java.lang.String r0 = android.os.Build.MODEL java.lang.String r0 = r0.trim() java.lang.String r7 = "[`|=]" java.lang.String r8 = "" java.lang.String r0 = r0.replaceAll(r7, r8) goto L_0x008d L_0x03e3: java.lang.String r0 = "1" goto L_0x00c6 L_0x03e8: java.lang.String r0 = "0" goto L_0x00e3 L_0x03ed: java.lang.String r0 = "0" goto L_0x00ee L_0x03f2: java.lang.String r0 = "0" goto L_0x010b L_0x03f7: java.lang.String r0 = "0" goto L_0x0128 L_0x03fc: java.lang.String r0 = "0" goto L_0x0145 L_0x0401: java.lang.String r0 = "0" goto L_0x0162 L_0x0406: java.lang.String r0 = "0" goto L_0x017f L_0x040b: java.lang.String r0 = "0" goto L_0x019c L_0x0410: java.lang.String r0 = "0" goto L_0x01b9 L_0x0415: java.lang.String r0 = "0" goto L_0x01d6 L_0x041a: java.lang.String r0 = "0" goto L_0x01f3 L_0x041f: java.lang.String r0 = "0" goto L_0x0210 L_0x0424: java.lang.String r0 = "0" goto L_0x022d L_0x0429: java.lang.String r0 = "0" goto L_0x024a L_0x042e: java.lang.String r0 = "0" goto L_0x0267 L_0x0433: java.lang.String r0 = "0" goto L_0x0284 L_0x0438: java.lang.String r0 = "0" goto L_0x02a2 L_0x043d: java.lang.String r0 = "0" goto L_0x02c0 L_0x0442: java.lang.String r0 = "0" goto L_0x02de L_0x0447: java.lang.String r0 = "0" goto L_0x02fc L_0x044c: r0 = r4 goto L_0x032e L_0x044f: java.lang.String r0 = android.os.Build.BRAND java.lang.String r0 = r0.trim() java.lang.String r7 = "[`|=]" java.lang.String r8 = "" java.lang.String r0 = r0.replaceAll(r7, r8) goto L_0x0333 L_0x0461: r0 = r4 goto L_0x0363 L_0x0464: java.lang.String r0 = "0" goto L_0x0391 L_0x0469: java.lang.String r0 = "0" goto L_0x03b7 */ throw new UnsupportedOperationException("Method not decompiled: com.uc.webview.export.internal.c.a.a.a(java.util.List):java.util.List"); } private static String b(Map<String, C0009a> map, List<b> list) { String str; String str2; String str3 = null; for (Map.Entry<String, C0009a> value : map.entrySet()) { String str4 = ((C0009a) value.getValue()).b.get("tm"); if (str4 == null || str4.length() <= 10) { str2 = null; } else { str2 = str4.substring(0, 10); } if (str2 == null || !str2.endsWith("01") || (str3 != null && str2.compareTo(str3) <= 0)) { str2 = str3; } str3 = str2; } for (b bVar : list) { String str5 = bVar.b.get("tm"); if (str5 == null || str5.length() <= 10) { str = null; } else { str = str5.substring(0, 10); } if (str != null && str.endsWith("01")) { if (str3 == null || str.compareTo(str3) > 0) { str3 = str; } } } return str3; } /* access modifiers changed from: package-private */ public final String a(String str, String[] strArr) { ArrayList<String[]> arrayList; Object[] b2 = b(); if (b2 == null) { return null; } Map map = (Map) b2[0]; List<b> list = (List) b2[1]; try { JSONObject jSONObject = new JSONObject(); jSONObject.put("uuid", str); List<PackageInfo> installedPackages = this.b.getPackageManager().getInstalledPackages(0); for (String[] next : a(installedPackages)) { jSONObject.put(next[0], next[1]); } strArr[0] = b(map, list); String str2 = strArr[0]; if (str2 == null) { arrayList = new ArrayList<>(0); } else { arrayList = new ArrayList<>(); String string = this.b.getSharedPreferences("UC_WA_STAT", 0).getString("4", (String) null); if (string == null || !string.equals(str2)) { arrayList.add(new String[]{"sdk_3rdappf", b(installedPackages)}); } } for (String[] strArr2 : arrayList) { jSONObject.put(strArr2[0], strArr2[1]); } for (Map.Entry next2 : d.v.entrySet()) { jSONObject.put((String) next2.getKey(), ((Integer) next2.getValue()).intValue()); } JSONArray jSONArray = new JSONArray(); for (Map.Entry entry : map.entrySet()) { JSONObject jSONObject2 = new JSONObject(); for (Map.Entry next3 : ((C0009a) entry.getValue()).a.entrySet()) { jSONObject2.put((String) next3.getKey(), String.valueOf(next3.getValue())); } for (Map.Entry next4 : ((C0009a) entry.getValue()).b.entrySet()) { jSONObject2.put((String) next4.getKey(), next4.getValue()); } jSONArray.put(jSONObject2); } for (b bVar : list) { JSONObject jSONObject3 = new JSONObject(); for (Map.Entry next5 : bVar.b.entrySet()) { jSONObject3.put((String) next5.getKey(), next5.getValue()); } jSONArray.put(jSONObject3); } jSONObject.put("items", jSONArray); return jSONObject.toString(); } catch (Exception e2) { Log.e("SDKWaStat", "getJsonUploadData", e2); return null; } } /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r3v0, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r2v1, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r3v1, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r3v2, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r2v2, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r3v3, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r2v3, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r3v4, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r4v11, resolved type: java.io.InputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r2v4, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r3v5, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r3v6, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r3v7, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r2v5, resolved type: java.io.OutputStream} */ /* JADX DEBUG: Multi-variable search result rejected for TypeSearchVarInfo{r3v8, resolved type: java.io.OutputStream} */ /* JADX WARNING: Multi-variable type inference failed */ /* JADX WARNING: Removed duplicated region for block: B:24:0x008a A[Catch:{ all -> 0x00f6 }] */ /* Code decompiled incorrectly, please refer to instructions dump. */ static boolean a(java.lang.String r9, byte[] r10) { /* r2 = 1 r1 = 0 r3 = 0 java.net.URL r0 = new java.net.URL // Catch:{ Throwable -> 0x00fb, all -> 0x00df } r0.<init>(r9) // Catch:{ Throwable -> 0x00fb, all -> 0x00df } java.net.URLConnection r0 = r0.openConnection() // Catch:{ Throwable -> 0x00fb, all -> 0x00df } java.net.HttpURLConnection r0 = (java.net.HttpURLConnection) r0 // Catch:{ Throwable -> 0x00fb, all -> 0x00df } r4 = 5000(0x1388, float:7.006E-42) r0.setConnectTimeout(r4) // Catch:{ Throwable -> 0x00fb, all -> 0x00df } r4 = 1 r0.setDoInput(r4) // Catch:{ Throwable -> 0x00fb, all -> 0x00df } r4 = 1 r0.setDoOutput(r4) // Catch:{ Throwable -> 0x00fb, all -> 0x00df } java.lang.String r4 = "POST" r0.setRequestMethod(r4) // Catch:{ Throwable -> 0x00fb, all -> 0x00df } r4 = 0 r0.setUseCaches(r4) // Catch:{ Throwable -> 0x00fb, all -> 0x00df } java.lang.String r4 = "Content-Type" java.lang.String r5 = "application/x-www-form-urlencoded" r0.setRequestProperty(r4, r5) // Catch:{ Throwable -> 0x00fb, all -> 0x00df } java.lang.String r4 = "Content-Length" int r5 = r10.length // Catch:{ Throwable -> 0x00fb, all -> 0x00df } java.lang.String r5 = java.lang.String.valueOf(r5) // Catch:{ Throwable -> 0x00fb, all -> 0x00df } r0.setRequestProperty(r4, r5) // Catch:{ Throwable -> 0x00fb, all -> 0x00df } java.io.OutputStream r5 = r0.getOutputStream() // Catch:{ Throwable -> 0x00fb, all -> 0x00df } r5.write(r10) // Catch:{ Throwable -> 0x00ff, all -> 0x00ec } int r4 = r0.getResponseCode() // Catch:{ Throwable -> 0x00ff, all -> 0x00ec } r6 = 200(0xc8, float:2.8E-43) if (r4 == r6) goto L_0x0065 boolean r0 = com.uc.webview.export.utility.Utils.sWAPrintLog // Catch:{ Throwable -> 0x00ff, all -> 0x00ec } if (r0 == 0) goto L_0x005a java.lang.String r0 = "SDKWaStat" java.lang.String r2 = "response == null" java.lang.Throwable r4 = new java.lang.Throwable // Catch:{ Throwable -> 0x00ff, all -> 0x00ec } r4.<init>() // Catch:{ Throwable -> 0x00ff, all -> 0x00ec } com.uc.webview.export.internal.utility.Log.e(r0, r2, r4) // Catch:{ Throwable -> 0x00ff, all -> 0x00ec } L_0x005a: com.uc.webview.export.cyclone.UCCyclone.close(r5) com.uc.webview.export.cyclone.UCCyclone.close(r3) com.uc.webview.export.cyclone.UCCyclone.close(r3) r0 = r1 L_0x0064: return r0 L_0x0065: java.io.InputStream r4 = r0.getInputStream() // Catch:{ Throwable -> 0x00ff, all -> 0x00ec } r0 = 1024(0x400, float:1.435E-42) byte[] r0 = new byte[r0] // Catch:{ Throwable -> 0x0104, all -> 0x00ef } java.io.ByteArrayOutputStream r6 = new java.io.ByteArrayOutputStream // Catch:{ Throwable -> 0x0104, all -> 0x00ef } int r7 = r4.available() // Catch:{ Throwable -> 0x0104, all -> 0x00ef } r6.<init>(r7) // Catch:{ Throwable -> 0x0104, all -> 0x00ef } L_0x0076: int r3 = r4.read(r0) // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } r7 = -1 if (r3 == r7) goto L_0x009e r7 = 0 r6.write(r0, r7, r3) // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } goto L_0x0076 L_0x0082: r0 = move-exception r2 = r4 r3 = r5 r4 = r6 L_0x0086: boolean r5 = com.uc.webview.export.utility.Utils.sWAPrintLog // Catch:{ all -> 0x00f6 } if (r5 == 0) goto L_0x0093 java.lang.String r5 = "SDKWaStat" java.lang.String r6 = "" com.uc.webview.export.internal.utility.Log.e(r5, r6, r0) // Catch:{ all -> 0x00f6 } L_0x0093: com.uc.webview.export.cyclone.UCCyclone.close(r3) com.uc.webview.export.cyclone.UCCyclone.close(r2) com.uc.webview.export.cyclone.UCCyclone.close(r4) L_0x009c: r0 = r1 goto L_0x0064 L_0x009e: java.lang.String r0 = new java.lang.String // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } byte[] r3 = r6.toByteArray() // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } r0.<init>(r3) // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } boolean r3 = com.uc.webview.export.utility.Utils.sWAPrintLog // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } if (r3 == 0) goto L_0x00c1 java.lang.String r3 = "SDKWaStat" java.lang.StringBuilder r7 = new java.lang.StringBuilder // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } java.lang.String r8 = "response:" r7.<init>(r8) // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } java.lang.StringBuilder r7 = r7.append(r0) // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } java.lang.String r7 = r7.toString() // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } com.uc.webview.export.internal.utility.Log.i(r3, r7) // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } L_0x00c1: java.lang.String r3 = "retcode=0" boolean r0 = r0.contains(r3) // Catch:{ Throwable -> 0x0082, all -> 0x00f3 } if (r0 == 0) goto L_0x00d5 com.uc.webview.export.cyclone.UCCyclone.close(r5) com.uc.webview.export.cyclone.UCCyclone.close(r4) com.uc.webview.export.cyclone.UCCyclone.close(r6) r0 = r2 goto L_0x0064 L_0x00d5: com.uc.webview.export.cyclone.UCCyclone.close(r5) com.uc.webview.export.cyclone.UCCyclone.close(r4) com.uc.webview.export.cyclone.UCCyclone.close(r6) goto L_0x009c L_0x00df: r0 = move-exception r5 = r3 r6 = r3 L_0x00e2: com.uc.webview.export.cyclone.UCCyclone.close(r5) com.uc.webview.export.cyclone.UCCyclone.close(r3) com.uc.webview.export.cyclone.UCCyclone.close(r6) throw r0 L_0x00ec: r0 = move-exception r6 = r3 goto L_0x00e2 L_0x00ef: r0 = move-exception r6 = r3 r3 = r4 goto L_0x00e2 L_0x00f3: r0 = move-exception r3 = r4 goto L_0x00e2 L_0x00f6: r0 = move-exception r5 = r3 r6 = r4 r3 = r2 goto L_0x00e2 L_0x00fb: r0 = move-exception r2 = r3 r4 = r3 goto L_0x0086 L_0x00ff: r0 = move-exception r2 = r3 r4 = r3 r3 = r5 goto L_0x0086 L_0x0104: r0 = move-exception r2 = r4 r4 = r3 r3 = r5 goto L_0x0086 */ throw new UnsupportedOperationException("Method not decompiled: com.uc.webview.export.internal.c.a.a.a(java.lang.String, byte[]):boolean"); } private static String b(List<PackageInfo> list) { long currentTimeMillis = System.currentTimeMillis(); HashSet hashSet = new HashSet(list.size()); for (PackageInfo packageInfo : list) { hashSet.add(Integer.valueOf(packageInfo.packageName.hashCode())); } StringBuilder sb = new StringBuilder(); int[] iArr = {744792033, -796004189, 1536737232, -1864872766, -245593387, 559984781, 1254578009, 460049591, -103524201, -191341086, 2075805265, -860300598, 195266379, 851655498, -172581751, -1692253156, -1709882794, 978047406, -1447376190, 1085732649, 400412247, 1007750384, 321803898, 1319538838, -1459422248, -173313837, 1488133239, 551552610, 1310504938, 633261597, -548160304, 1971200218, 757982267, 996952171, 1855462465, 2049668591, -189253699, -761937585}; for (int i2 = 0; i2 < 38; i2++) { if (hashSet.contains(Integer.valueOf(iArr[i2]))) { sb.append("1"); } else { sb.append("0"); } } Log.i("SDKWaStat", "getOtherAppInstallFlag用时:" + (System.currentTimeMillis() - currentTimeMillis) + " " + sb); return sb.toString(); } }
ad238217f09e54b00506d6af4ab58dc085261f9f
77cde6a8bb34ddd5d52f8acf94ea6638082d2280
/app/src/test/java/com/prakpapb1/sqliteapp/ExampleUnitTest.java
116fd8452938810184fcbe98c613a01367da3f55
[]
no_license
risa06/PrakPAPB1SQLiteApp
bafeca01781b1ebd4bb0107d1b927131589c665c
cd19d00dc3ed161f9459c71a0678afe75062f62f
refs/heads/master
2023-01-19T06:11:46.628202
2020-11-28T14:24:05
2020-11-28T14:24:05
316,750,587
0
0
null
null
null
null
UTF-8
Java
false
false
384
java
package com.prakpapb1.sqliteapp; 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); } }
53b54cd371bf4cfdc96369d74ce9f799b8bc023d
3c4763922cda3f3a990b74cdba6f8a30b07467de
/src/main/java/students/kate_br/lesson_8/level_2/task_7/Cats.java
4ad41b3d51db4d58d46e5a741d066b0f038a639d
[]
no_license
VitalyPorsev/JavaGuru1
07db5a0cc122b097a20e56c9da431cd49d3c01ea
f3c25b6357309d4e9e8ac0047e51bb8031d14da8
refs/heads/main
2023-05-10T15:35:55.419713
2021-05-15T18:48:12
2021-05-15T18:48:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
210
java
package students.kate_br.lesson_8.level_2.task_7; class Cats extends Pets { String meow; public Cats(String ears, String tails, String puffs) { super(ears, tails, puffs); this.meow = meow; } }
0ddbd9e4fa66952afcf051d4c23c08bf3c223afd
61c63b4822413c630220f51027018d8b1db42043
/test-eureka-naming-server/src/main/java/com/test/Microservices/eurekaNamingServer/testeurekanamingserver/TestEurekaNamingServerApplication.java
de4107c131e209b860c65fbe8b63063885f9754e
[]
no_license
pratd/java_microservices_Example
27d19cea65aa450a774ad2c622b1b86c49c24d60
3b3117fca2148dd2dfa1bd2ba5f335bd6beac1fc
refs/heads/main
2023-03-20T05:09:15.786487
2021-03-18T11:20:11
2021-03-18T11:20:11
349,045,080
0
0
null
null
null
null
UTF-8
Java
false
false
484
java
package com.test.Microservices.eurekaNamingServer.testeurekanamingserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class TestEurekaNamingServerApplication { public static void main(String[] args) { SpringApplication.run(TestEurekaNamingServerApplication.class, args); } }
45746577ced5718f1c7de765f4a384bccb6a1dde
2c047d17b5648a16c365530e8813a364914f76c0
/boot-order-web/src/test/java/org/augustus/order/BootOrderWebApplicationTests.java
ff8d1c18f0f063fadfa259f99bba5b25afe8ac98
[]
no_license
lyjady/boot-starter
5cf989ec9e3897e1a307fd0d84e5774bf55e20da
845890a03ff497e14c42b59e22e61c208df20c36
refs/heads/master
2020-12-27T04:10:28.140953
2020-02-06T10:47:06
2020-02-06T10:47:06
237,760,447
0
0
null
null
null
null
UTF-8
Java
false
false
216
java
package org.augustus.order; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class BootOrderWebApplicationTests { @Test void contextLoads() { } }
[ "lyj2780866735" ]
lyj2780866735
4afd089a3ce6f4a7818418a90792f98a0a636b1f
95e2dc95facd44a94941d6932a6e84ad52d8d31c
/src/main/java/com/bw/util/GenEntityOracle.java
922595c05ab176196eb5833f518d0e13d4a4e4e6
[]
no_license
wangboinit/day01
98d567bdc97778df129bfe6e70e0db8f3589ab3a
78397581c722d65beb2f2e0aef102aec56760ea3
refs/heads/master
2022-04-23T04:54:51.466310
2019-09-04T08:03:19
2019-09-04T08:03:19
257,784,617
0
0
null
2020-04-22T03:45:50
2020-04-22T03:45:49
null
UTF-8
Java
false
false
13,068
java
package com.bw.util; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class GenEntityOracle { private String authorName = "wangbo";// �������� private String tablename = "eb_brand";// ���� private String packageOutPath = "main.java.com.bw.bean";// ָ��ʵ���������ڰ���·�� private String[] colnames; // �������� private String[] colTypes; // ������������ private int[] colLens; // �ֶγ������� private String[] colComments; //��ע���� private String[] tablecolnames; private int[] colSizes; // ������С���� private boolean f_util = false; // �Ƿ���Ҫ�����java.util.* private boolean f_sql = false; // �Ƿ���Ҫ�����java.sql.* private String javaName = ""; private String databaseName = "";//mysql���ݿ��� // ���ݿ����� // private static final String URL = "jdbc:oracle:thin:@192.168.215.128:1521:orcl"; // private static final String NAME = "scott"; // private static final String PASS = "tiger"; private static final String URL="jdbc:mysql://localhost:3306/1705h?user=root&password=123456&useUnicode=true&characterEncoding=UTF8"; // private static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String DRIVER = "com.mysql.jdbc.Driver"; public GenEntityOracle() { this("pingtai_kaohezhouqi","",""); } public GenEntityOracle(String tablename,String javaName,String databaseName) { this.javaName = javaName; this.tablename = tablename; this.databaseName = databaseName; //�ж�������»��߾ͽ�ȡ�����򲻽�ȡ if(tablename.indexOf("_")>0){ javaName = tablename.split("_")[1]; }else{ javaName = tablename; } } public void init() { // �������� Connection con; // ��Ҫ����ʵ����ı� String sql = "select * from " + tablename; Statement pStemt = null; try { try { Class.forName(DRIVER); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } //��ȡע�� //mysql������Ҫ��ĵĵط� ��������databaseName mysql��ѯע�ͺ�oracle��ͬ String comSql = "select column_comment from information_schema.COLUMNS where TABLE_SCHEMA='"+databaseName+"' and table_name='"+tablename.toUpperCase()+"'"; // String comSql = "select * from user_col_comments where table_name='"+tablename.toUpperCase()+"'"; // Connection ccon = DriverManager.getConnection(URL, NAME, PASS); Connection ccon = DriverManager.getConnection(URL); Statement stmt = ccon.createStatement(); ResultSet cRs = stmt.executeQuery(comSql); // con = DriverManager.getConnection(URL, NAME, PASS); con = DriverManager.getConnection(URL); pStemt = (Statement) con.createStatement(); ResultSet rs = pStemt.executeQuery(sql); ResultSetMetaData rsmd = rs.getMetaData(); int size = rsmd.getColumnCount(); // ͳ���� colnames = new String[size]; colTypes = new String[size]; colLens = new int[size]; colComments = new String[size]; colSizes = new int[size]; int j = 0; while(cRs.next()) { //MySQL��Ҫ�ĵĵط� ӦΪ��select column_comment ���Բ�ѯ��һ���� ���1 3��ʾע�������е�λ�� colComments[j] = cRs.getString(1); // colComments[j] = cRs.getString(3); j++; } for (int i = 0; i < size; i++) { colnames[i] = rsmd.getColumnName(i + 1); colTypes[i] = rsmd.getColumnTypeName(i + 1); colLens[i] = rsmd.getColumnDisplaySize(i + 1); if (colTypes[i].equalsIgnoreCase("date") || colTypes[i].equalsIgnoreCase("timestamp")) { f_util = true; } if (colTypes[i].equalsIgnoreCase("blob") || colTypes[i].equalsIgnoreCase("char")) { f_sql = true; } colSizes[i] = rsmd.getColumnDisplaySize(i + 1); } tablecolnames = colnames.clone(); for(int i=0;i<colnames.length;i++) { String s = colnames[i]; String[] strs = s.split("_"); colnames[i] = ""; for(int k=0;k<strs.length;k++) { //�ж� ��һ��Ԫ��Ĭ��ȫСд if(k == 0){ colnames[i] += strs[k].toLowerCase(); }else{ //ʵ�ִӵڶ����ʿ�ʼ����ĸ��д String num = strs[k].toLowerCase(); colnames[i] += num.substring(0,1).toUpperCase()+num.substring(1); } } } String content = parse(colnames, colTypes, colSizes); try { File directory = new File(""); // System.out.println("����·����"+directory.getAbsolutePath()); // System.out.println("���·����"+directory.getCanonicalPath()); String path = this.getClass().getResource("").getPath(); System.out.println(path); // System.out.println("src/?/"+path.substring(path.lastIndexOf("/com/", // path.length())) ); // String outputPath = directory.getAbsolutePath()+ // "/src/"+path.substring(path.lastIndexOf("/com/", // path.length()), path.length()) + initcap(tablename) + // ".java"; //���Ŀ¼ ��Ҫ�䶯��ʱ���һ�� String outputPath = directory.getAbsolutePath() + "/src/" + this.packageOutPath.replace(".", "/") + "/" + initcap(javaName) + ".java"; FileWriter fw = new FileWriter(outputPath); PrintWriter pw = new PrintWriter(fw); pw.println(content); pw.flush(); pw.close(); } catch (IOException e) { e.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); } finally { // try { // con.close(); // } catch (SQLException e) { // e.printStackTrace(); // } } } /** * ���ܣ�����ʵ����������� * * @param colnames * @param colTypes * @param colSizes * @return */ private String parse(String[] colnames, String[] colTypes, int[] colSizes) { StringBuffer sb = new StringBuffer(); sb.append("package " + this.packageOutPath + ";\r\n"); sb.append("\r\n"); // �ж��Ƿ��빤�߰� if (f_util) { } if (f_sql) { sb.append("import java.sql.*;\r\n"); } // ע�Ͳ��� // sb.append(" /**\r\n"); // sb.append(" * " + javaName + " ʵ����\r\n"); // sb.append(" * " + new Date() + " " + this.authorName + "\r\n"); // sb.append(" */ \r\n"); SimpleDateFormat sm = new SimpleDateFormat("yyyy��MM��dd�� aHH:mm:ss"); String time = sm.format(new Date()); Calendar date = Calendar.getInstance(); // ʵ�岿�� sb.append("\r\npublic class " + initcap(javaName) + " implements java.io.Serializable {\r\n"); processAllAttrs(sb);// ���� processAllMethod(sb);// get set���� sb.append("}\r\n"); // System.out.println(sb.toString()); return sb.toString(); } /** * ���ܣ��������з��� * * @param sb */ private void processAllMethod(StringBuffer sb) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String now = sdf.format(date); for (int i = 0; i < colnames.length; i++) { sb.append("\r\n\tpublic void set" + initcap(colnames[i]) + "(" + sqlType2JavaType(colTypes[i]) + " " + colnames[i] + "){\r\n"); sb.append("\t\tthis." + colnames[i] + "=" + colnames[i] + ";\r\n"); sb.append("\t}\r\n"); sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(colnames[i]) + "(){\r\n"); sb.append("\t\treturn " + colnames[i] + ";\r\n"); sb.append("\t}\r\n"); } } /** * ���ܣ������������� * * @param sb */ private void processAllAttrs(StringBuffer sb) { sb.append("\r\n\t//columns START\r\n"); String str = ""; for (int i = 0; i < colnames.length; i++) { sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + colnames[i] + ";\r\n"); str+=","+sqlType2JavaType(colTypes[i])+" "+colnames[i]; } str = str.substring(1); sb.append("\t//columns END\r\n"); sb.append("\tpublic "+javaName+"(){\r\n"); sb.append("\r\t}\r\n\r"); sb.append("\tpublic "+javaName+"("+str+"){\r\n"); for (int i = 0; i < colnames.length; i++) { if(i!=colnames.length-1){ sb.append("\t\tthis."+colnames[i]+"="+colnames[i]+";\r"); }else{ sb.append("\t\tthis."+colnames[i]+"="+colnames[i]+";"); } } sb.append("\r\t}\r\n"); } /** * ���ܣ��������ַ���������ĸ�ijɴ�д * * @param str * @return */ private String initcap(String str) { char[] ch = str.toCharArray(); if (ch[0] >= 'a' && ch[0] <= 'z') { ch[0] = (char) (ch[0] - 32); } return new String(ch); } /** * ���ܣ�����е��������� * * @param sqlType * @return */ private String sqlType2JavaType(String sqlType) { if (sqlType.equalsIgnoreCase("binary_double")) { return "double"; } else if (sqlType.equalsIgnoreCase("binary_float")) { return "float"; } else if (sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase("nvarchar2") || sqlType.equalsIgnoreCase("varchar2") || sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("blob") || sqlType.equalsIgnoreCase("clob")) { return "String"; } else if (sqlType.equalsIgnoreCase("date") || sqlType.equalsIgnoreCase("timestamp") || sqlType.equalsIgnoreCase("timestamp with local time zone") || sqlType.equalsIgnoreCase("timestamp with time zone")) { // return "Date"; return "String"; } else if (sqlType.equalsIgnoreCase("number") || sqlType.equalsIgnoreCase("int")) { return "Integer"; } return "String"; } public static void main(String[] args) { //�������DZ��� ���ɵ�ʵ������ĸ��д ������User //��һ���������� �ڶ�������ʵ������ �������������ݿ����� new GenEntityOracle("mtv","Mtv","1705h").init(); new GenEntityOracle("type","Types","1705h").init(); new GenEntityOracle("mtv_type","MtvType","1705h").init(); } }
3cba48247d22f4633c3b6170bf6778a0a5e32440
9c7015c2498419aaeb24cd8cea23eb7c54ef120c
/aishang/src/main/java/com/aishang/pojo/TbMap.java
623dfeb55b961683aae7359c807995cc4efb9362
[]
no_license
tian1iang/GitRepository
aeb730a5bfddfb6389f1ed4cc0fcaf7fa6212a45
575f05976671861344dc954d85f1cf3a423cdf5e
refs/heads/master
2021-06-05T17:45:03.322400
2016-06-13T14:12:35
2016-06-13T14:12:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
393
java
package com.aishang.pojo; public class TbMap { private Long id; private String content; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content == null ? null : content.trim(); } }
be7252b0e968d79435e2a642a8482eac72e7f7c1
c8be6f80fdf7dcc2a71e29c9ae82d845a7a6eb88
/OJ/SwordOffer/007-斐波那契数列/Solution.java
3070413fee2f2074579da0fc2aaea87440db4b27
[]
no_license
cloudy-liu/BDSA
35be50ab83c39b86d2d213cfbcb9f5d23513d01f
af0ccbbe61e943cc60918f36e276a7e368105cf9
refs/heads/master
2021-06-11T07:08:30.724833
2021-03-21T15:12:16
2021-03-21T15:12:16
137,571,843
1
0
null
null
null
null
UTF-8
Java
false
false
1,022
java
/** * https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey * * 求第n个斐波那契数列: 0,1,1,2,3,5,8.. * Date:2021/3/19 */ public class Solution { public int fibonacciRecursive(int n) { if (n == 0 || n == 1) { return n; } return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2); } public int fibnoiccIter(int n) { if (n == 0 || n == 1) { return n; } int number_minus_two = 0; int number_minus_one = 1; int rst = 0; for (int i = 2; i <= n; i++) { rst = number_minus_one + number_minus_two; number_minus_two = number_minus_one; number_minus_one = rst; } return rst; } public static void main(String[] args) { Solution s = new Solution(); for (int i = 0; i < 10; i++) { System.out.println(s.fibnoiccIter(i)); } } }
5ab48a985a620776f0e93bc231cd153d074cd42d
28f8a5fc0b0862ce66a52e20001272f226ad2275
/mantis-tests/src/test/java/ru/stqa/pft/mantis/appmanager/ApplicationManager.java
913b3c99ecc8da563db254a9f8ae0ce8714389af
[ "Apache-2.0" ]
permissive
VitalyW/java_pft
fdf8baa591778470b2da726c918bd795005f7ea1
86fa59c10415fbd343f1bd488d666e5f8382e2a5
refs/heads/master
2021-09-06T13:18:53.386643
2018-02-07T00:42:32
2018-02-07T00:42:32
111,644,540
0
0
null
null
null
null
UTF-8
Java
false
false
2,998
java
package ru.stqa.pft.mantis.appmanager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.remote.BrowserType; import org.openqa.selenium.safari.SafariDriver; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Properties; import java.util.concurrent.TimeUnit; public class ApplicationManager { private final Properties properties; private WebDriver wd; private String browser; private RegistrationHelper registrationHelper; private FtpHelper ftp; private MailHelper mailHelper; private JamesHelper jamesHelper; private LoginHelper loginHelper; private PasswordResetHelper passwordResetHelper; private SoapHelper soapHelper; public ApplicationManager(String browser) { this.browser = browser; properties = new Properties(); } public void init() throws IOException { String target = System.getProperty("target", "local"); properties.load(new FileReader(new File(String.format("src/test/resources/%s.properties", target)))); } public void stop() { if (wd != null) { wd.quit(); } } public HttpSession newSession() { return new HttpSession(this); } public String getProperty(String key) { return properties.getProperty(key); } public RegistrationHelper registration() { if (registrationHelper == null) { registrationHelper = new RegistrationHelper(this); } return registrationHelper; } public FtpHelper ftp() { if (ftp == null) { ftp = new FtpHelper(this); } return ftp; } public WebDriver getDriver() { if (wd == null) { if (browser.equals(BrowserType.FIREFOX)) { wd = new FirefoxDriver(); } else if (browser.equals(BrowserType.CHROME)) { wd = new ChromeDriver(); } else if (browser.equals(BrowserType.SAFARI)) { wd = new SafariDriver(); } else if (browser.equals(BrowserType.OPERA)) { wd = new OperaDriver(); } wd.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); wd.get(properties.getProperty("web.baseUrl")); } return wd; } public MailHelper mail() { if (mailHelper == null) { mailHelper = new MailHelper(this); } return mailHelper; } public JamesHelper james() { if (jamesHelper == null) { jamesHelper = new JamesHelper(this); } return jamesHelper; } public LoginHelper login() { if (loginHelper == null) { loginHelper = new LoginHelper(this); } return loginHelper; } public PasswordResetHelper passwordResetHelper() { if (passwordResetHelper == null) { passwordResetHelper = new PasswordResetHelper(this); } return passwordResetHelper; } public SoapHelper soap() { if (soapHelper == null) { soapHelper = new SoapHelper(this); } return soapHelper; } }
3ece48f3945875d42873a830f3e28b5840bf8556
24eec07ef02b903627765be9442a98819c9eccd2
/UnidadUno/EVA1_2_LAYOUTS/app/src/main/java/com/example/mario/eva1_2_layouts/MainActivity.java
6b016e864fc25624858080e7cedad215b84ff11c
[]
no_license
BrandonATDeveloper/SOMoviles
df028eb86150ead49c98114e51c6a768c03f8ca5
59e339e4b580f69d8673b5135787530fac3cfe47
refs/heads/master
2021-08-30T03:41:22.749583
2017-12-15T22:27:28
2017-12-15T22:27:28
105,712,368
0
0
null
null
null
null
UTF-8
Java
false
false
345
java
package com.example.mario.eva1_2_layouts; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
8a48ed1a62c9059b82bd48dc1795ce36f7394e6d
0fcbf88dc40069fa4528b526f1b17eb4452522b2
/Coding Challenges/src/ProjectEuler/CountingSundays.java
9e99e225863da787374ed2416a7b10d2f73eb04d
[]
no_license
ad1992/Coding-Challenges-Collection
599008426d0b766567f030b278ea4bc35c64c3f5
f52753df74ac07605bbe7eae3492f944432cabc3
refs/heads/master
2021-01-10T14:50:12.493542
2015-07-11T07:49:06
2015-07-11T07:49:06
36,575,449
5
2
null
null
null
null
UTF-8
Java
false
false
1,091
java
package ProjectEuler; import java.io.BufferedReader; import java.io.InputStreamReader; /** * @author Aakansha Doshi * */ public class CountingSundays { public static void main(String[] args) { // TODO Auto-generated method stub //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int month[]={31,28,31,30,31,30,31,31,30,31,30,31}; String days[]={"sun","mon","tue","wed","thu","fri","sat"}; int y=1900;int d=0;int first=1;int sun=0; if(checkleap(y)){ month[1]=29; System.out.println("leap"+y); } while(y<=2000) { int day=month[d]; int rem=day%7; while(rem>0) { if(first==6) first=0; else first++; rem--; } //System.out.println(days[first]); if(first==0&&y>=1901) sun++; if(d==11) { y++; if(checkleap(y)){ month[1]=29; } else{ month[1]=28; } d=0; } else{ d++; } } System.out.print(sun); } private static boolean checkleap(int y) { // TODO Auto-generated method stub return((y%100!=0&&y%4==0)||y%400==0); } }
2a00f1956486f09d2e118eb41f4e20aa8a397bda
d8b6881c3e9722efcde977e0c82ab1a699505a8b
/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/OdontoTotal/org/apache/jsp/Cadastro_jsp.java
e6457a77f45e3ecf3bd995c76492985f22ff907d
[]
no_license
evelynsa/OdontoTotal_LP2
d84801fe753eebd904045aa58c73d10b6c7f7d39
510749305ea9803a2dd636ed3e59cf08259b65e6
refs/heads/master
2021-01-03T17:28:52.494006
2020-03-10T11:06:13
2020-03-10T11:06:13
240,169,688
0
0
null
null
null
null
UTF-8
Java
false
false
8,328
java
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/9.0.10 * Generated at: 2020-02-13 02:27:16 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class Cadastro_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent, org.apache.jasper.runtime.JspSourceImports { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private static final java.util.Set<java.lang.String> _jspx_imports_packages; private static final java.util.Set<java.lang.String> _jspx_imports_classes; static { _jspx_imports_packages = new java.util.HashSet<>(); _jspx_imports_packages.add("javax.servlet"); _jspx_imports_packages.add("javax.servlet.http"); _jspx_imports_packages.add("javax.servlet.jsp"); _jspx_imports_classes = null; } private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public java.util.Set<java.lang.String> getPackageImports() { return _jspx_imports_packages; } public java.util.Set<java.lang.String> getClassImports() { return _jspx_imports_classes; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { if (!javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) { final java.lang.String _jspx_method = request.getMethod(); if ("OPTIONS".equals(_jspx_method)) { response.setHeader("Allow","GET, HEAD, POST, OPTIONS"); return; } if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method)) { response.setHeader("Allow","GET, HEAD, POST, OPTIONS"); response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET, POST or HEAD. Jasper also permits OPTIONS"); return; } } final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=ISO-8859-1"); 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; out.write("\r\n"); out.write("<!DOCTYPE html>\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<meta charset=\"UTF-8\" />\r\n"); out.write(" <title>Cadastro</title>\r\n"); out.write(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> \r\n"); out.write(" <link rel=\"stylesheet\" type=\"text/css\" href=\"css/css1.css\" />\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("<img id=\"delicia1\" src=\"ODONTOfundo.png\">\r\n"); out.write(" <div id=\"cadastro\" style=\"margin-top: 5%;margin-left: 10%\">\r\n"); out.write("\r\n"); out.write(" <!--img vspace=\"35px\" hspace=\"15px\"-->\r\n"); out.write(" <center><img id = \"loginha\" align=\"center\" width=\"350\" height=\"150\" src=\"imagens/ODONTOCADASTRO.png\" />\r\n"); out.write("\r\n"); out.write(" \r\n"); out.write(" <h2>Insira seus dados:</h2> </center>\r\n"); out.write(" \r\n"); out.write(" <p> \r\n"); out.write(" <label id =\"cadastrinho\" for=\"nome_cad\">Seu nome:</label>\r\n"); out.write(" <input id=\"cadastrinho1\" name=\"nome_cad\" required=\"required\" type=\"text\" placeholder=\"nome\" />\r\n"); out.write(" </p>\r\n"); out.write(" \r\n"); out.write(" <p> \r\n"); out.write(" <label id =\"cadastrinho\" for=\"email_cad\">Seu e-mail:</label>\r\n"); out.write(" <input id=\"cadastrinho2\" name=\"email_cad\" required=\"required\" type=\"email\" placeholder=\"ex: [email protected]\"/> \r\n"); out.write(" </p>\r\n"); out.write(" \r\n"); out.write(" <p> \r\n"); out.write(" <label id =\"cadastrinho\" for=\"email_cad\">Seu CPF:</label>\r\n"); out.write(" <input id=\"cadastrinho3\" name=\"email_cad\" required=\"required\" type=\"CPF\" placeholder=\"ex: 000.000.000.000.-00\"/> \r\n"); out.write(" </p>\r\n"); out.write("\r\n"); out.write(" <p> \r\n"); out.write(" <label id =\"cadastrinho\" for=\"email_cad\">Seu Telefone:</label>\r\n"); out.write(" <input id=\"cadastrinho4\" name=\"email_cad\" required=\"required\" type=\"Telefone\" placeholder=\"ex: (DDD) 91234-5678\"/> \r\n"); out.write(" </p>\r\n"); out.write("\r\n"); out.write(" <p> \r\n"); out.write(" <label id =\"cadastrinho\" for=\"senha_cad\">Sua senha:</label>\r\n"); out.write(" <input id=\"cadastrinho5\" name=\"senha_cad\" required=\"required\" type=\"password\" placeholder=\"ex. 1234\"/>\r\n"); out.write(" </p>\r\n"); out.write(" \r\n"); out.write(" <p class=\"Cadastrar\"> \r\n"); out.write(" <input id= \"cadastrar\"type=\"submit\" value=\"Cadastrar\"/> \r\n"); out.write(" </p>\r\n"); out.write(" \r\n"); out.write(" <p class=\"link\" style=\"align-content: center\"> \r\n"); out.write(" Já tem conta? \r\n"); out.write(" <a href=\"Login.jsp\"> Ir para Login </a>\r\n"); out.write(" </p>\r\n"); out.write("\r\n"); out.write(" </div>\r\n"); out.write(" </div>\r\n"); out.write(" </div> \r\n"); out.write("</body>\r\n"); out.write("</html>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
9debc28585f4b388473d430bff59f56e39e66812
fdd99c0d0d9bf5d43a14d185e765bc50759fe3ae
/src/com/lianbiao/LinkedList.java
1515e0be49a65bd02119dc6ccca956598fc6e7f8
[]
no_license
hjw95588/Algorithm
b4e786ac168ce899826632246b7cce65914d90b5
2bf1c6459b86f7a295a32571bcef7e28bb411988
refs/heads/master
2021-07-22T16:14:34.506040
2021-07-20T07:01:08
2021-07-20T07:01:08
249,090,255
1
0
null
null
null
null
UTF-8
Java
false
false
4,600
java
package com.lianbiao; //自定义双向链表 public class LinkedList<E> extends AbstractList<E> { private Node<E> first; private Node<E> last; private static class Node<E> { E element; Node<E> prev; Node<E> next; public Node(Node<E> prev,E element, Node<E> next) { this.element = element; this.prev=prev; this.next = next; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (prev != null) { sb.append(prev.element); } else { sb.append("null"); } sb.append("_").append(element).append("_"); if (next != null) { sb.append(next.element); } else { sb.append("null"); } return sb.toString(); } } @Override public void clear() { size = 0; first = null; last = null; } @Override public E get(int index) { /* * 最好:O(1) * 最坏:O(n) * 平均:O(n) */ return node(index).element; } @Override public E set(int index, E element) { /* * 最好:O(1) * 最坏:O(n) * 平均:O(n) */ Node<E> node = node(index); E old = node.element; node.element = element; return old; } @Override public void add(int index, E element) { /* * 最好:O(1) * 最坏:O(n) * 平均:O(n) */ rangeCheckForAdd(index); //往最后添加元素 if(index==size){ Node<E> oldLast=last; Node<E> node=new Node<>(oldLast,element,null);//两根线 if(oldLast==null){ //考虑到刚开始添加节点,前方没节点的情况 first=node; last=node; }else{ //另外两根线 oldLast.next=node; last=node; } }else{ Node<E> next=node(index); Node<E> prev=next.prev; Node<E> node=new Node<>(prev,element,next); next.prev=node; if(prev==null)//index==0 { first=node; }else{ prev.next=node; } } size++; } @Override public E remove(int index) { /* * 最好:O(1) * 最坏:O(n) * 平均:O(n) */ rangeCheck(index); Node<E> node=node(index); Node<E> prev=node.prev; Node<E> next=node.next; //index==0 if(prev==null){ first=next; }else{ prev.next=next; } //index==size-1; if(next==null){ last=prev; }else{ next.prev=prev; } size--; return node.element; } @Override public int indexOf(E element) { if (element == null) { Node<E> node = first; for (int i = 0; i < size; i++) { if (node.element == null) return i; node = node.next; } } else { Node<E> node = first; for (int i = 0; i < size; i++) { if (element.equals(node.element)) return i; node = node.next; } } return ELEMENT_NOT_FOUND; } /** * 获取index位置对应的节点对象 * @param index * @return */ private Node<E> node(int index) { rangeCheck(index); //size>>1 => size/2 if(index<(size>>1)){ Node<E> node = first; for (int i = 0; i < index; i++) { node = node.next; } return node; }else{ Node<E> node = last; for (int i = size-1; i > index; i--) { node = node.prev; } return node; } } @Override public String toString() { StringBuilder string = new StringBuilder(); string.append("size=").append(size).append(", ["); Node<E> node = first; for (int i = 0; i < size; i++) { if (i != 0) { string.append(", "); } string.append(node); node = node.next; } string.append("]"); return string.toString(); } }
c829c6a9f8d786453d9041a84993703aa6a39725
7d28d457ababf1b982f32a66a8896b764efba1e8
/platform-pojo-bl/src/main/java/ua/com/fielden/platform/dir/DirectoryWorker.java
0726886878be333f94845cb7cb3ad0f3861da8a7
[ "MIT" ]
permissive
fieldenms/tg
f742f332343f29387e0cb7a667f6cf163d06d101
f145a85a05582b7f26cc52d531de9835f12a5e2d
refs/heads/develop
2023-08-31T16:10:16.475974
2023-08-30T08:23:18
2023-08-30T08:23:18
20,488,386
17
9
MIT
2023-09-14T17:07:35
2014-06-04T15:09:44
JavaScript
UTF-8
Java
false
false
2,344
java
package ua.com.fielden.platform.dir; import static java.lang.String.format; import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import org.apache.log4j.Logger; import ua.com.fielden.platform.dir.exceptions.LdapException; /** * A class that contains a common JNDI operations extensions. * * @author TG Team * */ public class DirectoryWorker { private static final Logger logger = Logger.getLogger(DirectoryWorker.class); private DirectoryWorker() {} /** * Connects to appropriate LDAP server database with provided master credentials and retrieves working directory context, that later could be used for search/modify/etc. * operations. * * @param server * - a server name or its IP address * @param port * - a port for LDAP server, typically 389. * @param base * - a base for which a dir context will be created (e.g. ou=TG Users,ou=Users,dc=example,dc=com) * @param username * - an username of some user with an appropriate privileges (e.g. "[email protected]" or "cn=JHOU,ou=TG Users,ou=Users,dc=example,dc=com") * @param password * - a password for some user with an appropriate privileges * @return * @throws NamingException */ public static DirContext ldapConnect(final String server, final String port, final String base, final String username, final String password) { final Hashtable<String, String> env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port + "/" + base); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, username); env.put(Context.SECURITY_CREDENTIALS, password); try { return new InitialDirContext(env); } catch (final Exception ex) { final String msg = format("Could not connect to LDAP server [%s] via port [%s] for base [%s] with master user [%s].", server, port, base, username); logger.error(msg, ex); throw new LdapException(msg, ex); } } }
a7247661c12a87fd2611eef1c2c7ee95793ef071
658677ea4f84849c01bee621994ff59259d95091
/src/botdiscord/Main.java
d1dd4c569cf9392b1280d35173e6202505b8a0ee
[]
no_license
Leocarmacedo/bot
2b12efe3c30e8abede649398856d4a5bf259978f
67a593993eec9ca25abf8a5d5778a19a6d0e25c4
refs/heads/master
2023-07-29T07:43:38.672061
2021-09-13T21:48:59
2021-09-13T21:48:59
406,102,180
0
0
null
null
null
null
UTF-8
Java
false
false
576
java
package botdiscord; import javax.security.auth.login.LoginException; import commands.Commands; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.entities.Activity; public class Main { public static JDA jda; public static String prefix = "-"; public static void main(String[] args) throws LoginException { jda = JDABuilder.createDefault("ODgxNjg5MDc3ODQ4NjI5MzQ5.YSwe8Q.17wkmBQbFjNLmkAj1bz-eoMr318").build(); jda.getPresence().setActivity(Activity.watching("Chaves")); jda.addEventListener(new Commands()); } }
01cd9c7de4ed659cac0ae8857df8655bb13bb21f
470d01631a73360bd4fb193bc698b6a45a44ffaf
/maven/src/test/java/demo/tests/GoogleThucydidesDriverIT.java
2ccb84f4d39ec468188fd418c8b536e18938cc2e
[ "MIT" ]
permissive
hypery2k/thucydides_sample
6e90991958b3149a892c85bf7e8bfcab55ac078f
e1587221a8343d7917a4bc0486bbef283eeb8f89
refs/heads/master
2023-05-03T13:37:25.388688
2014-10-22T09:15:27
2014-10-22T09:15:27
23,637,134
0
0
MIT
2023-04-16T19:10:16
2014-09-03T20:54:38
Java
UTF-8
Java
false
false
1,696
java
package demo.tests; import net.thucydides.core.annotations.Managed; import net.thucydides.junit.runners.ThucydidesRunner; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; @RunWith(ThucydidesRunner.class) public class GoogleThucydidesDriverIT { @Managed public WebDriver webdriver; @Test public void googleSearchTest() { // And now use this to visit Google webdriver.get("http://www.google.com"); // Find the text input element by its name WebElement element = webdriver.findElement(By.name("q")); // Enter something to search for element.sendKeys("Cheese!"); // Now submit the form. WebDriver will find the form for us from the element element.submit(); // Check the title of the page System.out.println("Page title is: " + webdriver.getTitle()); } public static void LegazyWebDriverTest(String[] args) { // Create a new instance of the html unit driver // Notice that the remainder of the code relies on the interface, // not the implementation. WebDriver driver = new HtmlUnitDriver(); // And now use this to visit Google driver.get("http://www.google.com"); // Find the text input element by its name WebElement element = driver.findElement(By.name("q")); // Enter something to search for element.sendKeys("Cheese!"); // Now submit the form. WebDriver will find the form for us from the element element.submit(); // Check the title of the page System.out.println("Page title is: " + driver.getTitle()); driver.quit(); } }
433ca2a12c50a74eae5abcead794a2595ed5f6a6
cd089e025c1598aa203dbf8dc95a52c2bb71eaeb
/tomp_ref/src/main/java/org/tomp/api/planning/BasePlanningProvider.java
eb1af53504ebabe96ca36a1604847e827651a073
[ "Apache-2.0" ]
permissive
maas-alliance/TOMP-REF
8875d2fe8823b46df39a56c74eeee078668cf0e8
31dd232602e4bd20520cbda828e3ccaa83344d82
refs/heads/master
2022-09-22T01:04:50.292610
2020-05-27T07:40:38
2020-05-27T07:40:38
267,531,321
1
1
Apache-2.0
2020-05-28T08:09:52
2020-05-28T08:09:51
null
UTF-8
Java
false
false
3,150
java
package org.tomp.api.planning; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tomp.api.configuration.ExternalConfiguration; import org.tomp.api.repository.DummyRepository; import org.tomp.api.utils.ObjectFromFileProvider; import io.swagger.model.Condition; import io.swagger.model.Coordinates; import io.swagger.model.Fare; import io.swagger.model.OptionsLeg; import io.swagger.model.PlanningCheck; import io.swagger.model.PlanningOptions; import io.swagger.model.PlanningResult; import io.swagger.model.SimpleLeg; import io.swagger.model.TypeOfAsset; public abstract class BasePlanningProvider implements PlanningProvider { private static final Logger log = LoggerFactory.getLogger(BasePlanningProvider.class); protected Coordinates from; protected Coordinates to; protected BigDecimal start; protected BigDecimal end; protected DummyRepository repository; protected ExternalConfiguration configuration; public BasePlanningProvider(DummyRepository repository, ExternalConfiguration configuration) { this.repository = repository; this.configuration = configuration; } public PlanningOptions getOptions(@Valid PlanningCheck body, String acceptLanguage) { log.info("Request for options"); boolean provideIds = body.isProvideIds() != null && body.isProvideIds().booleanValue(); PlanningOptions options = new PlanningOptions(); options.setConditions(getConditions(acceptLanguage)); from = body.getFrom(); to = body.getTo(); start = body.getStartTime(); end = body.getEndTime(); options.setResults(getResults(body)); if (provideIds) { repository.saveOptions(options); } else { log.info("Forget this one"); } return options; } protected List<Condition> getConditions(String acceptLanguage) { ObjectFromFileProvider<Condition[]> conditionFileProvider = new ObjectFromFileProvider<>(); Condition[] conditions = conditionFileProvider.getObject(acceptLanguage, Condition[].class, configuration.getConditionFile()); List<Condition> conditionList = new ArrayList<>(); for (Condition c : conditions) { conditionList.add(c); } return conditionList; } protected ArrayList<PlanningResult> getResults(@Valid PlanningCheck body) { boolean provideIds = body.isProvideIds() != null && body.isProvideIds().booleanValue(); ArrayList<PlanningResult> arrayList = new ArrayList<>(); SimpleLeg result = new SimpleLeg(); result.setTypeOfAsset(getAssetType()); result.setLeg(getLeg()); result.setPricing(getFare()); result.setConditions(getConditionsForLeg(result)); if (provideIds) { log.info("We have to take a closer look. Can we more or less guarantee that we can fulfill this request?"); result.setId(UUID.randomUUID().toString()); } arrayList.add(result); return arrayList; } protected List<String> getConditionsForLeg(SimpleLeg result) { return new ArrayList<>(); } protected abstract Fare getFare(); protected abstract OptionsLeg getLeg(); protected abstract TypeOfAsset getAssetType(); }
8301b68d1563e4c3941a82191698350063951df4
34b6199372628ff59a31810b3e5a1f2e0130bb6d
/src/main/java/com/xm4399/util/FlinkRestApiUtil.java
50f2aa312fddb302f1bc51fd0b950ec8f19e48fe
[]
no_license
7970691/flink_realtime_kuduTableName
cad3b9bcd8ebeea11729571ca62e3764fb85d099
c8f2f0f524875031506f0f796b75b8c2f87dee10
refs/heads/master
2022-12-26T20:42:21.419555
2020-10-13T06:08:55
2020-10-13T06:08:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,137
java
package com.xm4399.util; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.IOException; import java.util.LinkedList; /** * @Auther: czk * @Date: 2020/9/30 * @Description: */ public class FlinkRestApiUtil { // cancal flink job public void cancalFlinkJob(String jid) { CloseableHttpClient httpClient = HttpClients.createDefault(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String yarnWebIP = new ConfUtil().getValue("yarnWebIP"); String yarnSessionID = new ConfUtil().getValue("yarnSessionAppID"); try { httpClient = HttpClients.createDefault(); String url = "http://" + yarnWebIP + "/proxy/" + yarnSessionID + "/jobs/" + jid + "/yarn-cancel"; HttpGet httpGet = new HttpGet(url); httpClient.execute(httpGet, responseHandler); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // 获取 flinkJob的一个信息 如state,jid等 public String getFlinkJobOneInfo(String flinkJobName, String oneInfo) { String oneFlinkJobInfo = null; CloseableHttpClient httpClient = HttpClients.createDefault(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String yarnWebIP = new ConfUtil().getValue("yarnWebIP"); String yarnSessionID = new ConfUtil().getValue("yarnSessionAppID"); try { httpClient = HttpClients.createDefault(); String url = "http://" + yarnWebIP + "/proxy/" + yarnSessionID + "/jobs/overview"; //获取yarn session状态 HttpGet httpGet = new HttpGet(url); String returnValue = httpClient.execute(httpGet, responseHandler); //调接口获取返回值时,必须用此方法 JSONObject jsonObject = JSONObject.parseObject(returnValue); JSONArray jobs = jsonObject.getJSONArray("jobs"); int len = jobs.size(); for (int i = 0; i < len; i++) { JSONObject job = jobs.getJSONObject(i); if (flinkJobName.equals(job.getString("name")) && "RUNNING".equals(job.getString("state"))) { oneFlinkJobInfo = job.getString(oneInfo); return oneFlinkJobInfo; } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return oneFlinkJobInfo; } // 获取flinkjob最后的checkpoint 路径 public String getCheckPointPath(String flinkJobID) { LinkedList<String> yarnRunningJobNameList = new LinkedList<String>(); CloseableHttpClient httpClient = HttpClients.createDefault(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String yarnWebIP = new ConfUtil().getValue("yarnWebIP"); String yarnSessionID = new ConfUtil().getValue("yarnSessionAppID"); try { httpClient = HttpClients.createDefault(); String url = "http://" + yarnWebIP + "/proxy/" + yarnSessionID + "/jobs/" + flinkJobID + "/checkpoints"; //获取yarn session状态 HttpGet httpGet = new HttpGet(url); String returnValue = httpClient.execute(httpGet, responseHandler); JSONObject jsonObject = JSONObject.parseObject(returnValue); int completedCounts = Integer.parseInt(jsonObject.getJSONObject("counts").getString("completed")); String checkPointPath = null; if (completedCounts > 0 ){ checkPointPath = jsonObject.getJSONObject("latest").getJSONObject("completed").getString("external_path"); }else if (completedCounts == 0){ checkPointPath = "unfinished checkpoint, no checkpoint path "; } return checkPointPath; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } }
0765c4944406f119ac88194d117828de7bbfadef
5741045375dcbbafcf7288d65a11c44de2e56484
/reddit-decompilada/com/google/android/gms/internal/zzdp.java
f88376ff23bda86ecf1d93957e77e8993323bda5
[]
no_license
miarevalo10/ReporteReddit
18dd19bcec46c42ff933bb330ba65280615c281c
a0db5538e85e9a081bf268cb1590f0eeb113ed77
refs/heads/master
2020-03-16T17:42:34.840154
2018-05-11T10:16:04
2018-05-11T10:16:04
132,843,706
0
0
null
null
null
null
UTF-8
Java
false
false
323
java
package com.google.android.gms.internal; final class zzdp implements Runnable { private /* synthetic */ zzdm f7238a; zzdp(zzdm com_google_android_gms_internal_zzdm) { this.f7238a = com_google_android_gms_internal_zzdm; } public final void run() { zznh.m6490a(this.f7238a.f7216a); } }
604e59d27d6e23db827aa85854a8f6ca76f80c26
48ab7d6ae5ac74e369081055c2c40918c2d0e9b2
/src/me/frostythedev/bowwarfare/utils/NumberUtil.java
62f21bfab279766af77d93ae75317e079954c8ea
[]
no_license
frostythedev/BowWarfare
39db2ad1a8baf776fb8e8503eda869504cbe887f
a138075cc65e0f11647b93dcb8fb59df9ec79787
refs/heads/master
2022-01-18T19:09:51.153408
2019-05-16T18:24:10
2019-05-16T18:24:10
63,385,565
0
0
null
null
null
null
UTF-8
Java
false
false
1,512
java
package me.frostythedev.bowwarfare.utils; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.Random; public class NumberUtil { private static Random random = new Random(); private static DecimalFormat format = new DecimalFormat(); static { format.setRoundingMode(RoundingMode.CEILING); } public static int getRandomInRange(int min, int max) { return random.nextInt((max - min) + 1) + min; } public static double getRandomInRange(double min, double max) { double range = max - min; double scaled = random.nextDouble() * range; double shifted = scaled + min; return shifted; // == (rand.nextDouble() * (max-min)) + min; } public static double round(double num, int decimalPlaces) { StringBuilder formatString = new StringBuilder("#."); for (int i = 0; i < decimalPlaces; i++) { formatString.append("#"); } format.applyPattern(formatString.toString()); return Double.parseDouble(format.format(num)); } public static boolean percentCheck(int percent) { return random.nextInt(101) <= percent; } public static boolean percentCheck(double percent) { return random.nextInt(101) <= percent; } public static float percentOf(int num, int target) { return num * 100.0f / target; } public static boolean isInRange(int num, int min, int max) { return num >= min && num <= max; } }
522c413879bbcdc2cd0ed175894d0a81f5cd2a29
69e9bfa754cd5efb58d140b7a69b27756068dd8a
/experiments/src/main/java/twitter/recommendations/content/models/ContentVectorModel.java
4d5464f918f1a821f3b599e20aa92ad667030cb1
[]
no_license
efikarra/text-models-twitter
056c06403c07b9015e5607126c3ef7fe97eb9a0e
d939f0e81ea18581c6b7ffc86de1f359d192f2d0
refs/heads/master
2021-01-13T12:28:52.841379
2016-11-02T08:18:07
2016-11-02T08:18:07
72,595,589
1
0
null
null
null
null
UTF-8
Java
false
false
412
java
package twitter.recommendations.content.models; import Models.VectorModel; import twitter.modelUtilities.ModelInfoSource; public abstract class ContentVectorModel extends ContentAbstractModel{ public ContentVectorModel(VectorModel model,ModelInfoSource utype) { super(model,utype); } public abstract void finalizeModel(); @Override public void updateModel(String text) { model.updateModel(text); } }
6ce7bcb37717e011bfca7f5ff4e16a1314d7e288
e7568f8008adf091d6a6c7057106503d2db5d4bd
/.svn/pristine/78/78ced6ea7d66f8527518ae4971066d4e95f03ae1.svn-base
8e75c131e567054d8fff41b710091b41ae6a94a1
[]
no_license
HurryUpWb/HLAdm
31eb45eaf253a6588e4967bd30f460274b7f7e03
6f8dd88cc8c8766c3fcff78c50c06eaea525459f
refs/heads/master
2021-01-01T04:35:52.150372
2017-07-14T06:36:36
2017-07-14T06:36:36
97,201,120
0
0
null
null
null
null
UTF-8
Java
false
false
356
package com.auis.auib.admin.vo; public class SessionVo { private String userId; private String userName; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
92a209ba57254cca527a310de7803442ac4ced91
86fb8bdac36bdbf06c44e0167331fbff9a25e777
/practical/src/Hospital/doctor.java
c9e124f11f756cf9db7cd6221962eb3f7d853ccb
[]
no_license
YosefAhmed/Play-Code
e1fa4884087f7934ec8dfe10040dee0faafa62e0
626456fce06638d0db23ef508d37b5cccd61d0b1
refs/heads/master
2021-06-24T04:51:38.805176
2021-01-18T16:14:24
2021-01-18T16:14:24
182,417,881
0
1
null
null
null
null
UTF-8
Java
false
false
938
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 Hospital; import java.util.ArrayList; /** * * @author Yousef */ public class doctor extends person { private String Specialization; private ArrayList<patient> Patients=new ArrayList<patient>(); public void getPatients() { for(patient p: Patients){ p.Display_Info(); } } public void setPatients(patient Patient) { this.Patients.add(Patient); } public doctor(String Name, String Specialization) { super(Name); this.Specialization=Specialization; } @Override public void Display_Info(){ super.Display_Info(); System.out.println("Doctor Specialization is: "+Specialization); getPatients(); } }
e327a08924bf7b1995555a95d6bc9f48e4ecef3f
670d1de143b975f886fb7865ae1d17476c6e7961
/src/main/java/seedu/address/logic/parser/ViewClassCommandParser.java
c621d2896c7ed04729be59d780a80bb38b864e04
[ "MIT" ]
permissive
Leofeng10/tp
9a67aa9a6b7ab3ffb0140f40625d8186574a2b0a
0de7a56db14298cbd23c0bc844eeaa587a5ebe7e
refs/heads/master
2023-08-29T09:48:30.841241
2021-11-07T14:24:43
2021-11-07T14:24:43
406,382,379
0
0
NOASSERTION
2021-10-10T11:53:55
2021-09-14T13:39:36
Java
UTF-8
Java
false
false
1,073
java
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.ViewClassCommand; import seedu.address.logic.parser.exceptions.ParseException; /** * Parses input arguments and creates a new ViewClassCommand object */ public class ViewClassCommandParser implements Parser<ViewClassCommand> { /** * Parses the given {@code String} of arguments in the context of the ViewClassCommand * and returns a ViewClassCommand object for execution. * @throws ParseException if the user input does not conform the expected format */ public ViewClassCommand parse(String args) throws ParseException { try { Index index = ParserUtil.parseIndex(args); return new ViewClassCommand(index); } catch (ParseException pe) { throw new ParseException( String.format(MESSAGE_INVALID_COMMAND_FORMAT, ViewClassCommand.MESSAGE_USAGE), pe); } } }
6fabec27e522761917e4c2f1ab55071a8a496d31
f962307203e8eb92bdce3070b8b19fec03faaf8e
/analiseGenoma/src/main/java/org/analiseGenoma/managedbean/VfImpact.java
581d4dac8729739de70b8205a33a352a356377ae
[]
no_license
marcelogomesrp/analiseGenoma
39a8bcc58149849520fc77c15a81131545caec9d
23c4a83dd147d51bbe48c0cb5f4a7e3a3a7334ac
refs/heads/master
2018-10-17T00:25:33.859750
2018-10-11T08:39:04
2018-10-11T08:39:04
113,789,525
0
0
null
null
null
null
UTF-8
Java
false
false
3,530
java
package org.analiseGenoma.managedbean; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import org.analiseGenoma.managedbean.util.FacesUtil; import org.analiseGenoma.model.Analise; import org.analiseGenoma.model.Filtro; import org.analiseGenoma.model.Impact; import org.analiseGenoma.model.VcfMetadata; import org.analiseGenoma.service.AnaliseService; import org.analiseGenoma.service.FiltroService; import org.analiseGenoma.service.ImpactService; import org.analiseGenoma.service.VcfMetadataService; import org.analiseGenoma.sessionbean.AnaliseSB; import org.analiseGenoma.sessionbean.FilterSB; import org.primefaces.context.RequestContext; import org.primefaces.model.DualListModel; @Named(value = "VfImpact") @RequestScoped public class VfImpact { private DualListModel<String> list; private Long idAnalise; private VcfMetadata vcfMetadata; private Filtro filtro; @Inject private AnaliseService analiseService; @Inject private VcfMetadataService vcfMetadataService; @Inject private FiltroService filtroService; @Inject private AnaliseSB analiseSB; @Inject private FilterSB filterSB; @Inject private ImpactService impactService; @PostConstruct public void init() { idAnalise = (Long) FacesUtil.getSessionMapValue("id"); if (idAnalise != null) { Analise analise = analiseSB.getAnalise(); filtro = filterSB.getFilter(); vcfMetadata = vcfMetadataService.findByVcfId(analise.getVcf().getId()); List<String> target = filtro.getImpacts().stream().map(u -> u.getName()).collect(Collectors.toList()); List<String> source = vcfMetadata.getImpacts().stream().map(u -> u.getName()).filter(u -> !target.contains(u)).collect(Collectors.toList()); list = new DualListModel<>(source, target ); } } public void closeView(){ this.updateFiltro(); filtroService.merge(filtro); RequestContext.getCurrentInstance().closeDialog("Filtro aplicado com sucesso"); ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); try { ec.redirect(((HttpServletRequest) ec.getRequest()).getRequestURI()); } catch (IOException ex) { Logger.getLogger(AnaliseSelecionarVarianteMB.class.getName()).log(Level.SEVERE, null, ex); } } public DualListModel<String> getList() { return list; } public void setList(DualListModel<String> list) { this.list = list; } public Long getValue() { return idAnalise; } public void setValue(Long value) { this.idAnalise = value; } private void updateFiltro() { Set<Impact> listFilter = new HashSet<>(); for(String name: list.getTarget()){ List<Impact> find = impactService.findByName(name); //effectService.findByName(name); if(find.size() == 1) listFilter.add(find.get(0)); } filtro.setImpacts(listFilter); } }
[ "marcelo@jaddyPC" ]
marcelo@jaddyPC
a70ae2883dd899b8783c7d4ace95e8cc22fc27dd
5bf57ea50b471fca345cda4ccc6793665bc0838e
/src/main/java/com/wsj/wsj/base/entity/JsonResult.java
0c2adc9c6b554fd13828ac812e4eaaf47d75ea19
[]
no_license
wsj1104940621/Online-Compiler
fd3844cf9eb45a4ac20299975805f8b4f6806e7b
129ce58c7ace16f0cce934a97ce8ba30b99be81a
refs/heads/master
2020-08-23T04:59:15.838840
2019-10-24T07:13:08
2019-10-24T07:13:08
216,548,883
0
0
null
null
null
null
UTF-8
Java
false
false
400
java
package com.wsj.wsj.base.entity; public class JsonResult { private String success; private String error; public String getSuccess() { return success; } public void setSuccess(String success) { this.success = success; } public String getError() { return error; } public void setError(String error) { this.error = error; } }
29686ca754cb9b634a0fa4bfff63c528576a2366
12a6c64433636dbdc2ed62333ac81d0843073305
/src/main/java/org/saikrishna/apps/scanner/task/utils/Chunks.java
c8e967e4f1f4d0d75016787a43db5d56e2c5aa8f
[]
no_license
saikrir/Netscanner
f94465764946aabe0d26d3301754616ce063aa2d
24d753e2586ebc361c11c88d9c97a036c56f979a
refs/heads/master
2021-05-07T02:24:08.349680
2017-11-18T15:29:10
2017-11-18T15:29:10
110,558,292
0
0
null
null
null
null
UTF-8
Java
false
false
1,672
java
package org.saikrishna.apps.scanner.task.utils; import org.saikrishna.apps.model.ChunkBounds; import java.util.Iterator; public class Chunks implements Iterable<ChunkBounds>{ private int chunkSize; private int taskCount; public Chunks(int chunkSize, int taskCount) { this.chunkSize = chunkSize; this.taskCount = taskCount; } @Override public Iterator<ChunkBounds> iterator() { return new ChunkIterator(this.chunkSize, this.taskCount); } static class ChunkIterator implements Iterator<ChunkBounds> { private int chunkSize; private double numChunks; private int index; private int taskCount; public ChunkIterator(int chunkSize, int taskCount) { this.index = 0; this.chunkSize = chunkSize; this.numChunks = Math.ceil((float)taskCount / chunkSize); this.taskCount = taskCount; } @Override public boolean hasNext() { return this.index < this.numChunks; } @Override public ChunkBounds next() { int startIndex = getStartIndex(); int endIndex = getEndIndex(); this.index++; return new ChunkBounds(startIndex, endIndex); } protected int getStartIndex() { return this.index * this.chunkSize; } protected int getEndIndex() { int endIndex = getStartIndex() + this.chunkSize; if(endIndex > taskCount) { endIndex = getStartIndex() + (taskCount - getStartIndex()); } return endIndex; } } }
ba555848c7835a5ab071fa6fb2315a3a7b83182e
0f92bc0293ca43346a75a5f824f254e37ffa5977
/Java/Euler_13.java
c5b3af1d2202d78f502873ccb1a5643284f179f2
[]
no_license
aftabn/ProjectEuler
fee91de01a379c8f88035c9bca6d5486c510053d
0f2db3d4a6ab0c04fdbcac431bdd542a11c3f025
refs/heads/master
2016-09-05T23:51:19.097147
2016-01-05T04:27:50
2016-01-05T04:27:50
33,051,753
0
0
null
null
null
null
UTF-8
Java
false
false
760
java
import java.util.*; import java.io.*; import java.math.*; public class Euler_13 { public static void main (String args[]) { String line = null; BigInteger sum = BigInteger.ZERO; try { FileReader input = new FileReader("Euler_13_Number.txt"); BufferedReader br = new BufferedReader(input); while((line = br.readLine()) != null) sum = sum.add(new BigInteger(line)); br.close(); } catch(FileNotFoundException ex) { System.out.println("Unable to open file 'Euler_13_Number.txt'"); } catch(IOException ex) { System.out.println("Error reading file 'Euler_13_Number.txt'"); } System.out.println(sum); } }
8abedd058d2fa9954d660f6d68583b2ba3d9eda0
6a876694dc5276b9cc41e43c3445a5e792766c57
/src/main/java/org/two/two/exercises/Exercise6.java
ee3d37fa10f015ca1e33fa86a315b7a53ec93ffd
[]
no_license
zchengi/Algorithm
9bcfdefdf5d8852be624d49ffb82fa3f0190d5f4
7276aed9934147acc02a52ac06fd83bd85822deb
refs/heads/master
2021-09-18T15:20:26.974991
2018-07-16T09:24:21
2018-07-16T09:24:21
107,095,799
0
0
null
2017-10-17T03:31:08
2017-10-16T07:54:51
Java
UTF-8
Java
false
false
2,808
java
package org.two.two.exercises; import edu.princeton.cs.algs4.StdDraw; import edu.princeton.cs.algs4.StdRandom; import org.two.one.learn.Template; /** * 2.2.6 编写一个程序来计算自顶向下和自底向上的归并排序访问数组的准确次数。 * 使用这个程序将N=1至512的结果绘成曲线图,并将其和上限6NlgN比较。 * * @author cheng * 2018/1/17 19:34 */ public class Exercise6 extends Template { /** * 访问数组的次数 */ private static int count = 0; private static Comparable[] aux; public static void sort(Comparable[] a) { aux = new Comparable[a.length]; sort(a, 0, a.length - 1); } /** * 自顶向下 */ private static void sort(Comparable[] a, int lo, int hi) { if (hi <= lo) return; int mid = lo + (hi - lo) / 2; sort(a, lo, mid); sort(a, mid + 1, hi); merge(a, lo, mid, hi); } /** * 自底向上 */ private static void sort2(Comparable[] a) { int n = a.length; aux = new Comparable[n]; for (int sz = 1; sz < n; sz += sz) { for (int lo = 0; lo + sz < n; lo += sz + sz) { merge(a, lo, lo + sz - 1, Math.min(lo + sz + sz - 1, n - 1)); } } } private static void merge(Comparable[] a, int lo, int mid, int hi) { int i = lo; int j = mid + 1; for (int k = lo; k <= hi; k++) { aux[k] = a[k]; count++; } for (int k = lo; k <= hi; k++) { if (i > mid) a[k] = aux[j++]; else if (j > hi) a[k] = aux[i++]; else if (less(aux[i], aux[j])) a[k] = aux[i++]; else a[k] = aux[j++]; count++; } } public static void main(String[] args) { StdDraw.setScale(0, 512); StdDraw.setYscale(-5, 20000); double lastC1 = 0, lastC2 = 0; for (int i = 1; i <= 512; i++) { int n = i; Integer[] a = new Integer[n]; for (int j = 0; j < n; j++) { a[j] = j; } StdRandom.shuffle(a); Integer[] b = a.clone(); Exercise6 ex = new Exercise6(); ex.sort(a); int c1 = ex.count; ex.count = 0; ex.sort2(a); int c2 = ex.count; StdDraw.setPenColor(StdDraw.RED); StdDraw.line((i - 1), lastC1, i, c1); StdDraw.setPenColor(StdDraw.BLUE); StdDraw.line((i - 1), lastC2, i, c2); StdDraw.setPenColor(StdDraw.GREEN); // 访问上限N*log(N) StdDraw.line((i-1),6*(n-1)*Math.log(n-1),i,6*n*Math.log(n)); lastC1 = c1; lastC2 = c2; } } }
53c324bf74c291d063bd4e620b0989477f1ed939
69db466b12bf8152ed146178a99b3edc909b15a9
/tinyos.dlrc.parser.nesc12/src/tinyos/dlrc/nesc12/collector/actions/Action276.java
b74d46e4d04f3e3ac6366ec9dc3bd9a2a4a8e482
[]
no_license
mahmoudimus/dlrc-tinyos-plugin
788a575a3cc909b049d4b5b9da9d6370a50eccc9
9e1c6e495f7ac15966a1463f66700f7f4b619381
refs/heads/master
2021-05-29T09:52:46.507638
2013-08-22T08:11:57
2013-08-22T08:11:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,634
java
/* * Dlrc 2, NesC development in Eclipse. * Copyright (C) 2009 DLRC * * 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/>. * * Web: http://tos-ide.ethz.ch * Mail: [email protected] */ package tinyos.dlrc.nesc12.collector.actions; import tinyos.dlrc.nesc12.parser.StringRepository; import tinyos.dlrc.nesc12.parser.ScopeStack; import tinyos.dlrc.nesc12.parser.RawParser; import tinyos.dlrc.nesc12.lexer.Token; import tinyos.dlrc.nesc12.lexer.Lexer; import tinyos.dlrc.nesc12.parser.ast.*; import tinyos.dlrc.nesc12.parser.ast.nodes.*; import tinyos.dlrc.nesc12.parser.ast.nodes.declaration.*; import tinyos.dlrc.nesc12.parser.ast.nodes.definition.*; import tinyos.dlrc.nesc12.parser.ast.nodes.error.*; import tinyos.dlrc.nesc12.parser.ast.nodes.expression.*; import tinyos.dlrc.nesc12.parser.ast.nodes.general.*; import tinyos.dlrc.nesc12.parser.ast.nodes.nesc.*; import tinyos.dlrc.nesc12.parser.ast.nodes.statement.*; import tinyos.dlrc.nesc12.collector.*; public final class Action276 implements ParserAction{ public final java_cup.runtime.Symbol do_action( int CUP$parser$act_num, java_cup.runtime.lr_parser CUP$parser$parser, java.util.Stack CUP$parser$stack, int CUP$parser$top, parser parser) throws java.lang.Exception{ java_cup.runtime.Symbol CUP$parser$result; // n_interface_head_parameters ::= n_interface_head n_attributes_no_init { Interface RESULT =null; Interface h = (Interface)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; AttributeList a = (AttributeList)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; RESULT = h; h.setAttributes( a ); CUP$parser$result = parser.getSymbolFactory().newSymbol("n_interface_head_parameters",141, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); } return CUP$parser$result; } }
[ "heavey@heavey-ThinkPad-T420.(none)" ]
heavey@heavey-ThinkPad-T420.(none)
02e2701372ae4def933046b9f0de58aaf0886c24
f673badd5600966c3b777f8b708a6cf27755c267
/src/main/java/handler/ReadMessage.java
90ae7ff3c949f87f9bcecd5a362010cc3a96416c
[]
no_license
magictext/snat-server
df48d96353a28eb498af985a06878232b3f1e595
a65873242e6e9e6af874029f657e166b9b0e332e
refs/heads/master
2022-11-21T12:21:50.568748
2020-01-10T08:46:36
2020-01-10T08:46:36
230,708,239
1
0
null
2022-11-16T10:32:01
2019-12-29T05:41:25
Java
UTF-8
Java
false
false
6,066
java
package handler; import java.util.HashMap; import config.ClientConfig; import config.ConfigEntity; import exception.RangePortException; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.bidimap.DualHashBidiMap; import org.apache.log4j.Logger; import runner.TcpToClient; import runner.UdpToClient; import util.Data; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import map.ServerChannelMap; import map.ServerProxyMap; import util.Mapper; import util.RangePort; import util.Type; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; //此处理器用于服务器接收客户端代理的信息并进行转发 public class ReadMessage extends SimpleChannelInboundHandler<Data> { private static EventLoopGroup bossGroup = new NioEventLoopGroup(); private static EventLoopGroup workerGroup = new NioEventLoopGroup(); //此客户端对应的连接信息 HashMap<Integer,Channel> port = new HashMap<>(); //发生错误的端口号列表 List<Integer> list = new ArrayList<>(); @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { super.channelRegistered(ctx); Logger.getLogger(this.getClass()).debug("received an connection"); //服务端接收用户代理连接并记录下对应端口和channel // Channel channel = ctx.channel(); // InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.localAddress(); // int port=inetSocketAddress.getPort(); // ServerProxyMap.serverProxyMap.put(port, ctx.channel()); } private void configureTCP(ConfigEntity entity, ChannelHandlerContext ctx) throws RangePortException { BidiMap bidiMap = ((BidiMap) RangePort.getRangePort(entity.getLocalServer(), entity.getPort(), entity.getRemotePort())).inverseBidiMap(); //加入总表中 for (Object o : bidiMap.keySet()) { int serverport= (Integer)o; if (ServerProxyMap.serverProxyMap.containsKey(serverport)==true) { list.add(serverport); } else { ServerProxyMap.serverProxyMap.put(serverport,ctx.channel()); //开启serverSocket new Thread(new TcpToClient((Integer) o,bossGroup, workerGroup,port),this.getClass().getName()+o).start(); } } } private void configureUDP(ConfigEntity entity, ChannelHandlerContext ctx) throws RangePortException { BidiMap bidiMap = ((BidiMap) RangePort.getRangePort(entity.getLocalServer(), entity.getPort(), entity.getRemotePort())).inverseBidiMap(); port.putAll(bidiMap); //加入总表中 for (Object o : bidiMap.keySet()) { int serverport= (Integer)o; if (ServerProxyMap.serverProxyMap.containsKey(serverport)==true) { list.add(serverport); } else { ServerProxyMap.serverProxyMap.put(serverport,ctx.channel()); //开启serverSocket new Thread(new UdpToClient((Integer) o, workerGroup,port),this.getClass().getName()+o).start(); } } } private void configureSUDP(ConfigEntity entity, ChannelHandlerContext ctx) { } private void configureServerForNewClient(ClientConfig config, ChannelHandlerContext ctx) throws RangePortException { for (ConfigEntity entity : config.getList()) { switch (entity.getName()){ case "tcp": configureTCP(entity, ctx); break; case "udp": configureUDP(entity, ctx); break; case "sudp": configureSUDP(entity, ctx); break; } if(list.size()!=0){ ctx.channel().writeAndFlush(new Data().setType(Type.portBindsError).setB(Mapper.getJsonByte(list))); } } } @Override protected void channelRead0(ChannelHandlerContext ctx, Data msg) throws Exception { Logger.getLogger(this.getClass()).debug(msg); switch (msg.type){ case 1: ClientConfig config = Mapper.parseObject(msg.getB(), ClientConfig.class); Logger.getLogger(this.getClass()).debug("received config: "+config); configureServerForNewClient(config,ctx); break; case 200: case 201: Channel channel = ServerChannelMap.serverChannelMap.get(msg.session); //由于此channel没有绑定编码器 理论上会直接输出。 channel.writeAndFlush(msg.getB()); break; } } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { for (Integer key : port.keySet()) { Channel channel = port.get(key); ServerProxyMap.serverProxyMap.remove(key); Logger.getLogger(this.getClass()).debug(ServerProxyMap.serverProxyMap.toString()); channel.close(); Logger.getLogger(this.getClass()).debug(key+" has free"); } port.clear(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof IOException){ for (Integer key : port.keySet()) { Channel channel = port.get(key); ServerProxyMap.serverProxyMap.remove(key); Logger.getLogger(this.getClass()).debug(ServerProxyMap.serverProxyMap.toString()); channel.close(); Logger.getLogger(this.getClass()).debug(key+" has free"); } port.clear(); return; } Logger.getLogger(this.getClass()).warn(cause.getMessage(), cause); } }
e52b254c714f0000610a5a56ccb542a88e19cfb5
851d7883e667b1883a327fe29e24c180ec63cb09
/src/blocks/woody/java/org/apache/cocoon/woody/validation/impl/AssertValidatorBuilder.java
ddc4d64fc24943f122b83eafee2a49937527f273
[ "Apache-2.0" ]
permissive
sri-desai/Cocoon
6772622f5e4b45339df25825cfc5bc50360b48a3
a513391476ea1d8c835df03187947bf0fde913c2
refs/heads/master
2021-07-10T22:46:35.108428
2017-10-06T03:36:02
2017-10-06T03:36:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,677
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.cocoon.woody.validation.impl; import org.apache.cocoon.woody.datatype.validationruleimpl.AssertValidationRuleBuilder; import org.apache.cocoon.woody.formmodel.WidgetDefinition; import org.apache.cocoon.woody.validation.WidgetValidator; import org.apache.cocoon.woody.validation.WidgetValidatorBuilder; import org.w3c.dom.Element; /** * Adapter for {@link org.apache.cocoon.woody.datatype.validationruleimpl.AssertValidationRuleBuilder} * * @author <a href="http://www.apache.org/~sylvain/">Sylvain Wallez</a> * @version CVS $Id$ */ public class AssertValidatorBuilder extends AssertValidationRuleBuilder implements WidgetValidatorBuilder { public WidgetValidator build(Element validationRuleElement, WidgetDefinition definition) throws Exception { return new ValidationRuleValidator(super.build(validationRuleElement)); } }
50140258d02e312d2a30c80584a22ac7bbebd0b7
c437bb7b42bccf19673b1ec9fbaf26632ae73692
/j2me/media/graphics/geography/GeographicPathFindingLibrary/src/allbinary/media/graphics/geography/pathfinding/PathFindingNode.java
c6067d66128b5b4c3250ecd06e8a735440dc2693
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
sanyaade/AllBinary-Platform
e9256f55df8ffa82c55ca401eba9ffe83956995c
a07ee2008a1b4f27025b229191545dec62bc34ad
refs/heads/master
2016-09-10T13:34:06.672577
2011-10-07T02:14:46
2011-10-07T02:14:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,394
java
/* * AllBinary Open License Version 1 * Copyright (c) 2011 AllBinary * * By agreeing to this license you and any business entity you represent are * legally bound to the AllBinary Open License Version 1 legal agreement. * * You may obtain the AllBinary Open License Version 1 legal agreement from * AllBinary or the root directory of AllBinary's AllBinary Platform repository. * * Created By: Travis Berthelot * */ package allbinary.media.graphics.geography.pathfinding; import abcs.logic.basic.string.CommonSeps; import allbinary.media.graphics.geography.map.GeographicMapCellPosition; public class PathFindingNode { private PathFindingNode parent; private GeographicMapCellPosition geographicMapCellPosition; public PathFindingNode(PathFindingNode parent, GeographicMapCellPosition geographicMapCellPosition) throws Exception { this.setParent(parent); this.setGeographicMapCellPosition(geographicMapCellPosition); /* if(this.getParent() == null) { LogUtil.put(LogFactory.getInstance("No Parent", this, CommonStrings.getInstance().CONSTRUCTOR)); } */ if(this.getGeographicMapCellPosition() == null) { throw new Exception("No GeographicMapCellPosition"); } } public PathFindingNode getParent() { return parent; } private void setParent(PathFindingNode parent) { this.parent = parent; } public GeographicMapCellPosition getGeographicMapCellPosition() { return geographicMapCellPosition; } public void setGeographicMapCellPosition(GeographicMapCellPosition geographicMapCellPosition) { this.geographicMapCellPosition = geographicMapCellPosition; } public String toString() { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(this.getClass().getName()); stringBuffer.append(": "); stringBuffer.append(" Path: "); stringBuffer.append(this.getGeographicMapCellPosition().toString()); PathFindingNode pathFindingNode = this.parent; while(pathFindingNode != null) { stringBuffer.append(pathFindingNode.getGeographicMapCellPosition().toString()); stringBuffer.append(CommonSeps.getInstance().SPACE); pathFindingNode = pathFindingNode.parent; } return stringBuffer.toString(); } }
5b81b798c527dc79ad9b4b5a1f325810d819f0e7
fd9ad9d69168a6f68d2c66b0ad10d60effe3df6a
/src/RayTracing/A4App.java
99118b361183c3c69cd82aca49dda436608fd8d7
[]
no_license
chenbi/Demo
5fcc0608953fb65994777b0b170f4bc2f02b9347
b4631e49dca1603ab4cf38a4b12f53b1910bb5d0
refs/heads/master
2021-05-04T15:33:56.560026
2018-02-04T22:59:02
2018-02-04T22:59:02
120,230,982
1
0
null
null
null
null
UTF-8
Java
false
false
1,359
java
package RayTracing; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import mintools.swing.FileSelect; import org.w3c.dom.Document; public class A4App { /** * Entry point for the application. * * @param args The first argument should be the filename of the scene XML file. */ public static void main(String[] args) { if ( args.length == 0 ) { File f = FileSelect.select( "xml", "Scene Description", "Load", "a4data", false); if( f != null ) { args = new String[] { f.getAbsolutePath() }; } else { System.exit(0); } } try { InputStream inputStream = new FileInputStream( new File(args[0]) ); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(inputStream); Scene scene = Parser.createScene( document.getDocumentElement() ); scene.render(true); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Failed to load simulation input file.", e); } System.exit(0); } }
27eb7a071c59eb4e1ce0d68c174b1355db7656a8
acefd48311f0c8c07139a9affbf7f07d6d806d56
/src/PRACTICE_ADF2/studentsView.java
3e52a6383534741780cddb8120922c4245bbbd70
[]
no_license
nguyentrongty/Sem2
0b628b70bffb99ecb9c038d79c51e6f500ef204e
db0978c6eb023ed24470dc5a133eac0b3acd2ce6
refs/heads/master
2021-04-17T17:28:39.643599
2020-04-28T02:32:40
2020-04-28T02:32:40
249,462,797
1
0
null
null
null
null
UTF-8
Java
false
false
1,121
java
package PRACTICE_ADF2; import java.util.Scanner; public class studentsView { public static void main(String[] args) { int i = 1; while(i > 0) { System.out.println("1.Add student records\n" + "2. Display student records\n" + "3. Save\n" + "4. Exit"); int num = new Scanner(System.in).nextInt(); switch (num) { case 1: System.out.println("Add student records:"); StudentsController.add(); break; case 2: System.out.println("Display student records"); StudentsController.select(); break; case 3: System.out.println("Save"); StudentsController.save(); break; case 4: System.out.println("End"); i = -1;break; default: System.out.println("nothing");break; } } } }
21b0805698cc032c993a2b7550d1dd3f1c42bb78
1559bd447dc999860cca334564fcdabd8acd6aa7
/TestProject/src/kuchBI/Strings.java
4cbe43d48fa1e9126c58789a597584558e0e3f18
[]
no_license
priyasar/Gitdemo
211efca6d3ef6c3a6d894a92915638774e6f3c89
d93683e95dd961f2a533908908303fc4ebe05569
refs/heads/master
2020-05-19T14:30:11.807935
2019-05-05T17:30:44
2019-05-05T17:30:44
185,062,099
0
0
null
null
null
null
UTF-8
Java
false
false
47
java
package kuchBI; public interface Strings { }
0989a51ed920951e6d10187d5d6588a374bfef87
9e01c682b6b19b2de083e22d61681822b0ce8bca
/enum/src/app/Pizzeria.java
aa558ab633eb3a86812798808e1a8617c9aad97f
[]
no_license
TutorialeLS/Tutoriale
151d3ad69af798fec06758c29ad8073f680ebf5d
5bcbb8b42083d501e3d098ee977638151f7e490b
refs/heads/master
2020-04-12T09:45:13.097512
2018-12-19T09:35:37
2018-12-19T09:35:37
162,406,591
0
0
null
null
null
null
UTF-8
Java
false
false
424
java
package app; import java.util.Scanner; public class Pizzeria { public static void main(String[] args) { System.out.println("Wyswietl wszystkie pizze"); for(Pizza p:Pizza.values()) { System.out.println(p.name()+" "+p); } System.out.println("podaj pizze"); Scanner scan=new Scanner(System.in); Pizza pizz1=Pizza.valueOf(scan.nextLine()); System.out.println(pizz1.name()+pizz1); scan.close(); } }
f289484a08fb15550f81d102f6dfc22ac18f78b8
33ec334bea7b6a6c38e5a82df70920c5e750ca5a
/src/main/java/com/lavrente/soundtrack/command/admin/ShowUsersCommand.java
f668ba913dce129fbe87ed14edf72f1572de188f
[]
no_license
LavrentevaAlexandra/EpamSoundTracker
c80d182458624e3627f6537e359a595469395f9a
a4189d28a8a3f1314bab9063853a3151745a570c
refs/heads/master
2021-01-11T20:21:14.527785
2017-01-28T16:06:41
2017-01-28T16:06:41
79,097,883
0
0
null
null
null
null
UTF-8
Java
false
false
1,566
java
package com.lavrente.soundtrack.command.admin; import com.lavrente.soundtrack.command.AbstractCommand; import com.lavrente.soundtrack.entity.User; import com.lavrente.soundtrack.exception.LogicException; import com.lavrente.soundtrack.logic.UserLogic; import com.lavrente.soundtrack.manager.ConfigurationManager; import com.lavrente.soundtrack.servlet.SessionRequestContent; import java.util.List; /** * Created by 123 on 26.01.2017. */ public class ShowUsersCommand extends AbstractCommand { private final String USER_LIST_ATTR = "users"; /** * Execute. * * @param sessionRequestContent the session request content * @return the string */ @Override public String execute(SessionRequestContent sessionRequestContent) { String page; User user = (User) sessionRequestContent.getSessionAttribute(USER_ATTRIBUTE); if (user != null && user.getRole() == 1) { UserLogic userLogic = new UserLogic(); try { List<User> userList = userLogic.findClients(); sessionRequestContent.setSessionAttribute(USER_LIST_ATTR, userList); page = ConfigurationManager.getProperty(ConfigurationManager.SET_BONUS_PATH); } catch (LogicException e) { LOG.error("Exception during clients search", e); page = redirectToErrorPage(sessionRequestContent, e); } } else { page = ConfigurationManager.getProperty(ConfigurationManager.HOME_PATH); } return page; } }
54a5f47d5aa0488a0bbbc0446163d68e6f019de2
c4d26fc2ec0ccbc47ee5d78e1143d097b1dd86ec
/app/src/main/java/com/example/solarcleaner/FirstFragment.java
8719c9332b2bcbb6232b4054aa56ab18c696bb1a
[]
no_license
goddamnnoob/SolarCleaner
cd126a1593ac4763d97eb97af33e34bc49cab76a
1c43d93f13f13f517ab829162c7b396a97bc9584
refs/heads/master
2023-01-11T23:53:57.931009
2020-10-25T17:45:46
2020-10-25T17:45:46
307,114,955
0
0
null
null
null
null
UTF-8
Java
false
false
1,090
java
package com.example.solarcleaner; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.navigation.fragment.NavHostFragment; public class FirstFragment extends Fragment { @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_first, container, false); } public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { NavHostFragment.findNavController(FirstFragment.this) .navigate(R.id.action_FirstFragment_to_SecondFragment); } }); } }
9aa0161d877322adfb5666cb2cc0b2b7f1541fa1
57de3f63ab106612ade294a30058c358cec79ca9
/src/java/modeloDAO/JornadaVotacionDAO.java
320265cab7fccf60188488f8411cd8851aba6e70
[]
no_license
migolbain/Proyecto-Votaciones-Electronicas
dbec1bd57d7be28df47d1e3a1a266f0b151cd336
4a3d8835e08b7ad37067c6daed39510d178d85f2
refs/heads/master
2020-09-27T06:01:18.131504
2019-12-07T03:14:20
2019-12-07T03:14:20
226,446,894
0
0
null
null
null
null
UTF-8
Java
false
false
11,228
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 modeloDAO; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import modeloVO.JornadaVotacionVO; import modeloVO.VotoVO; import util.ConexionBD; import util.InterfaceCRUD; /** * * @author migol */ public class JornadaVotacionDAO extends ConexionBD implements InterfaceCRUD { private Connection conexion = null; private Statement puente = null; private ResultSet mensajero = null; private ResultSet mensajero2 = null; private String ID_JornadaVotacion = ""; private String Fecha_JornadaApertura = ""; private String Fecha_JornadaCierre = ""; private String Estado_JornadaVotacion = ""; private String Fecha_Jornada = ""; private String Estado_Voto = ""; private String id_persona = ""; private String tipoid_persona = ""; private String documento_persona = ""; private String nombres_persona = ""; private String primerapellido_persona = ""; private String segundoapellido_persona = ""; private String genero_persona = ""; private String correo_persona = ""; private String estado_formacion = ""; private String estado_candidato = ""; private String id_usuario = ""; private String id_jornada = ""; private String ID_Detallejornada = ""; private boolean operaciones = false; public JornadaVotacionDAO(JornadaVotacionVO jornadaVotacionVO) { super(); try { conexion = this.obtenerConexion(); puente = conexion.createStatement(); ID_JornadaVotacion = jornadaVotacionVO.getID_JornadaVotacion(); Fecha_JornadaApertura = jornadaVotacionVO.getFecha_JornadaApertura(); Fecha_JornadaCierre = jornadaVotacionVO.getFecha_JornadaCierre(); Estado_JornadaVotacion = jornadaVotacionVO.getEstado_JornadaVotacion(); Fecha_Jornada = jornadaVotacionVO.getFecha_Jornada(); Estado_Voto = jornadaVotacionVO.getEstado_Voto(); id_persona = jornadaVotacionVO.getId_persona(); nombres_persona = jornadaVotacionVO.getNombres_persona(); primerapellido_persona = jornadaVotacionVO.getPrimerapellido_persona(); segundoapellido_persona = jornadaVotacionVO.getSegundoapellido_persona(); tipoid_persona = jornadaVotacionVO.getTipoid_persona(); documento_persona = jornadaVotacionVO.getDocumento_persona(); genero_persona = jornadaVotacionVO.getGenero_persona(); correo_persona = jornadaVotacionVO.getCorreo_persona(); estado_formacion = jornadaVotacionVO.getEstado_formacion(); estado_candidato = jornadaVotacionVO.getEstado_candidato(); id_jornada = jornadaVotacionVO.getId_jornada(); id_usuario = jornadaVotacionVO.getId_usuario(); ID_Detallejornada = jornadaVotacionVO.getID_Detallejornada(); } catch (Exception e) { System.out.println("¡Error!: " + e.toString()); } } @Override public boolean agregarRegistro() { try { CallableStatement call = conexion.prepareCall("call crearjornada(?,?,?,?,?);"); call.setString(1, ID_JornadaVotacion); call.setString(2, Fecha_Jornada); call.setString(3, Fecha_JornadaApertura); call.setString(4, Fecha_JornadaCierre); call.setString(5, Estado_JornadaVotacion); call.executeUpdate(); operaciones = true; } catch (Exception e) { System.out.println("¡Error!: " + e.toString()); } return operaciones; } @Override public boolean actualizarRegistro() { try { CallableStatement call = conexion.prepareCall("call cerrarjornada (?,?,?);"); CallableStatement call2 = conexion.prepareCall("call actualizarestadovoto(?)"); call.setString(1, ID_JornadaVotacion); call.setString(2, Fecha_JornadaCierre); call.setString(3, Estado_JornadaVotacion = "Inactivo"); call2.setString(1, Estado_Voto); call.executeUpdate(); call2.executeUpdate(); operaciones = true; this.cerrarConexion(); } catch (Exception e) { System.out.println("¡Error!: " + e.toString()); } return operaciones; } public boolean insertarpersonasdetalle() { ConexionBD conexion2 = new ConexionBD(); try { CallableStatement callStat = conexion2.obtenerConexion().prepareCall("call consultarpersonas"); mensajero = callStat.executeQuery(); while (mensajero.next()) { id_persona = mensajero.getString("id_persona"); tipoid_persona = mensajero.getString("TipoIdentificacion_persona"); documento_persona = mensajero.getString("documento_persona"); nombres_persona = mensajero.getString("Nombres_persona"); primerapellido_persona = mensajero.getString("PrimerApellido_Persona"); segundoapellido_persona = mensajero.getString("SegundoApellido_Persona"); genero_persona = mensajero.getString("Genero_persona"); correo_persona = mensajero.getString("Correo_persona"); estado_formacion = mensajero.getString("Estado_Formacion"); Estado_Voto = mensajero.getString("Estado_voto"); estado_candidato = mensajero.getString("Estado_candidato"); id_usuario = mensajero.getString("ID_Usuario"); id_jornada = mensajero.getString("ID_Jornada"); JornadaVotacionVO personas = new JornadaVotacionVO(); personas.setId_persona(id_persona); personas.setTipoid_persona(tipoid_persona); personas.setDocumento_persona(documento_persona); personas.setNombres_persona(nombres_persona); personas.setPrimerapellido_persona(primerapellido_persona); personas.setSegundoapellido_persona(segundoapellido_persona); personas.setGenero_persona(genero_persona); personas.setCorreo_persona(correo_persona); personas.setEstado_formacion(estado_formacion); personas.setEstado_Voto(Estado_Voto); personas.setEstado_candidato(estado_candidato); personas.setId_usuario(id_usuario); personas.setId_jornada(id_jornada); CallableStatement callStat2 = conexion2.obtenerConexion().prepareCall("call consultarultimajornada"); mensajero2 = callStat2.executeQuery(); while (mensajero2.next()) { Fecha_Jornada = mensajero2.getString("Fecha_Jornada"); ID_JornadaVotacion = mensajero2.getString("ID_JornadaVotaciones"); Estado_JornadaVotacion = mensajero2.getString("Estado_JornadaVotacion"); Fecha_JornadaApertura = mensajero2.getString("Fecha_JornadaApertura"); JornadaVotacionVO ultimajornada = new JornadaVotacionVO(); ultimajornada.setFecha_Jornada(Fecha_Jornada); ultimajornada.setID_JornadaVotacion(ID_JornadaVotacion); ultimajornada.setEstado_JornadaVotacion(Estado_JornadaVotacion); ultimajornada.setFecha_JornadaApertura(Fecha_JornadaApertura); } CallableStatement call = conexion.prepareCall("call insertardetalle (?,?,?,?);"); call.setString(1, ID_Detallejornada); call.setString(2, ID_JornadaVotacion); call.setString(3, id_persona); call.setString(4, Estado_Voto); call.executeUpdate(); } operaciones = true; } catch (SQLException e) { System.out.println("¡Error!: " + e.toString()); } return operaciones; } public ArrayList<JornadaVotacionVO> consultarultimajornada() { ArrayList<JornadaVotacionVO> consultaultimajornada = new ArrayList<>(); ConexionBD conexion2 = new ConexionBD(); try { CallableStatement callStat = conexion2.obtenerConexion().prepareCall("call consultarultimajornada"); mensajero = callStat.executeQuery(); while (mensajero.next()) { Fecha_Jornada = mensajero.getString("Fecha_Jornada"); ID_JornadaVotacion = mensajero.getString("ID_JornadaVotaciones"); Estado_JornadaVotacion = mensajero.getString("Estado_JornadaVotacion"); Fecha_JornadaApertura = mensajero.getString("Fecha_JornadaApertura"); JornadaVotacionVO ultimoid = new JornadaVotacionVO(); ultimoid.setFecha_Jornada(Fecha_Jornada); ultimoid.setID_JornadaVotacion(ID_JornadaVotacion); ultimoid.setEstado_JornadaVotacion(Estado_JornadaVotacion); ultimoid.setFecha_JornadaApertura(Fecha_JornadaApertura); consultaultimajornada.add(ultimoid); } } catch (SQLException e) { System.out.println("¡Error!: " + e.toString()); } return consultaultimajornada; } public ArrayList<JornadaVotacionVO> Conteonovotosreportes(String fecha) { ConexionBD conexion2 = new ConexionBD(); ArrayList<JornadaVotacionVO> listavotos = new ArrayList<>(); try { CallableStatement callStat = conexion2.obtenerConexion().prepareCall("call conteonovotosreportedetalle(?)"); callStat.setString(1, fecha); mensajero = callStat.executeQuery(); while (mensajero.next()) { documento_persona = mensajero.getString("documento_persona"); nombres_persona = mensajero.getString("Nombres_persona"); primerapellido_persona = mensajero.getString("Apellidos"); Estado_Voto = mensajero.getString("estado_voto"); id_jornada = mensajero.getString("Jornada"); Fecha_Jornada = mensajero.getString("Fecha_Jornada"); JornadaVotacionVO jornadaVotacionVO = new JornadaVotacionVO(); jornadaVotacionVO.setDocumento_persona(documento_persona); jornadaVotacionVO.setNombres_persona(nombres_persona); jornadaVotacionVO.setPrimerapellido_persona(primerapellido_persona); jornadaVotacionVO.setEstado_Voto(Estado_Voto); jornadaVotacionVO.setId_jornada(id_jornada); jornadaVotacionVO.setFecha_Jornada(Fecha_Jornada); listavotos.add(jornadaVotacionVO); } } catch (SQLException e) { System.out.println("¡Error!: " + e.toString()); } return listavotos; } }
b36c6e72faebdc1326763c3b6a1686373f314ce3
dbfdac1ba3c15d8992fffff5cbc6c62377c0e81e
/dp/PalindromicSubstrings.java
822592d724f5709414f9e2f6449d1c284e889ad1
[]
no_license
yzzyq/leetcode
27e7fc1f0796fbb36ce8e169efe7c7ed301d612f
ac765db26cbe99f311d1fe72a643276ff019d625
refs/heads/main
2023-04-09T00:00:40.592691
2021-04-13T03:50:30
2021-04-13T03:50:30
280,605,247
0
0
null
null
null
null
GB18030
Java
false
false
4,046
java
package dp; /** * 647. Palindromic Substrings * * Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. Example 1: Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". Note: The input string length won't exceed 1000. * * @author yzzyq * */ // 查看字符串中有多少个回文子串 public class PalindromicSubstrings { // 动态规划问题,不过运行时间较长,并且运行空间较大 public int countSubstrings(String s) { if(s.length() == 0) return 0; if(s.length() == 1) return 1; int s_len = s.length(); boolean[][] is_palind = new boolean[s_len][s_len]; int max_num = 0; for(int index = s_len - 1; index >= 0; index--) { for(int com_index = s_len - 1; com_index >= index; com_index--) { // 一句话即可进行判断关系 is_palind[index][com_index] = (s.charAt(index) == s.charAt(com_index) && (com_index - index <= 2 || is_palind[index + 1][com_index - 1])); if(is_palind[index][com_index]) max_num++; // if(com_index == index) { // is_palind[index][com_index] = true; // max_num++; // }else { // if(s.charAt(index) == s.charAt(com_index)) { // is_palind[index][com_index] = true; // if(com_index - 1 >= index + 1) is_palind[index][com_index] = is_palind[index + 1][com_index - 1]; // if(is_palind[index][com_index]) max_num++; // }else { // is_palind[index][com_index] = false; // } // } } } return max_num; } // 最基本的判断回文串的方式,就是暴力遍历,由中心字符进行中心拓展 public int countSubstrings_1(String s) { if(s.length() == 0) return 0; if(s.length() == 1) return 1; char[] s_char = s.toCharArray(); int palindrom_num = 0; for(int start = 0; start < s.length(); start++) { palindrom_num += getNum(start, start, s_char); palindrom_num += getNum(start, start + 1, s_char); } return palindrom_num; } public int getNum(int left, int right, char[] s_char) { int num = 0; while(left >= 0 && right < s_char.length && s_char[left] == s_char[right]) { left--; right++; num++; } return num; } // 经典马拉车算法 public int countSubstrings_2(String s) { if(s.length() == 0) return 0; if(s.length() == 1) return 1; // 对字符串进行重新组织 StringBuilder sb = new StringBuilder(); sb.append("^#"); for(int i = 0; i < s.length(); i++) { sb.append(s.charAt(i)); sb.append("#"); } sb.append("$"); int sb_len = sb.length(); int[] par_len = new int[sb_len]; int r_pos = 0, m_pos = 0, num = 0; for(int index = 1; index < sb_len - 1; index++) { // 先判断它的镜像是否超过了边界距离 par_len[index] = index < r_pos?Math.min(r_pos - index, par_len[2*m_pos - index]):1; // 进行中心拓展 while(sb.charAt(index+par_len[index]) == sb.charAt(index-par_len[index])) { par_len[index]++; } // 维护 if(index + par_len[index] > r_pos) { m_pos = index; r_pos = par_len[index] + index; } // 统计 num += par_len[index]/2; } return num; } public static void main(String[] args) { String s = "aaa"; var ps = new PalindromicSubstrings(); int num = ps.countSubstrings_2(s); System.out.println(num); } }
ec6b45b036049af438d9323111fe0d54fae6afbf
7b0bfecb35b284e4933a72460ca22c0e43d08cc1
/e3-parent/e3-common/src/main/java/com/Lee/dto/EasyUIDataGridResultDTO.java
32d29c6f0b675a9e2b093d447b40c31a49956a31
[]
no_license
Leme34/e3-parent
3efc28f7fde0756bf37ecd494d4790ee6bf4619c
43415abbee396a803c6d3dacc80b53c89016ecec
refs/heads/master
2020-04-02T13:00:25.517545
2018-10-24T08:37:57
2018-10-24T08:37:57
154,462,423
2
0
null
null
null
null
UTF-8
Java
false
false
215
java
package com.Lee.dto; import lombok.Data; import java.io.Serializable; import java.util.List; @Data public class EasyUIDataGridResultDTO implements Serializable{ private Long total; private List rows; }
eb936f61b0e5f33bb58b4944e16796d29f3789c3
13f9110581f5827f763b5f855634a74248de8d71
/JavaAlgorithms/src/edu/princeton/cs/algs4/FileIndex.java
72e454e6298852e66d0414b816bbc163d2bf23f2
[]
no_license
neoontherun/AlgoPractice
7b3aba5b72508080a00bfd4cdfd437436347a3e1
7c7178cc39089745671e3cf0065e45f12ef25157
refs/heads/master
2021-06-02T15:16:15.217390
2019-02-25T04:30:26
2019-02-25T04:30:26
96,607,102
0
0
null
null
null
null
UTF-8
Java
false
false
3,344
java
/****************************************************************************** * Compilation: javac FileIndex.java * Execution: java FileIndex file1.txt file2.txt file3.txt ... * Dependencies: ST.java SET.java In.java StdIn.java StdOut.java * Data files: https://algs4.cs.princeton.edu/35applications/ex1.txt * https://algs4.cs.princeton.edu/35applications/ex2.txt * https://algs4.cs.princeton.edu/35applications/ex3.txt * https://algs4.cs.princeton.edu/35applications/ex4.txt * * % java FileIndex ex*.txt * age * ex3.txt * ex4.txt * best * ex1.txt * was * ex1.txt * ex2.txt * ex3.txt * ex4.txt * * % java FileIndex *.txt * * % java FileIndex *.java * ******************************************************************************/ package edu.princeton.cs.algs4; import java.io.File; /** * The {@code FileIndex} class provides a client for indexing a set of files, * specified as command-line arguments. It takes queries from standard input and * prints each file that contains the given query. * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/35applications">Section 3.5</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class FileIndex { // Do not instantiate. private FileIndex() { } public static void main(String[] args) { // key = word, value = set of files containing that word ST<String, SET<File>> st = new ST<String, SET<File>>(); // create inverted index of all files StdOut.println("Indexing files"); for (String filename : args) { StdOut.println(" " + filename); File file = new File(filename); In in = new In(file); while (!in.isEmpty()) { String word = in.readString(); if (!st.contains(word)) st.put(word, new SET<File>()); SET<File> set = st.get(word); set.add(file); } } // read queries from standard input, one per line while (!StdIn.isEmpty()) { String query = StdIn.readString(); if (st.contains(query)) { SET<File> set = st.get(query); for (File file : set) { StdOut.println(" " + file.getName()); } } } } } /****************************************************************************** * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, Addison-Wesley * Professional, 2011, ISBN 0-321-57351-X. http://algs4.cs.princeton.edu * * * algs4.jar 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. * * algs4.jar 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 * algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
a82f929f364e3b6458e9a56405191a854bf59880
4568d89a4930e0a20ed53efad855b067106591d2
/crudusingr2dbcwebflux/src/main/java/com/dovile/crudusingr2dbcwebflux/config/R2DBCConfiguration.java
4bbf7f0e4dae1501897ffcdfe205adb655b0a11c
[]
no_license
Doirena/works-with-java-spring-boot
50988f14c21946ba20d94d6d0c2964c2e0e354ff
b7df773db86ef83e7f8dc8c3121b9ca3171b2690
refs/heads/master
2023-01-28T10:26:06.533098
2020-12-08T23:22:07
2020-12-08T23:22:07
318,335,019
0
0
null
2020-12-08T23:22:09
2020-12-03T22:21:23
Java
UTF-8
Java
false
false
2,270
java
package com.dovile.crudusingr2dbcwebflux.config; import com.dovile.crudusingr2dbcwebflux.entity.Person; import com.dovile.crudusingr2dbcwebflux.repository.PersonRepository; import io.r2dbc.spi.ConnectionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.r2dbc.connection.init.ConnectionFactoryInitializer; import org.springframework.r2dbc.connection.init.ResourceDatabasePopulator; import java.time.Duration; import java.util.Arrays; import java.util.Random; /** * @author Dovile Barkauskaite <[email protected]> */ @Configuration public class R2DBCConfiguration { private static final Logger log = LoggerFactory.getLogger(R2DBCConfiguration.class); @Bean ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory) { ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer(); initializer.setConnectionFactory(connectionFactory); initializer.setDatabasePopulator(new ResourceDatabasePopulator(new ClassPathResource("schema.sql"))); return initializer; } //Add data into memory db @Bean public CommandLineRunner init(PersonRepository personRepository) { System.out.println(" DATA which I add"); return args -> { personRepository.saveAll(Arrays.asList(new Person("Jack", "Bauer", new Random().nextInt(100)), new Person("Chloe", "O'Brian", new Random().nextInt(100)), new Person("Kim", "Bauer", new Random().nextInt(100)), new Person("David", "Palmer", new Random().nextInt(100)), new Person("Michelle", "Dessler", new Random().nextInt(100)))) .blockLast(Duration.ofSeconds(10)); log.info("Person found with findAll():"); log.info("-------------------------------"); personRepository.findAll().doOnNext(person -> { log.info(person.toString()); }).blockLast(Duration.ofSeconds(10)); }; } }
0c1f07815441c3accb82c4462810d9938b778a7e
52cb8c24300c537efc8a8e454891d840d358aede
/src/com/twu/biblioteca/LoginService.java
5f50d011bf0c13cdd59a4d97c321b272f00fcf2f
[ "Apache-2.0" ]
permissive
hchauke/twu-biblioteca-ralson-2
11c5e26eb77f28bbbf372e5c49f9161401309ed8
c6a9bc4c917295bfecb761b232b32ee3d626bc66
refs/heads/master
2021-01-12T12:45:58.907717
2016-10-03T13:20:27
2016-10-03T13:20:27
69,855,588
0
0
null
null
null
null
UTF-8
Java
false
false
1,499
java
package com.twu.biblioteca; import com.twu.biblioteca.businessLogic.extend.ConsoleService; import com.twu.biblioteca.library.LibraryManager; import com.twu.biblioteca.model.UserAccount; public class LoginService { private UserAccount loginUser; public boolean login(String loginId, String password) { if (loginId == null || loginId.isEmpty() || password == null || password.isEmpty()) { return false; } loginUser = LibraryManager.findUserAccount(loginId, password); return loginUser != null; } public UserAccount loginManager(ConsoleService consoleService, int attempts) { boolean isLogin = false; while (!isLogin) { String loginId = consoleService.inputWithPrompt("Please input login id: "); String password = consoleService.inputWithPrompt("Please input login password: "); isLogin = login(loginId, password); if(!isLogin) { consoleService.printError("Login Failed! Please check your id and password."); if(attempts <= 0) { consoleService.printError("=======Try too many! Login Aborted!======="); return null; } consoleService.inputWithPrompt(""); --attempts; } } consoleService.printMessage("Login Successfully!\n"); consoleService.printMessage(loginUser.getUserProfile()); return loginUser; } }