text
stringlengths
10
2.72M
package reactive; public class Main { public static void main(String[] args) { // new DataLoader().load(); new ParallelDataLoader().load(); } }
package rent; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JButton; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.awt.event.ActionEvent; import java.awt.Font; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; public class UserDetail extends JFrame { PreparedStatement pst; Connection con; ResultSet rs; private JPanel contentPane; private JTextField textField; private JTextField textField_1; private JTextField textField_2; private JTextField textField_3; private JTextField textField_4; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UserDetail frame = new UserDetail(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public UserDetail() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 475, 344); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblNewLabel = new JLabel("UserDetail"); lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 16)); lblNewLabel.setBounds(191, 24, 124, 14); contentPane.add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("CustomerId"); lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 11)); lblNewLabel_1.setBounds(52, 72, 89, 14); contentPane.add(lblNewLabel_1); JLabel lblNewLabel_2 = new JLabel("CustomerName"); lblNewLabel_2.setFont(new Font("Tahoma", Font.BOLD, 11)); lblNewLabel_2.setBounds(52, 104, 89, 14); contentPane.add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel("CustomerAddress"); lblNewLabel_3.setFont(new Font("Tahoma", Font.BOLD, 11)); lblNewLabel_3.setBounds(52, 143, 108, 14); contentPane.add(lblNewLabel_3); JLabel lblNewLabel_4 = new JLabel("PhoneNo"); lblNewLabel_4.setFont(new Font("Tahoma", Font.BOLD, 11)); lblNewLabel_4.setBounds(52, 183, 89, 14); contentPane.add(lblNewLabel_4); JLabel lblNewLabel_5 = new JLabel("GovtId"); lblNewLabel_5.setFont(new Font("Tahoma", Font.BOLD, 11)); lblNewLabel_5.setBounds(52, 222, 46, 14); contentPane.add(lblNewLabel_5); textField = new JTextField(); textField.setBounds(189, 69, 126, 20); contentPane.add(textField); textField.setColumns(10); textField_1 = new JTextField(); textField_1.setBounds(191, 101, 124, 20); contentPane.add(textField_1); textField_1.setColumns(10); textField_2 = new JTextField(); textField_2.setBounds(191, 140, 124, 20); contentPane.add(textField_2); textField_2.setColumns(10); textField_3 = new JTextField(); textField_3.setBounds(191, 180, 124, 20); contentPane.add(textField_3); textField_3.setColumns(10); textField_4 = new JTextField(); textField_4.setBounds(191, 219, 124, 20); contentPane.add(textField_4); textField_4.setColumns(10); JButton btnNewButton = new JButton("Insert"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { String sql = "insert into UserDetails4(CustomerId,CustomerName,CustomerAddress,PhoneNo,GovtId)values ( ?,?,?,?,?)"; Class.forName("com.mysql.cj.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/backend", "root","root"); pst = con.prepareStatement(sql); String CustomerId = textField.getText(); pst.setString(1,CustomerId); String CustomerName = textField_1.getText(); pst.setString(2,CustomerName); String CustomerAddress = textField_2.getText(); pst.setString(3,CustomerAddress); String PhoneNo = textField_3.getText(); pst.setString(4,PhoneNo); String GovtId = textField_4.getText(); pst.setString(5,GovtId); pst.executeUpdate(); //if(rs.next()) { JOptionPane.showMessageDialog(null," inserted Sucessfully" ); /*} else { JOptionPane.showMessageDialog(null," not inserted Sucessfully" ); }*/ } catch(SQLException ex){ JOptionPane.showMessageDialog(null,ex ); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 12)); btnNewButton.setBounds(34, 259, 89, 23); contentPane.add(btnNewButton); JButton btnNewButton_1 = new JButton("Update"); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/backend", "root","root"); pst = con.prepareStatement("UPDATE UserDetails4 SET CustomerAddress=?,PhoneNo=? where CustomerId=?"); String CustomerAddress = textField_2.getText(); pst.setString(1,CustomerAddress); String PhoneNo = textField_3.getText(); pst.setString(2,PhoneNo); String CustomerId = textField.getText(); pst.setString(3, CustomerId); pst.executeUpdate(); System.out.print(pst); JOptionPane.showMessageDialog(null," Updated Sucessfully" ); } catch(SQLException ex){ JOptionPane.showMessageDialog(null,ex ); } catch (ClassNotFoundException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } } }); btnNewButton_1.setFont(new Font("Tahoma", Font.BOLD, 12)); btnNewButton_1.setBounds(154, 260, 89, 23); contentPane.add(btnNewButton_1); JButton btnNewButton_2 = new JButton("Delete"); btnNewButton_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { String sql = "delete from UserDetails4 where CustomerId=? "; Class.forName("com.mysql.cj.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/backend", "root","root"); pst = con.prepareStatement(sql); String CustomerId = textField.getText(); pst.setString(1,CustomerId); pst.executeUpdate(); JOptionPane.showMessageDialog(null," Deleted Sucessfully" ); } catch(SQLException ex){ JOptionPane.showMessageDialog(null,ex ); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); btnNewButton_2.setFont(new Font("Tahoma", Font.BOLD, 12)); btnNewButton_2.setBounds(275, 260, 89, 23); contentPane.add(btnNewButton_2); } }
/* 2022-08-22 [Leetcode][Easy] 1528. Shuffle String */ class ShuffleString { /* * Runtime: 1 ms, faster than 100.00% of Java online submissions for Shuffle String. * Memory Usage: 45 MB, less than 39.33% of Java online submissions for Shuffle String. */ public String restoreString(String s, int[] indices) { char[] chStr = s.toCharArray(); char[] shuffled = new char[indices.length]; for(int i=0; i<indices.length; i++) { shuffled[indices[i]] = chStr[i]; } return String.valueOf(shuffled); } }
package com.redstoner.remote_console.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.zip.GZIPInputStream; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.redstoner.remote_console.protected_classes.FakePlayer; public class LogHandler extends Thread { private CommandSender sender; private String regex, fileName; private static ArrayList<CommandSender> stillSearching = new ArrayList<CommandSender>(); private LogHandler(CommandSender sender, String regex, String fileName) { this.sender = sender; this.regex = regex; this.fileName = fileName; } public static void doSearch(CommandSender sender, String regex, String fileName) { if (stillSearching.contains(sender)) { sender.sendMessage(" §eRMC: §4DO NOT EVER TRY TO QUERY TWO SEARCHES AT ONCE. Go die..."); return; } stillSearching.add(sender); LogHandler instance = new LogHandler(sender, regex, fileName); instance.start(); } /** * Searches the logs for a certain regex and forwards any matches to the sender. * * @param sender the issuer of the search * @param regex the regex to search for. Will be wrapped in "^.*" and ".*$" if it is missing line delimiters * @param fileName the name of the files to search through. May contain wildcards. */ private void search(CommandSender sender, String regex, String fileName) { long starttime = System.currentTimeMillis(); int matches = 0; sender.sendMessage(" §eRMC: Starting log search for §a" + regex + " §ein §a" + fileName + " §enow. Please don't query another search untils this one is done."); try { if (!regex.startsWith("^")) regex = "^.*" + regex; if (!regex.endsWith("$")) regex += ".*$"; boolean singleFile = true; if (fileName.contains("*")) singleFile = false; File logFolder = ConfigHandler.getFile("rmc.logs.path"); fileName = fileName.replace("*", ".*"); for (File file : logFolder.listFiles()) { if (file.getName().matches(fileName)) { if (file.getName().endsWith(".gz")) { BufferedReader inputReader = new BufferedReader( new InputStreamReader(new GZIPInputStream(new FileInputStream(file)))); matches += searchStream(inputReader, regex, sender, singleFile, file.getName()); inputReader.close(); } else { BufferedReader inputReader = new BufferedReader(new FileReader(file)); matches += searchStream(inputReader, regex, sender, singleFile, file.getName()); inputReader.close(); } continue; } } } catch (Exception e) { sender.sendMessage(" §eRMC: §cSomething went wrong, the search returned -1... Please check your settings!"); stillSearching.remove(sender); return; } stillSearching.remove(sender); sender.sendMessage(" §eRMC: Your search took a total of " + (System.currentTimeMillis() - starttime) + "ms."); sender.sendMessage(" §eRMC: Found " + (matches > 0 ? "§a" : "§c") + matches + " §ematches total."); return; } /** * This function searches through an InputStream to find a regex. If it finds a match, it will forward that match to the sender and increase the match counter. * * @param inputReader the input reader containing the data * @param regex the regex to search for * @param sender the issuer of the search * @param singleFile true if only a single file is being searched, false if the original filename contained wildcards. * @param filename the name of the file that is currently being searched * @return how many matches it found * @throws IOException if something goes wrong */ private static int searchStream(BufferedReader inputReader, String regex, CommandSender sender, boolean singleFile, String filename) throws IOException { FakePlayer fp = null; if (sender instanceof FakePlayer) fp = (FakePlayer) sender; Player p = null; if (sender instanceof Player) p = (Player) sender; try { Pattern.compile(regex); } catch (PatternSyntaxException e) { stillSearching.remove(sender); sender.sendMessage(" §eRMC: §cInvalid regex detected:"); sender.sendMessage(" §eRMC: §c" + e.getMessage()); } int matches = 0; String line = ""; while ((line = inputReader.readLine()) != null) { if (line.matches(regex)) { if (((fp != null) && (!fp.ownerConnected())) || ((p != null) && (!p.isOnline()))) { stillSearching.remove(sender); throw new IOException("The player has left during the search. Aborting now."); } sender.sendMessage("§b> " + (singleFile ? "" : "§7" + filename + ": ") + "§f" + resolveColors(line)); matches++; } } return matches; } /** * Will resolve escape codes back to minecraft colors codes for ingame output * * @param message the message to resolve * @return the converted message */ private static String resolveColors(String message) { message = message.replace("", "§0"); message = message.replace("", "§1"); message = message.replace("", "§2"); message = message.replace("", "§3"); message = message.replace("", "§4"); message = message.replace("", "§5"); message = message.replace("", "§6"); message = message.replace("", "§7"); message = message.replace("", "§8"); message = message.replace("", "§9"); message = message.replace("", "§a"); message = message.replace("", "§b"); message = message.replace("", "§c"); message = message.replace("", "§d"); message = message.replace("", "§e"); message = message.replace("", "§f"); message = message.replace("", "§k"); message = message.replace("", "§l"); message = message.replace("", "§m"); message = message.replace("", "§n"); message = message.replace("", "§o"); message = message.replace("", "§r"); return message; } @Override public void run() { try { search(sender, regex, fileName); } catch (Exception e) {} } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package polskaad1340.window; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.plaf.basic.BasicBorders; import world.Blockade; import agents.Agent; /** * * @author Kuba */ public final class OknoMapy extends javax.swing.JFrame { private static final long serialVersionUID = 6686871012707857578L; public int tileSize; private ArrayList<ArrayList<JLabel>> foregroundTileGrid, backgroundTileGrid; //najpierw Y, potem X private int defaultBgTileID = 72; public BasicBorders.FieldBorder defaultBorder; private boolean isTileBordered = false; private ArrayList<ObiektPierwszegoPlanu> foregroundList = new ArrayList<>(); private LadowanieMapy lm; private javax.swing.JPanel backgroundPanel; private javax.swing.JPanel bulkPanel; private javax.swing.JPanel contextPanel; private javax.swing.JPanel foregroundPanel; private javax.swing.JPanel iconDisplayPanel; private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1; private javax.swing.JMenu jMenu3; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPanel overallBackgroundPanel; private JScrollPane tileInfoScrollPanel; private javax.swing.JLabel tileInfoPanelLabel1; private JPanel controlPanel; private JButton btnNextIter; private JButton btnNextAgent; private JLabel lblIteracja; private JLabel lblAgent; private JTextField textFieldIter; private JTextField textFieldAgent; private Rectangle contextPanelDefaultRect; private JLabel lblBlockades; private JButton btnBlockades; private JLabel lblCataclysms; private JButton btnCataclysms; private JLabel lblBandits; private JButton btnBandits; private JLabel lblChangePrices; private JButton btnChangePrices; private JLabel lblPricesChanged; private JInternalFrame browseDetailFrame; private JMenu mnBrowse; private JMenu mnBrowseAgents; private JMenu mnBrowseTowns; private JMenu mnInference; private JMenuItem mnWorldInference; public int addObjectToForegroundList(ObiektPierwszegoPlanu opp) { int index = this.foregroundList.size(); this.foregroundList.add(opp); opp.om = this; opp.OknoMapyListHandler = index; return index; } public void removeObjectFromForegroundList(ObiektPierwszegoPlanu opp) { opp.om = null; opp.OknoMapyListHandler = -1; this.foregroundList.remove(opp); } public int isValidCoords(Point p) { if (p.x >= foregroundTileGrid.size() || p.x < 0 || p.y >= foregroundTileGrid.get(0).size() || p.y < 0) { return -1; // out of bounds; } return 1; } public JLabel tileFromNumber(int num) { String path = "/images/" + num + ".png"; //System.out.println("path: " + path); ImageIcon ii = new ImageIcon(getClass().getResource(path)); JLabel jl = new JLabel(ii); jl.setSize(tileSize, tileSize); jl.setBackground(new Color(num)); //"optymalizacja": w polu Color trzymamy numer kratki. return jl; } public OknoMapy(LadowanieMapy lm) { this.lm = lm; /* Set native look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(OknoMapy.class.getName()).log(java.util.logging.Level.WARNING, null, ex); } //</editor-fold> initComponents(); this.tileSize = 32; this.defaultBorder = new BasicBorders.FieldBorder(Color.lightGray, new Color(0, true), new Color(0, true), new Color(0, true)); jCheckBoxMenuItem1.setSelected(false); mnInference = new JMenu("Pokaz wnioskowanie"); jMenuBar1.add(mnInference); mnWorldInference = new JMenuItem("swiat"); mnInference.add(mnWorldInference); addTileGridToWindow(createTileGrid(100, defaultBgTileID), overallBackgroundPanel); drawAllTiles(); bulkPanel.setPreferredSize(this.getSize()); contextPanel.setVisible(false); this.requestFocus(); } public ObiektPierwszegoPlanu nowyObiektPierwszegoPlanu(int x, int y, String id, int tileID) { if(isValidCoords(new Point(x, y)) == -1) { return null; } ObiektPierwszegoPlanu opp = new ObiektPierwszegoPlanu(x, y, id); opp.tile = this.tileFromNumber(tileID); if (getTileIDFromColor(foregroundTileGrid.get(y).get(x)) == 0) { this.getForegroundTileGrid().get(y).set(x, new TilesLabel(opp)); } else { ((TilesLabel) this.getForegroundTileGrid().get(y).get(x)).addObject(opp); } this.addObjectToForegroundList(opp); return opp; } public JLabel getTileAt(ArrayList<ArrayList<JLabel>> tileGrid, int tiledX, int tiledY) { return (tileGrid.get(tiledY)).get(tiledX); } public void setTileBorders(boolean on) { //FIXME: Tiles don't remove their borders for (int i = 0; i < foregroundTileGrid.size(); i++) { ArrayList<JLabel> arrayList = foregroundTileGrid.get(i); for (int j = 0; j < arrayList.size(); j++) { JLabel jLabel = arrayList.get(j); if (on) { jLabel.setBorder(defaultBorder); } else { jLabel.setBorder(BorderFactory.createEmptyBorder()); } jLabel.repaint(); } } this.drawAllTiles(); this.repaint(); } public void setTileAt(ArrayList<ArrayList<JLabel>> tileGrid, int tiledX, int tiledY, JLabel jl) { tileGrid.get(tiledY).get(tiledX).setIcon(jl.getIcon()); tileGrid.get(tiledY).get(tiledX).setBackground(jl.getBackground()); } public void drawAllTiles() { if (foregroundTileGrid != null) { addTileGridToWindow(foregroundTileGrid, foregroundPanel); } if (backgroundTileGrid != null) { addTileGridToWindow(backgroundTileGrid, backgroundPanel); } } public void importForegroundTileGrid(ArrayList<ArrayList<Integer>> arr) { ArrayList<ArrayList<JLabel>> tileGrid = new ArrayList<>(arr.size()); for (int i = 0; i < arr.size(); i++) { ArrayList<JLabel> tileGridRow = new ArrayList<>(arr.size()); for (int j = 0; j < arr.size(); j++) { int num = arr.get(i).get(j); JLabel jl = tileFromNumber(num); tileGridRow.add(jl); } tileGrid.add(tileGridRow); } this.foregroundTileGrid = tileGrid; } public void importBackgroundTileGrid(ArrayList<ArrayList<Integer>> arr) { ArrayList<ArrayList<JLabel>> tileGrid = new ArrayList<>(arr.size()); for (int i = 0; i < arr.size(); i++) { ArrayList<JLabel> tileGridRow = new ArrayList<>(arr.size()); for (int j = 0; j < arr.size(); j++) { int num = arr.get(i).get(j); JLabel jl = tileFromNumber(num); tileGridRow.add(jl); } tileGrid.add(tileGridRow); } this.backgroundTileGrid = tileGrid; } public ArrayList<ArrayList<JLabel>> createTileGrid(int size, int defaultTileNo) { ArrayList<ArrayList<JLabel>> tileGrid = new ArrayList<>(size); for (int i = 0; i < size; i++) { ArrayList<JLabel> tileGridRow = new ArrayList<>(size); for (int j = 0; j < size; j++) { int num = defaultTileNo; if (defaultTileNo == -1) { num = i * size + j; } //wszystkie obrazy po kolei JLabel jl = tileFromNumber(num); tileGridRow.add(jl); } tileGrid.add(tileGridRow); } return tileGrid; } private void addTileGridToWindow(ArrayList<ArrayList<JLabel>> tileGrid, JPanel targetPanel) { int size = tileGrid.size(); targetPanel.removeAll(); GridLayout gl = (GridLayout) targetPanel.getLayout(); if (tileGrid.size() > 0) { gl.setRows(tileGrid.size()); gl.setColumns(tileGrid.size()); targetPanel.setSize(size * tileSize, size * tileSize); } for (int i = 0; i < tileGrid.size(); i++) { ArrayList<JLabel> arrayList = tileGrid.get(i); for (int j = 0; j < arrayList.size(); j++) { targetPanel.add(arrayList.get(j)); } } } public void highlightVisibleFrames(Agent agent) { for (int x = -agent.getFieldOfView(); x <= agent.getFieldOfView(); x++ ) { for (int y = -agent.getFieldOfView(); y <= agent.getFieldOfView(); y++) { int yAfter = agent.getMapFrame().getY() + y; int xAfter = agent.getMapFrame().getX() + x; if (yAfter < this.backgroundTileGrid.size() && yAfter >= 0 && xAfter < this.backgroundTileGrid.get(0).size() && xAfter >=0) { this.backgroundTileGrid.get(yAfter).get(xAfter).setBorder(new LineBorder(new Color(185, 226, 18), 3, true)); } } } } public void deleteHighlightedBorders() { for (int x = 0; x < this.backgroundTileGrid.size(); x++ ) { for (int y = 0; y < this.backgroundTileGrid.get(0).size(); y++) { this.backgroundTileGrid.get(y).get(x).setBorder(null); } } } public void setScrollFocusOn(int x, int y) { JScrollBar vertical = jScrollPane1.getVerticalScrollBar(); vertical.setValue( y * this.tileSize - 5 * this.tileSize); JScrollBar horizontal = jScrollPane1.getHorizontalScrollBar(); horizontal.setValue( x * this.tileSize - 10 * this.tileSize); } public void displayInferenceResults(int x, int y, String header, String inferenceMessage, String type) { this.displayContextPanelWithInferenceResults(x, y, header, inferenceMessage, type); } public void displayBlockades(ArrayList<Blockade> blockades) { for (Blockade blockade : blockades) { int x = blockade.getMapFrame().getX(); int y = blockade.getMapFrame().getY(); blockade.setReplacedTile(this.backgroundTileGrid.get(y).get(x)); this.setTileAt(this.backgroundTileGrid, x, y, blockade.getTile()); } } public void hideBlockades(ArrayList<Blockade> blockades) { this.importBackgroundTileGrid(this.lm.getMap()); } public ArrayList<ArrayList<JLabel>> getForegroundTileGrid() { return foregroundTileGrid; } public ArrayList<ArrayList<JLabel>> getBackgroundTileGrid() { return backgroundTileGrid; } public void setForegroundTileGrid(ArrayList<ArrayList<JLabel>> foregroundTileGrid) { this.foregroundTileGrid = foregroundTileGrid; } public JPanel getForegroundPanel() { return foregroundPanel; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); bulkPanel = new javax.swing.JPanel(); contextPanel = new javax.swing.JPanel(); iconDisplayPanel = new javax.swing.JPanel(); tileInfoScrollPanel = new JScrollPane(); tileInfoPanelLabel1 = new javax.swing.JLabel(); foregroundPanel = new javax.swing.JPanel(); backgroundPanel = new javax.swing.JPanel(); overallBackgroundPanel = new javax.swing.JPanel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu3 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Polska, AD 1340"); setBackground(new java.awt.Color(102, 102, 102)); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setMinimumSize(new java.awt.Dimension(800, 600)); addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { formMouseClicked(evt); } }); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { formComponentResized(evt); } }); getContentPane().setLayout(null); bulkPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.CROSSHAIR_CURSOR)); bulkPanel.setLayout(null); contextPanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 4, true)); contextPanel.setOpaque(false); contextPanel.setLayout(new BoxLayout(contextPanel, BoxLayout.Y_AXIS)); contextPanel.setBounds(500, 270, 290, 180); contextPanelDefaultRect = new Rectangle(contextPanel.getBounds()); iconDisplayPanel.setBackground(new java.awt.Color(255, 255, 255)); iconDisplayPanel.setPreferredSize(new java.awt.Dimension(20, 50)); iconDisplayPanel.setLayout(new java.awt.GridLayout(1, 1)); contextPanel.add(iconDisplayPanel); tileInfoPanelLabel1.setText("jLabel1"); tileInfoPanelLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP); tileInfoScrollPanel.setViewportView(tileInfoPanelLabel1); contextPanel.add(tileInfoScrollPanel); bulkPanel.add(contextPanel); foregroundPanel.setOpaque(false); foregroundPanel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { foregroundPanelMouseClicked(evt); } }); browseDetailFrame = new JInternalFrame("Szczegoly"); browseDetailFrame.setBounds(0, 0, 700, 320); browseDetailFrame.setLocation(300, 100); getContentPane().add(browseDetailFrame); browseDetailFrame.getContentPane().setLayout(new BoxLayout(browseDetailFrame.getContentPane(), BoxLayout.Y_AXIS)); browseDetailFrame.setVisible(false); foregroundPanel.setLayout(new java.awt.GridLayout(1, 0)); bulkPanel.add(foregroundPanel); foregroundPanel.setBounds(0, 0, 750, 400); backgroundPanel.setForeground(new java.awt.Color(240, 240, 240)); backgroundPanel.setOpaque(false); backgroundPanel.setLayout(new java.awt.GridLayout(1, 0)); bulkPanel.add(backgroundPanel); backgroundPanel.setBounds(0, 0, 710, 410); overallBackgroundPanel.setForeground(new java.awt.Color(240, 240, 240)); overallBackgroundPanel.setLayout(new java.awt.GridLayout(1, 0)); bulkPanel.add(overallBackgroundPanel); overallBackgroundPanel.setBounds(0, 0, 620, 410); jScrollPane1.setViewportView(bulkPanel); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(0, 0, 680, 540); controlPanel = new JPanel(); controlPanel.setLayout(null); controlPanel.setBounds(683, 0, 101, 540); getContentPane().add(controlPanel); btnNextIter = new JButton("<html><center>Nastepna<br>iteracja</center></html>"); btnNextIter.setBounds(10, 11, 81, 92); btnNextIter.setFocusable(false); controlPanel.add(btnNextIter); btnNextAgent = new JButton("<html><center>Nastepny<br>agent</center></html>"); btnNextAgent.setBounds(10, 128, 81, 92); btnNextAgent.setFocusable(false); controlPanel.add(btnNextAgent); lblIteracja = new JLabel("ITERACJA"); lblIteracja.setBounds(13, 226, 78, 19); controlPanel.add(lblIteracja); lblAgent = new JLabel("AGENT"); lblAgent.setBounds(12, 278, 41, 19); controlPanel.add(lblAgent); textFieldIter = new JTextField(); textFieldIter.setBounds(8, 246, 86, 20); textFieldIter.setFocusable(false); textFieldIter.setEditable(false); controlPanel.add(textFieldIter); textFieldIter.setColumns(10); textFieldAgent = new JTextField(); textFieldAgent.setBounds(7, 299, 86, 20); textFieldAgent.setFocusable(false); textFieldAgent.setEditable(false); controlPanel.add(textFieldAgent); textFieldAgent.setColumns(10); lblBlockades = new JLabel("BLOKADY"); lblBlockades.setBounds(10, 330, 81, 19); controlPanel.add(lblBlockades); btnBlockades = new JButton("WYLACZONE"); btnBlockades.setFont(new Font("Tahoma", Font.PLAIN, 8)); btnBlockades.setForeground(Color.RED); btnBlockades.setBounds(10, 348, 83, 23); btnBlockades.setFocusable(false); btnBlockades.setToolTipText("<html>Po wlaczeniu/wylaczeniu przy NASTEPNEJ iteracji<br>" + "zostana wlaczone/wylaczone wylosowane blokady</html>"); controlPanel.add(btnBlockades); lblCataclysms = new JLabel("KLESKI"); lblCataclysms.setBounds(10, 378, 81, 19); controlPanel.add(lblCataclysms); btnCataclysms = new JButton("WYLACZONE"); btnCataclysms.setFont(new Font("Tahoma", Font.PLAIN, 8)); btnCataclysms.setForeground(Color.RED); btnCataclysms.setFocusable(false); btnCataclysms.setBounds(10, 396, 83, 23); btnCataclysms.setToolTipText("<html>Po wlaczeniu/wylaczeniu przy NASTEPNEJ iteracji<br>" + "zostana wlaczone/wylaczone wylosowane kleski<html>"); controlPanel.add(btnCataclysms); lblBandits = new JLabel("ROZBOJNICY"); lblBandits.setBounds(10, 426, 81, 19); controlPanel.add(lblBandits); btnBandits = new JButton("WYLACZONE"); btnBandits.setForeground(Color.RED); btnBandits.setFont(new Font("Tahoma", Font.PLAIN, 8)); btnBandits.setFocusable(false); btnBandits.setBounds(10, 444, 83, 23); btnBandits.setToolTipText("<html>Po wlaczeniu przy KAZDEJ iteracji<br>" + "beda losowani na nowo rozbojnicy<html>"); controlPanel.add(btnBandits); lblChangePrices = new JLabel("ZMIEN CENY"); lblChangePrices.setBounds(11, 476, 81, 19); controlPanel.add(lblChangePrices); btnChangePrices = new JButton("ZMIEN CENY"); btnChangePrices.setToolTipText("<html>Zmiena losowo ceny w kazdym grodzie z przedzialu (-7, 8)<html>"); btnChangePrices.setForeground(new Color(128, 128, 0)); btnChangePrices.setFont(new Font("Tahoma", Font.PLAIN, 8)); btnChangePrices.setFocusable(false); btnChangePrices.setBounds(11, 494, 83, 23); controlPanel.add(btnChangePrices); lblPricesChanged = new JLabel("zmieniono ceny"); lblPricesChanged.setForeground(new Color(0, 128, 0)); lblPricesChanged.setBounds(15, 517, 77, 19); lblPricesChanged.setVisible(false); controlPanel.add(lblPricesChanged); jMenu3.setText("Widok"); jMenuBar1.add(jMenu3); jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER, java.awt.event.InputEvent.ALT_MASK)); jMenuItem1.setText("Dopasuj do ekranu"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu3.add(jMenuItem1); jCheckBoxMenuItem1.setSelected(true); jCheckBoxMenuItem1.setText("Wyświetl siatkę"); jCheckBoxMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxMenuItem1ActionPerformed(evt); } }); jMenu3.add(jCheckBoxMenuItem1); mnBrowse = new JMenu("Przegladaj"); jMenuBar1.add(mnBrowse); mnBrowseAgents = new JMenu("agenci"); mnBrowse.add(mnBrowseAgents); mnBrowseTowns = new JMenu("grody"); mnBrowse.add(mnBrowseTowns); setJMenuBar(jMenuBar1); pack(); }// </editor-fold>//GEN-END:initComponents public void resizeContentsTo(Dimension d) { jScrollPane1.setPreferredSize(d); jScrollPane1.setSize(d); //przesuwam odpowiednio panel kontrolny this.controlPanel.setBounds(d.width, 0, this.controlPanel.getWidth(), this.controlPanel.getHeight()); if (this.backgroundTileGrid != null) { bulkPanel.setPreferredSize(new Dimension(this.tileSize * this.backgroundTileGrid.size(), this.tileSize * this.backgroundTileGrid.size())); } if (jScrollPane1.getHorizontalScrollBar() != null) { jScrollPane1.getHorizontalScrollBar().setUnitIncrement(tileSize / 2); } if (jScrollPane1.getVerticalScrollBar() != null) { jScrollPane1.getVerticalScrollBar().setUnitIncrement(tileSize / 2); } this.jScrollPane1.validate(); } private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized //nalezy takze uwzglednic panel kontrolny, ktory jest obok scroll panelu, //aby scroll panel nie nachodzil na panel kontrolny Dimension contentPanelDim = this.getContentPane().getSize(); Dimension controlPanelDim = this.controlPanel.getSize(); Dimension newDim = new Dimension(contentPanelDim.width - controlPanelDim.width, contentPanelDim.height); this.resizeContentsTo(newDim); }//GEN-LAST:event_formComponentResized private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed this.setExtendedState(Frame.MAXIMIZED_BOTH); }//GEN-LAST:event_jMenuItem1ActionPerformed private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked //TODO }//GEN-LAST:event_formMouseClicked public int getTileIDFromColor(JLabel tile) { return (tile.getBackground().getRGB() & 0xFFFFFF); } private void foregroundPanelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_foregroundPanelMouseClicked if (evt.getButton() == MouseEvent.BUTTON1) { //LMB Point pointClicked = evt.getPoint(); this.displayContextPanelWithTileInfo(pointClicked.x, pointClicked.y); } else if (evt.getButton() == MouseEvent.BUTTON3) { //RMB contextPanel.setVisible(false); ((JPanel) contextPanel.getComponent(0)).removeAll(); } }//GEN-LAST:event_foregroundPanelMouseClicked public void displayContextPanelWithTileInfo(int x, int y) { contextPanel.setVisible(false); ((JPanel) contextPanel.getComponent(0)).removeAll(); int tileX = x / this.tileSize; int tileY = y / this.tileSize; //klikniety tile tła JLabel clickedTile = this.backgroundTileGrid.get(tileY).get(tileX); int tileNum = getTileIDFromColor(clickedTile); contextPanel.setBounds(this.contextPanelDefaultRect); Rectangle rect = new Rectangle(x, y, contextPanel.getWidth(), contextPanel.getHeight()); if (rect.y > this.getContentPane().getHeight() - rect.height) { rect.y -= rect.height; } if (rect.x > this.getContentPane().getWidth() - rect.width) { rect.x -= rect.width; } contextPanel.setBounds(rect); JLabel iconForContextPanel = tileFromNumber(tileNum); iconForContextPanel.setHorizontalAlignment(JLabel.CENTER); iconForContextPanel.setVerticalAlignment(JLabel.CENTER); ((JPanel) contextPanel.getComponent(0)).add(iconForContextPanel); //klikniety tile pierwszego planu JLabel clickedFgTile = this.foregroundTileGrid.get(tileY).get(tileX); int tileFgNum = -1; //jesli klikniety tile jest typu TilesLabel to wtedy pobiramy liste obiektow, ktore tam sa //i wyswietlamy o nich informacje JLabel iconFgForContextPanel = new JLabel(clickedFgTile.getIcon()); if (!(clickedFgTile instanceof TilesLabel)) { tileFgNum = getTileIDFromColor(clickedFgTile); iconFgForContextPanel = tileFromNumber(tileFgNum); } else { if (((TilesLabel)clickedFgTile).getForegroundObjects().size() == 1) { tileFgNum = ((TilesLabel)clickedFgTile).getForegroundObjects().get(0).tile.getBackground().getRGB() & 0xFFFFFF; } } iconFgForContextPanel.setHorizontalAlignment(JLabel.CENTER); iconFgForContextPanel.setVerticalAlignment(JLabel.CENTER); ((JPanel) contextPanel.getComponent(0)).add(iconFgForContextPanel); JLabel opisIkony; opisIkony = new JLabel("<html><h3>Informacje o polu</h3></html>"); opisIkony.setBorder(new EmptyBorder(0, 8, 0, 0)); iconDisplayPanel.add(opisIkony); StringBuilder sb = new StringBuilder("<html>"); sb.append("Kliknięte pole: <pre>X: <b>").append(tileX).append("</b> Y: <b>").append(tileY).append("</b></pre>"); sb.append("<br/> "); sb.append("Warstwa obiektów:<br/>"); if (!(clickedFgTile instanceof TilesLabel)) { sb.append(tileFgNum).append(": <b>").append(InformacjeOSwiecie.getOpisKafelka(tileFgNum)).append("</b>"); } else { sb.append(tileFgNum).append(": <b>").append(((TilesLabel)clickedFgTile).getDescription()).append("</b>"); } sb.append("<br/>Warstwa tła:<br/>"); sb.append(tileNum).append(": <b>").append(InformacjeOSwiecie.getOpisKafelka(tileNum)).append("</b>"); sb.append("</html>"); tileInfoPanelLabel1.setText(sb.toString()); contextPanel.setVisible(true); } public void displayContextPanelWithInferenceResults(int x, int y, String header, String message, String type) { contextPanel.setVisible(false); ((JPanel) contextPanel.getComponent(0)).removeAll(); contextPanel.setBounds(this.contextPanelDefaultRect); Rectangle rect; if (type.equals("world")) { rect = new Rectangle(x, y, contextPanel.getWidth() + 110, contextPanel.getHeight() + 180); } else { rect = new Rectangle(x, y, contextPanel.getWidth() + 80, contextPanel.getHeight()); } if (rect.y > this.getContentPane().getHeight() - rect.height) { rect.y -= rect.height; } if (rect.x > this.getContentPane().getWidth() - rect.width) { rect.x -= rect.width; } contextPanel.setBounds(rect); JLabel opisIkony; opisIkony = new JLabel("<html><h3>" + header + "</h3></html>"); opisIkony.setBorder(new EmptyBorder(0, 8, 0, 0)); iconDisplayPanel.add(opisIkony); StringBuffer sb = new StringBuffer("<html>"); sb.append(message.replaceAll("\n", "<br>")); sb.append("</html>"); tileInfoPanelLabel1.setText(sb.toString()); contextPanel.setVisible(true); } private void jCheckBoxMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuItem1ActionPerformed this.isTileBordered = !this.isTileBordered; this.setTileBorders(isTileBordered); }//GEN-LAST:event_jCheckBoxMenuItem1ActionPerformed public javax.swing.JPanel getIconDisplayPanel() { return iconDisplayPanel; } public void setIconDisplayPanel(javax.swing.JPanel iconDisplayPanel) { this.iconDisplayPanel = iconDisplayPanel; } public javax.swing.JLabel getTileInfoPanelLabel1() { return tileInfoPanelLabel1; } public void setTileInfoPanelLabel1(javax.swing.JLabel tileInfoPanelLabel1) { this.tileInfoPanelLabel1 = tileInfoPanelLabel1; } public JButton getBtnNextIter() { return btnNextIter; } public void setBtnNextIter(JButton btnNextIter) { this.btnNextIter = btnNextIter; } public JButton getBtnNextAgent() { return btnNextAgent; } public void setBtnNextAgent(JButton btnNextAgent) { this.btnNextAgent = btnNextAgent; } public JTextField getTextFieldIter() { return textFieldIter; } public void setTextFieldIter(JTextField textFieldIter) { this.textFieldIter = textFieldIter; } public JTextField getTextFieldAgent() { return textFieldAgent; } public void setTextFieldAgent(JTextField textFieldAgent) { this.textFieldAgent = textFieldAgent; } public int getTileSize() { return tileSize; } public void setTileSize(int tileSize) { this.tileSize = tileSize; } public JButton getBtnBlockades() { return btnBlockades; } public void setBtnBlockades(JButton btnBlockades) { this.btnBlockades = btnBlockades; } public JButton getBtnCataclysms() { return btnCataclysms; } public void setBtnCataclysms(JButton btnCataclysms) { this.btnCataclysms = btnCataclysms; } public JButton getBtnBandits() { return btnBandits; } public void setBtnBandits(JButton btnBandits) { this.btnBandits = btnBandits; } public JButton getBtnChangePrices() { return btnChangePrices; } public void setBtnChangePrices(JButton btnChangePrices) { this.btnChangePrices = btnChangePrices; } public JLabel getLblPricesChanged() { return lblPricesChanged; } public void setLblPricesChanged(JLabel lblPricesChanged) { this.lblPricesChanged = lblPricesChanged; } public JMenu getMnBrowseAgents() { return mnBrowseAgents; } public void setMnBrowseAgents(JMenu mnBrowseAgents) { this.mnBrowseAgents = mnBrowseAgents; } public JMenu getMnBrowseTowns() { return mnBrowseTowns; } public void setMnBrowseTowns(JMenu mnBrowseTowns) { this.mnBrowseTowns = mnBrowseTowns; } public JMenu getMnBrowse() { return mnBrowse; } public void setMnBrowse(JMenu mnBrowse) { this.mnBrowse = mnBrowse; } public JInternalFrame getBrowseDetailFrame() { return browseDetailFrame; } public void setBrowseDetailFrame(JInternalFrame browseDetailFrame) { this.browseDetailFrame = browseDetailFrame; } public JMenuItem getMnWorldInference() { return mnWorldInference; } public void setMnWorldInference(JMenuItem mnWorldInference) { this.mnWorldInference = mnWorldInference; } public javax.swing.JPanel getContextPanel() { return contextPanel; } public void setContextPanel(javax.swing.JPanel contextPanel) { this.contextPanel = contextPanel; } }
package com.example.jiyushi1.dis.ws.local; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.Map; /** * Created by Joe on 7/28/2015. */ public class HttpDBServer extends Thread{ private URL url = null; private Map<String, String> params; private String encode; private int requestType; public String result = null; public static Object locker = new Object(); public HttpDBServer(Map<String, String> params, String encode,int requestType){ this.params = params; this.encode = encode; this.requestType = requestType; } public String getResult(){ return result; } public void run(){ String IP = "***.***.***.**:8080/"; switch (requestType) { case 1: //case sign up try { url = new URL("http://"+IP+ "Discount_Server/Sign_up_customer"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 2: //case log in try { url = new URL("http://"+IP+"Discount_Server/Sign_up_seller"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 3: try { url = new URL("http://"+IP+"Discount_Server/Login"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 4: try { url = new URL("http://"+IP+"Discount_Server/Search_sellers"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 5: try { url = new URL("http://"+IP+"Discount_Server/Search_products"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 6: try { url = new URL("http://"+IP+"Discount_Server/Read_a_customer"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 7: try { url = new URL("http://"+IP+"Discount_Server/Edit_a_customer"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 8: try { url = new URL("http://"+IP+"Discount_Server/Change_password"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 9: try { url = new URL("http://"+IP+"Discount_Server/Seller_get_product"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 10: try { url = new URL("http://"+IP+"Discount_Server/Edit_a_product"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 11: try { url = new URL("http://"+IP+"Discount_Server/Delete_a_product"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 12: try { url = new URL("http://"+IP+"Discount_Server/Add_a_product"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 13: try { url = new URL("http://"+IP+"Discount_Server/Seller_discount_barn"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 21: try { url = new URL("http://"+IP+"Discount_Server/Read_a_seller"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; case 22: try { url = new URL("http://"+IP+"Discount_Server/Edit_a_seller"); } catch (MalformedURLException e) { e.printStackTrace(); } result = submitPostData(params, encode); break; } } public String submitPostData(Map<String, String> params, String encode) { byte[] data = getRequestData(params, encode).toString().getBytes(); try { HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(10000); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length)); OutputStream outputstream = httpURLConnection.getOutputStream(); outputstream.write(data); //String test = params.get("shoptype"); //Log.e("TYPE IN USER TYPE", test); int response = httpURLConnection.getResponseCode(); //Get Response Code if (response == HttpURLConnection.HTTP_OK) { InputStream inptStream = httpURLConnection.getInputStream(); return dealResponseResult(inptStream); // Deal Response } } catch (IOException e) { e.printStackTrace(); } return "Internet Disconnected"; } protected StringBuffer getRequestData(Map<String, String> params, String encode) { StringBuffer stringBuffer = new StringBuffer(); try { for(Map.Entry<String, String> entry : params.entrySet()) { stringBuffer.append(entry.getKey()) .append("=") .append(URLEncoder.encode(entry.getValue(), encode)) .append("&"); } stringBuffer.deleteCharAt(stringBuffer.length() - 1); } catch (Exception e) { e.printStackTrace(); } return stringBuffer; } protected String dealResponseResult(InputStream inputStream) { String resultData = null; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; try { while ((len = inputStream.read(data)) != -1) { byteArrayOutputStream.write(data, 0, len); } } catch (IOException e) { e.printStackTrace(); } resultData = new String(byteArrayOutputStream.toByteArray()); return resultData; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.transaction.interceptor; import java.lang.reflect.Method; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.ReactiveTransaction; import org.springframework.transaction.ReactiveTransactionManager; import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.UnexpectedRollbackException; import org.springframework.transaction.reactive.TransactionContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * Abstract support class to test {@link TransactionAspectSupport} with reactive methods. * * @author Mark Paluch * @author Juergen Hoeller */ public abstract class AbstractReactiveTransactionAspectTests { protected Method getNameMethod; protected Method setNameMethod; protected Method exceptionalMethod; @BeforeEach public void setup() throws Exception { getNameMethod = TestBean.class.getMethod("getName"); setNameMethod = TestBean.class.getMethod("setName", String.class); exceptionalMethod = TestBean.class.getMethod("exceptional", Throwable.class); } @Test public void noTransaction() throws Exception { ReactiveTransactionManager rtm = mock(); DefaultTestBean tb = new DefaultTestBean(); TransactionAttributeSource tas = new MapTransactionAttributeSource(); // All the methods in this class use the advised() template method // to obtain a transaction object, configured with the when PlatformTransactionManager // and transaction attribute source TestBean itb = (TestBean) advised(tb, rtm, tas); checkReactiveTransaction(false); itb.getName(); checkReactiveTransaction(false); // expect no calls verifyNoInteractions(rtm); } /** * Check that a transaction is created and committed. */ @Test public void transactionShouldSucceed() throws Exception { TransactionAttribute txatt = new DefaultTransactionAttribute(); MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(getNameMethod, txatt); ReactiveTransaction status = mock(); ReactiveTransactionManager rtm = mock(); // expect a transaction given(rtm.getReactiveTransaction(txatt)).willReturn(Mono.just(status)); given(rtm.commit(status)).willReturn(Mono.empty()); DefaultTestBean tb = new DefaultTestBean(); TestBean itb = (TestBean) advised(tb, rtm, tas); itb.getName() .as(StepVerifier::create) .verifyComplete(); verify(rtm).commit(status); } /** * Check that two transactions are created and committed. */ @Test public void twoTransactionsShouldSucceed() throws Exception { TransactionAttribute txatt = new DefaultTransactionAttribute(); MapTransactionAttributeSource tas1 = new MapTransactionAttributeSource(); tas1.register(getNameMethod, txatt); MapTransactionAttributeSource tas2 = new MapTransactionAttributeSource(); tas2.register(setNameMethod, txatt); ReactiveTransaction status = mock(); ReactiveTransactionManager rtm = mock(); // expect a transaction given(rtm.getReactiveTransaction(txatt)).willReturn(Mono.just(status)); given(rtm.commit(status)).willReturn(Mono.empty()); DefaultTestBean tb = new DefaultTestBean(); TestBean itb = (TestBean) advised(tb, rtm, new TransactionAttributeSource[] {tas1, tas2}); itb.getName() .as(StepVerifier::create) .verifyComplete(); Mono.from(itb.setName("myName")) .as(StepVerifier::create) .verifyComplete(); verify(rtm, times(2)).commit(status); } /** * Check that a transaction is created and committed. */ @Test public void transactionShouldSucceedWithNotNew() throws Exception { TransactionAttribute txatt = new DefaultTransactionAttribute(); MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(getNameMethod, txatt); ReactiveTransaction status = mock(); ReactiveTransactionManager rtm = mock(); // expect a transaction given(rtm.getReactiveTransaction(txatt)).willReturn(Mono.just(status)); given(rtm.commit(status)).willReturn(Mono.empty()); DefaultTestBean tb = new DefaultTestBean(); TestBean itb = (TestBean) advised(tb, rtm, tas); itb.getName() .as(StepVerifier::create) .verifyComplete(); verify(rtm).commit(status); } @Test public void rollbackOnCheckedException() throws Throwable { doTestRollbackOnException(new Exception(), true, false); } @Test public void noRollbackOnCheckedException() throws Throwable { doTestRollbackOnException(new Exception(), false, false); } @Test public void rollbackOnUncheckedException() throws Throwable { doTestRollbackOnException(new RuntimeException(), true, false); } @Test public void noRollbackOnUncheckedException() throws Throwable { doTestRollbackOnException(new RuntimeException(), false, false); } @Test public void rollbackOnCheckedExceptionWithRollbackException() throws Throwable { doTestRollbackOnException(new Exception(), true, true); } @Test public void noRollbackOnCheckedExceptionWithRollbackException() throws Throwable { doTestRollbackOnException(new Exception(), false, true); } @Test public void rollbackOnUncheckedExceptionWithRollbackException() throws Throwable { doTestRollbackOnException(new RuntimeException(), true, true); } @Test public void noRollbackOnUncheckedExceptionWithRollbackException() throws Throwable { doTestRollbackOnException(new RuntimeException(), false, true); } /** * Check that the when exception thrown by the target can produce the * desired behavior with the appropriate transaction attribute. * @param ex exception to be thrown by the target * @param shouldRollback whether this should cause a transaction rollback */ @SuppressWarnings("serial") protected void doTestRollbackOnException( final Exception ex, final boolean shouldRollback, boolean rollbackException) throws Exception { TransactionAttribute txatt = new DefaultTransactionAttribute() { @Override public boolean rollbackOn(Throwable t) { assertThat(t).isSameAs(ex); return shouldRollback; } }; Method m = exceptionalMethod; MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(m, txatt); ReactiveTransaction status = mock(); ReactiveTransactionManager rtm = mock(); // Gets additional call(s) from TransactionControl given(rtm.getReactiveTransaction(txatt)).willReturn(Mono.just(status)); TransactionSystemException tex = new TransactionSystemException("system exception"); if (rollbackException) { if (shouldRollback) { given(rtm.rollback(status)).willReturn(Mono.error(tex)); } else { given(rtm.commit(status)).willReturn(Mono.error(tex)); } } else { given(rtm.commit(status)).willReturn(Mono.empty()); given(rtm.rollback(status)).willReturn(Mono.empty()); } DefaultTestBean tb = new DefaultTestBean(); TestBean itb = (TestBean) advised(tb, rtm, tas); itb.exceptional(ex) .as(StepVerifier::create) .expectErrorSatisfies(actual -> { if (rollbackException) { assertThat(actual).isEqualTo(tex); } else { assertThat(actual).isEqualTo(ex); } }).verify(); if (!rollbackException) { if (shouldRollback) { verify(rtm).rollback(status); } else { verify(rtm).commit(status); } } } /** * Simulate a transaction infrastructure failure. * Shouldn't invoke target method. */ @Test public void cannotCreateTransaction() throws Exception { TransactionAttribute txatt = new DefaultTransactionAttribute(); Method m = getNameMethod; MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(m, txatt); ReactiveTransactionManager rtm = mock(); // Expect a transaction CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null); given(rtm.getReactiveTransaction(txatt)).willThrow(ex); DefaultTestBean tb = new DefaultTestBean() { @Override public Mono<String> getName() { throw new UnsupportedOperationException( "Shouldn't have invoked target method when couldn't create transaction for transactional method"); } }; TestBean itb = (TestBean) advised(tb, rtm, tas); itb.getName() .as(StepVerifier::create) .expectError(CannotCreateTransactionException.class) .verify(); } /** * Simulate failure of the underlying transaction infrastructure to commit. * Check that the target method was invoked, but that the transaction * infrastructure exception was thrown to the client */ @Test public void cannotCommitTransaction() throws Exception { TransactionAttribute txatt = new DefaultTransactionAttribute(); Method m = setNameMethod; MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(m, txatt); // Method m2 = getNameMethod; // No attributes for m2 ReactiveTransactionManager rtm = mock(); ReactiveTransaction status = mock(); given(rtm.getReactiveTransaction(txatt)).willReturn(Mono.just(status)); UnexpectedRollbackException ex = new UnexpectedRollbackException("foobar", null); given(rtm.commit(status)).willReturn(Mono.error(ex)); given(rtm.rollback(status)).willReturn(Mono.empty()); DefaultTestBean tb = new DefaultTestBean(); TestBean itb = (TestBean) advised(tb, rtm, tas); String name = "new name"; Mono.from(itb.setName(name)) .as(StepVerifier::create) .verifyErrorSatisfies(actual -> assertThat(actual).isEqualTo(ex)); // Should have invoked target and changed name itb.getName() .as(StepVerifier::create) .expectNext(name) .verifyComplete(); } private void checkReactiveTransaction(boolean expected) { Mono.deferContextual(Mono::just) .handle((context, sink) -> { if (context.hasKey(TransactionContext.class) != expected) { fail("Should have thrown NoTransactionException"); } sink.complete(); }) .block(); } protected Object advised( Object target, ReactiveTransactionManager rtm, TransactionAttributeSource[] tas) throws Exception { return advised(target, rtm, new CompositeTransactionAttributeSource(tas)); } /** * Subclasses must implement this to create an advised object based on the * when target. In the case of AspectJ, the advised object will already * have been created, as there's no distinction between target and proxy. * In the case of Spring's own AOP framework, a proxy must be created * using a suitably configured transaction interceptor * @param target the target if there's a distinct target. If not (AspectJ), * return target. * @return transactional advised object */ protected abstract Object advised( Object target, ReactiveTransactionManager rtm, TransactionAttributeSource tas) throws Exception; public interface TestBean { Mono<String> getName(); Publisher<Void> setName(String name); Mono<Void> exceptional(Throwable t); } public class DefaultTestBean implements TestBean { private String name; @Override public Mono<String> getName() { return Mono.justOrEmpty(name); } @Override public Publisher<Void> setName(String name) { return Mono.fromRunnable(() -> this.name = name); } @Override public Mono<Void> exceptional(Throwable t) { if (t != null) { return Mono.error(t); } return Mono.empty(); } } }
package be.tarsos.dsp.example; import be.tarsos.dsp.AudioEvent; import be.tarsos.dsp.AudioProcessor; public class AmplitudeProcessor implements AudioProcessor, AutoBand.OnUpdateBands{ private Client client; private float pitch = 0; private float offset = 0; private float multiply = 1; private float brightnessOffset = 0; private GraphPanel graphPanel; private GraphPanel normalGraph; private boolean automate = true; private AutoBand autoBand = new AutoBand(this); private LEDColor currentColor = new LEDColor(1, 1, 1); private int pitchIndex = 0; public AutoBand getAutoBand() { return autoBand; } public void setAutoBand(AutoBand autoBand) { this.autoBand = autoBand; } public float getBrightnessOffset() { return brightnessOffset; } public void setBrightnessOffset(float brightnessOffset) { this.brightnessOffset = brightnessOffset; } public boolean isAutomate() { return automate; } public void setAutomate(boolean automate) { this.automate = automate; } public GraphPanel getNormalGraph() { return normalGraph; } public void setNormalGraph(GraphPanel normalGraph) { this.normalGraph = normalGraph; } public float getPitch() { return pitch; } public void setPitch(float pitch) { this.pitch = pitch; //randomColor = getRandomColor(randomColor); //Get new color on pitch change. } public AmplitudeProcessor(Client client, GraphPanel graphPanel){ this.client = client; this.graphPanel = graphPanel; } public GraphPanel getGraphPanel() { return graphPanel; } public void setGraphPanel(GraphPanel graphPanel) { this.graphPanel = graphPanel; } public LEDColor getRandomColor(LEDColor notThisOne){ LEDColor randLED = notThisOne; while(randLED.equals(notThisOne)){ int rand = randomWithRange(1, 6); switch(rand){ case 1: randLED = new LEDColor(1, 0, 0); break; case 2: randLED = new LEDColor(0, 1, 0); break; case 3: randLED = new LEDColor(0, 0, 1); break; case 4: randLED = new LEDColor(1, 1, 0); break; case 5: randLED = new LEDColor(1, 0, 1); break; default: randLED = new LEDColor(0, 1, 1); } } return randLED; } int randomWithRange(int min, int max) { int range = (max - min) + 1; return (int)(Math.random() * range) + min; } @Override public boolean process(AudioEvent audioEvent) { // TODO Auto-generated method stub float[] data = audioEvent.getFloatBuffer(); float volume = 0; //1 being loudest for(int i = 0; i < data.length; i++){ float value = data[i]; if(value > volume){ volume = value; } } volume = Math.min(1, volume); volume = Math.max(0, volume); if(normalGraph != null){ normalGraph.addScore(volume * 100); autoBand.newVolume(volume); } float exagVolume; exagVolume = (multiply * volume) - offset; exagVolume = Math.min(1, exagVolume); exagVolume = Math.max(0, exagVolume); exagVolume = exagVolume / (100 / Math.max(1, brightnessOffset * 100)); if(graphPanel != null){ graphPanel.addScore(exagVolume * 100); } if(exagVolume > 1 || exagVolume < 0){ System.out.println(exagVolume); System.exit(0); } //System.out.println("Amplitude : " + maxValue); int brightness = Math.round(exagVolume * 255); brightness = (int) Math.round(Math.pow(brightness, 2) / 255); int currPitchIndex = getPitchIndex(pitch); if(currPitchIndex != pitchIndex){ pitchIndex = currPitchIndex; currentColor = getRandomColor(currentColor); } LEDColor color = new LEDColor(currentColor.getRed() * brightness, currentColor.getGreen() * brightness, currentColor.getBlue() * brightness); sendColor(color); return true; } public int getPitchIndex(float pitch){ if(pitch <= 80){ return 1; }else if(pitch <= 160){ return 2; }else if(pitch <= 320){ return 3; }else if(pitch <= 480){ return 4; }else if(pitch <= 640){ return 5; }else if(pitch <= 800){ return 6; }else if(pitch <= 1600){ return 7; }else if(pitch <= 3200){ return 8; }else{ return 9; } } public void setMinMaxValues(float max, float min){ if(max < min) return; multiply = 1 / (max - min); offset = min * multiply; if(normalGraph != null){ normalGraph.setUpperBand(max); normalGraph.setLowerBand(min); } } public void setMinValue(float min){ float max = getMaxValue(); setMinMaxValues(max, min); } public void setMaxValue(float max){ float min = getMinValue(); setMinMaxValues(max, min); } public float getMinValue(){ return offset / multiply; } public float getMaxValue(){ return (1 / multiply) + getMinValue(); } public void sendColor(LEDColor color){ client.sendColor(color); } @Override public void processingFinished() { // TODO Auto-generated method stub } @Override public void updateBands(float max, float min, float lowerSpacing, float upperSpacing) { // TODO Auto-generated method stub if(automate){ normalGraph.setUpperBand(max); normalGraph.setLowerBand(min); normalGraph.setLowerSpacing(lowerSpacing); normalGraph.setUpperSpacing(upperSpacing); setMinMaxValues(max, min); } } }
package pl.com.nur.springsecurityemailverification.model; public enum AppRole { USER, ADMIN; public String getName(){ return this.name(); } }
package cn.algerfan; /** * 343. 整数拆分 * 给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。 * <p> * 示例 1: * 输入: 2 * 输出: 1 * 解释: 2 = 1 + 1, 1 × 1 = 1。 * 示例 2: * 输入: 10 * 输出: 36 * 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。 * 说明: 你可以假设 n 不小于 2 且不大于 58。 * * @author algerfan */ public class LeetCode343 { public static void main(String[] args) { System.out.println(new LeetCode343().integerBreak2(10)); } /** * 1. 暴力递归(超时) * @param n */ public int integerBreak1(int n) { if (n == 1) { return 1; } int res = -1; for (int i = 1; i < n; i++) { // 分割成 i + (n - i) // integerBreak1(int n)中的n至少分割两部分,因此还需要计算 i * (n - i) res = max3(res, i * (n - i), i * integerBreak1(n - i)); } return res; } private static int max3(int a, int b, int c) { return Math.max(a, Math.max(b, c)); } /** * 2. 记忆化搜索 * @param n */ public int integerBreak2(int n) { int[] memo = new int[2 * n]; return breakBreak2(n, memo); } private int breakBreak2(int n, int[] memo) { if (n == 1) { return 1; } if(memo[n] != 0) { return memo[n]; } int res = -1; for (int i = 1; i < n; i++) { // 分割成 i + (n - i) // integerBreak1(int n)中的n至少分割两部分,因此还需要计算 i * (n - i) res = max3(res, i * (n - i), i * breakBreak2(n - i, memo)); } memo[n] = res; return res; } /** * 3. 动态规划 * @param n */ public int integerBreak3(int n) { int[] dp = new int[n + 1]; dp[1] = 1; for (int i = 2; i <= n; i++) { for (int j = 1; j < i; j++) { dp[i] = Math.max(dp[i], (Math.max(j, dp[j])) * (Math.max(i - j, dp[i - j]))); } } return dp[n]; } /** * 4. 最佳方案,列出可能的情况,发现规律,巧妙解题 * 分析: * 根据题目设定的条件整数n的取值范围为: 2<=n<=58 * 分析一下: * 当n=2时: n=1+1; result = 1*1=1 * 当n=3时:可以拆分为: 1+2 或者 1+1+1,但是显然拆分为 1+2,所获得的乘积最大 * 当n=4时:可以拆分为:1+3 或者 2+2,但是显然拆分为 2+2,所获得的乘积最大 * 当n=5时:可以拆分为:2+3,所获得乘积最大 * 当n=6时:可以拆分为:3+3,所获得乘积最大 * 当n=7时:可以拆分为:3+4,所获得乘积最大 * 当n=8时:可以拆分为:3+3+2,所获得乘积最大 * 当n=9时:可以拆分为:3+3+3,所获得乘积最大 * 当n=10时:可以拆分为:3+3+4,所获得乘积最大 * 通过观察上述内容,我们可以发现从n=5开始,拆分的结果都有数字3。 * 之后的数字,例如11,可以先拆出来1个3,然后再看余下的8如何拆分。 */ public int integerBreak4(int n) { if (n == 2 || n == 3) { return n - 1; } if (n == 4) { return n; } int result = 1; while (n > 4) { result *= 3; n -= 3; } return result * n; } }
package org.levelup.web.controllers; import org.levelup.model.Category; import org.levelup.repositories.CategoryRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.security.Principal; import java.util.List; import java.util.stream.Collectors; import static org.levelup.web.AppConstants.INDEX; import static org.levelup.web.AppConstants.REDIRECT; @Controller public class MainController { @Autowired CategoryRepository categories; @GetMapping("/") public String mainPage(Principal principal, Model model) { if (principal != null) { model.addAttribute("username", principal.getName()); } model.addAttribute("private_categories", categories.findPrivateCategories(getPage()).toList()); model.addAttribute("public_categories", categories.findPublicCategories(getPage()).toList()); return INDEX; } @GetMapping("/log-out") public String logOut(Model model) { model.addAttribute("username",null); return REDIRECT; } private PageRequest getPage() { return PageRequest.of(0, 10); } private List<Category> toList(Page<Category> categoryPage) { return categoryPage.get().collect(Collectors.toList()); } }
package br.com.tt.petshop.client; import br.com.tt.petshop.exception.ErroNegocioException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestTemplate; @Component// ou @Service public class CreditoRestTemplateClient { private final RestTemplate restTemplate; private final String creditoUrl; public CreditoRestTemplateClient(RestTemplate restTemplate, @Value("${app.servicos.credito.url}") String creditoUrl) { this.restTemplate = restTemplate; this.creditoUrl = creditoUrl; } /* Retorno esperado: {"situacao":"NEGATIVADO","pontos":-679} */ public CreditoDto consultaSituacaoCpf(String cpf) { //ResponseEntity<CreditoDto> retorno = restTemplate.getForEntity(url, CreditoDto.class); //String headerToken = retorno.getHeaders().getFirst("Authorization"); //return retorno.getBody(); try { return restTemplate.getForObject(creditoUrl, CreditoDto.class, cpf); }catch (HttpClientErrorException e){ if(e.getStatusCode().ordinal() == 422){ throw new ErroNegocioException("erro_externo", e.getResponseBodyAsString()); } throw new ErroNegocioException("erro_externo", "Erro desconhecido!"); }catch (HttpServerErrorException e){ throw new ErroNegocioException("erro_externo", "Ocorreu um erro na chamada a api de crédito!"); } } }
package org.giveback.dscbanasthali.graph; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class AdjMatrixGraph { private final boolean[][] adjMatrix; private final int vertexCount; public AdjMatrixGraph(int vertexCount) { this.vertexCount = vertexCount; adjMatrix = new boolean[vertexCount][vertexCount]; } private static void print(String v) { System.out.println(v); } private boolean isOutOfBounds(int row, int col) { return row < 0 && row > vertexCount && col < 0 && col > vertexCount; } public void addEdge(int vertex1, int vertex2) { if (isOutOfBounds(vertex1, vertex2)) { return; } adjMatrix[vertex1][vertex2] = true; adjMatrix[vertex2][vertex1] = true; } public void removeEdge(int vertex1, int vertex2) { if (isOutOfBounds(vertex1, vertex2)) { return; } adjMatrix[vertex1][vertex2] = false; adjMatrix[vertex2][vertex1] = false; } public boolean isEdge(int vertex1, int vertex2) { if (isOutOfBounds(vertex1, vertex2)) { return false; } return adjMatrix[vertex1][vertex2]; } public void bfs() { AdjVertex[] vertices = new AdjVertex[vertexCount]; Queue<Integer> q = new LinkedList<>(); // First element. vertices[0].isVisited = true; print(vertices[0].label); q.offer(0); while(!q.isEmpty()) { int vertex = q.poll(); int nextVertex; while((nextVertex = getUnvisitedVertex(vertex, vertices) )!= -1){ vertices[nextVertex].isVisited = true; print(vertices[nextVertex].label); q.offer(nextVertex); } } } private int getUnvisitedVertex(int v, AdjVertex[] vertices) { for(var index = 0; index < vertexCount; index++) { if(adjMatrix[v][index] && !vertices[index].isVisited) { return index; } } return -1; } public void dfs() { AdjVertex[] vertices = new AdjVertex[vertexCount]; Stack<Integer> stack = new Stack<>(); print(vertices[0].label); stack.push(0); while(!stack.isEmpty()) { int vertex = stack.peek(); int nextVertex = getUnvisitedVertex(vertex, vertices); if(nextVertex == -1) { stack.pop(); continue; } vertices[nextVertex].isVisited = true; print(vertices[nextVertex].label); stack.push(nextVertex); } } } class AdjVertex { public String label; public boolean isVisited; public AdjVertex(String label, boolean isVisited) { this.label = label; this.isVisited = isVisited; } }
package com.carlos.theculinaryapp; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.GridView; import android.widget.ListAdapter; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import java.util.ArrayList; public class SearchRecipe extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private ListAdapter customListAdapterRecipes; private GridView customListView; private GenericDAO dao = GenericDAO.getInstance(); private FirebaseAuth auth = dao.getFirebaseAuth(); private FirebaseUser user = auth.getCurrentUser(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_recipe); customListView = (GridView) findViewById(R.id.result_list_search_recipe); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view_search_recipe); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { super.onBackPressed(); this.finish(); } public void updateResultView(ArrayList<RecipeItem> recipeItems){ RecipeItem[] items = new RecipeItem[recipeItems.size()]; for (int i = 0; i < recipeItems.size(); i++) { items[i] = recipeItems.get(i); } customListAdapterRecipes = new CustomAdapterRecipe(this, items); customListView.setAdapter(customListAdapterRecipes); customListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { RecipeItem i = (RecipeItem)customListView.getItemAtPosition(position); Intent k = new Intent(SearchRecipe.this, RecipeActivity.class); k.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); k.putExtra("recipeUuid", i.getRecipeUuid()); startActivity(k); } }); } public void onSearchButtonClick(View view){ EditText queryInput = (EditText) findViewById(R.id.search_recipe_input); String query = String.valueOf(queryInput.getText()); Log.e(SearchRecipe.class.getName(), query); dao.searchRecipesByText(query, this); } private void doLogout() { auth.signOut(); Intent k = new Intent(SearchRecipe.this, LoginActivity.class); k.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); k.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); k.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(k); finish(); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); if (id == R.id.nav_go_to_your_own_profile) { Intent k = new Intent(new Intent(getApplicationContext(), ProfileActivity.class)); k.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); k.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); k.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); k.putExtra("userUuid", user.getUid()); startActivity(k); }else if (id == R.id.nav_search_for_profile) { startActivity(new Intent(getApplicationContext(), SearchProfile.class)); }else if (id == R.id.nav_search_for_ingredient){ }else if (id == R.id.nav_create_recipe){ }else if (id == R.id.nav_logout){ doLogout(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.activity_drawer_layout_search_profile); drawer.closeDrawer(GravityCompat.START); return true; } }
package Model.impl; import Bean.Message; import Configure.RouterAndHostConfigure; import Listener.RouterAndHostMomentStrListener; import Model.IHost; import Util.PrintUtil; import Util.RandomUtil; import java.util.*; import java.util.concurrent.*; /** * @author dmrfcoder * @date 2019-04-15 */ public class Host implements IHost { private String ip; private ArrayList<String> ips; private int sentCount; private RouterInterface routerInterface; private int processId; private ScheduledExecutorService scheduledExecutorService; private RouterAndHostMomentStrListener routerAndHostMomentStrListener; public void setRouterInterface(RouterInterface routerInterface) { this.routerInterface = routerInterface; } public RouterInterface getRouterInterface() { return routerInterface; } public String getIp() { return ip; } public void setIps(ArrayList<String> ips) { ips.remove(ip); this.ips = ips; } public Host(String ip) { PrintUtil.printLn("初始化主机:" + ip); this.ip = ip; sentCount = 0; RandomUtil.getInstance().addIpToIps(ip); } public void setRouterAndHostMomentStrListener(RouterAndHostMomentStrListener routerAndHostMomentStrListener) { this.routerAndHostMomentStrListener = routerAndHostMomentStrListener; } @Override public boolean outputMessage() { try { ArrayList<Message> messageArrayList = buildMessages(RouterAndHostConfigure.messageCountSentPerSecondOfHost); for (Message message : messageArrayList) { if (routerInterface.inputMessage(message)) { routerAndHostMomentStrListener.addMomentStrToHostQueue(ip, "发送报文到主机:" + message.getTargetAddress(), 1); //发送成功 } else { //发送失败,因为路由器存储器容量不够了 routerAndHostMomentStrListener.addMomentStrToHostQueue(ip, "发送报文到主机:" + message.getTargetAddress() + "失败!", 2); } } } catch (Exception e) { System.out.println("Exception-outputMessage:" + e.getLocalizedMessage()); } return true; } @Override public boolean outputMessageProxy() { boolean res = false; try { res = outputMessage(); } catch (Exception e) { PrintUtil.printLn("Exception-outputMessageProxy:" + e.getLocalizedMessage()); } return res; } @Override public boolean inputMessage(Message message) { routerAndHostMomentStrListener.addMomentStrToHostQueue(ip, "收到来自主机:" + message.getOriginIp() + "的报文", 0); return true; } @Override public ArrayList<Message> buildMessages(int messageCount) { ArrayList<Message> messageArrayList = new ArrayList<>(); RandomUtil randomUtil = RandomUtil.getInstance(); for (int index = 0; index < messageCount; index++) { Message message = new Message(processId, randomUtil.getRandomPort(), sentCount++, ip, randomUtil.getRandomIpForSendMessage(ip), randomUtil.getRandomMessageContent()); messageArrayList.add(message); } return messageArrayList; } @Override public void startSendMessage() { scheduledExecutorService = new ScheduledThreadPoolExecutor(1); scheduledExecutorService.scheduleWithFixedDelay(this::outputMessageProxy, 0, RouterAndHostConfigure.periodOfHostSendMessage, TimeUnit.MICROSECONDS); PrintUtil.printLn("启动主机" + ip + "的发送信息线程"); } @Override public void stopSendMessage() { scheduledExecutorService.shutdown(); PrintUtil.printLn("停止主机" + ip + "的发送信息线程"); } }
package org.wuxinshui.boosters.designPatterns.singleton; /** * Created with IntelliJ IDEA. * User: FujiRen * Date: 2016/11/11 * Time: 7:31 * To change this template use File | Settings | File Templates. */ //饿汉模式 public class HungrySingleton { //利用静态变量来记录singleton的唯一实例 private final static HungrySingleton uniqueInstance=new HungrySingleton(); /** * 构造器私有化,只有singleton内部才可以调用 * 确保不会被其他代码实例化 */ private HungrySingleton(){ System.out.println("HungrySingleton is create"); } public static HungrySingleton getInstance(){ return uniqueInstance; } //其他角色 public static void createString(){ System.out.println("createString in HungrySingleton"); } public static void main(String[] args) { HungrySingleton.createString(); } }
package lk.ac.mrt.cse.mscresearch.remoting; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import lk.ac.mrt.cse.mscresearch.remoting.dto.ClassDTO; import lk.ac.mrt.cse.mscresearch.remoting.dto.JarDTO; public interface ByteCodePersistor { boolean isJarIndexed(String hash); Set<JarDTO> getIndexedJars(Set<JarDTO> jars); void indexJar(JarDTO jar); Map<String, ClassDTO> getIndexedClasses(Set<ClassDTO> classes); Map<String, ClassDTO> getIndexedClasses(Collection<String> values); ClassDTO indexClass(ClassDTO classDTO); List<ClassDTO> indexClasses(List<ClassDTO> classDTO); Map<String, Boolean> isIndexed(Set<String> jarHashes); }
package com.rev.dao; import java.io.Serializable; import java.util.List; public interface GenericRepository<T> { Serializable save(T t); List<T> findAll(); T findById(Serializable id); boolean update(T t); boolean deleteById(Serializable id); }
package Tools; import java.awt.AWTException; import java.awt.Color; import java.awt.Dimension; import java.awt.DisplayMode; import java.awt.Graphics2D; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.DataBufferInt; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import java.awt.image.ImageProducer; import java.awt.image.RGBImageFilter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.UnknownFormatConversionException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.WindowConstants; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.imgcodecs.Imgcodecs; public class Tools { public static Robot robot; static { try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); } } public static BufferedImage screenshotRegion(Rectangle rect) { return robot.createScreenCapture(rect); } public static BufferedImage GetFullscreenScreenshot() throws AWTException { // var dimensions = getMonitorSizes(); // var s = dimensions.getFirst(); Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage capture = new Robot().createScreenCapture(screenRect); return capture; } public static Mat bufferedImageToMat(BufferedImage bi) { Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3); DataBuffer buffer = bi.getRaster().getDataBuffer(); if (buffer instanceof DataBufferByte) { byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData(); mat.put(0, 0, data); return mat; } else if (buffer instanceof DataBufferInt) { // int[] data = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData(); // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // ByteBuffer bBuffer = java.nio.ByteBuffer.allocate(data.length * 4); // IntBuffer iBuffer = bBuffer.asIntBuffer(); // iBuffer.put(data); // mat.put(0, 0, bBuffer.array()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { ImageIO.write(bi, "jpg", byteArrayOutputStream); byteArrayOutputStream.flush(); return Imgcodecs.imdecode(new MatOfByte(byteArrayOutputStream.toByteArray()), Imgcodecs.IMREAD_UNCHANGED); } catch (IOException e) { e.printStackTrace(); } return mat; } else { throw new UnknownFormatConversionException("Screenshot format unimplemented: " + buffer.getDataType()); } } public static BufferedImage matToImg(Mat img) { // Imgproc.resize(img, img, new Size(1000, 1000)); MatOfByte matOfByte = new MatOfByte(); Imgcodecs.imencode(".jpg", img, matOfByte); byte[] byteArray = matOfByte.toArray(); BufferedImage bufImage = null; try { InputStream in = new ByteArrayInputStream(byteArray); bufImage = ImageIO.read(in); return bufImage; } catch (Exception e) { e.printStackTrace(); return null; } } public static JFrame jf = null; public static JQuickDrawPanel qdp; public static void showImage(BufferedImage bi) { if (jf == null) { jf = new JFrame("Image"); jf.setResizable(false); qdp = new JQuickDrawPanel(bi); qdp.setFocusable(true); jf.add(qdp); jf.pack(); jf.setVisible(true); jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } else { qdp._img = bi; jf.repaint(); } } public static void showImage(Mat mat) { showImage(matToImg(mat)); } public static double colorDistance(Color c1, Color c2) { double sum = 0.0; sum += Math.pow(c1.getBlue() - c2.getBlue(), 2); sum += Math.pow(c1.getGreen() - c2.getGreen(), 2); sum += Math.pow(c1.getRed() - c2.getRed(), 2); return Math.sqrt(sum); } public static JFrame jf_full = null; private static MainFrameSpielerei imageDisplay; public static void hideFullscreenImage() { if (jf_full != null) jf_full.setVisible(false); } public static void showFullscreenImageOnTop(BufferedImage img) { // Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if (jf_full == null) { // LinkedList<Dimension> sizes = getMonitorSizes(); jf_full = new JFrame(); imageDisplay = new MainFrameSpielerei(img); jf_full.add(imageDisplay); jf_full.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jf_full.setUndecorated(true); jf_full.setExtendedState(JFrame.MAXIMIZED_BOTH); // jf_full.setSize(sizes.get(0)); jf_full.setResizable(false); // f.setOpacity((float) 0.5); jf_full.setBackground(new Color(0, 0, 0, 0)); jf_full.setAlwaysOnTop(true); } imageDisplay.setImage(img); jf_full.setVisible(true); } @SuppressWarnings("unused") private static LinkedList<Dimension> getMonitorSizes() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gs = ge.getScreenDevices(); LinkedList<Dimension> dimensions = new LinkedList<Dimension>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < gs.length; i++) { DisplayMode dm = gs[i].getDisplayMode(); sb.append(i + ", width: " + dm.getWidth() + ", height: " + dm.getHeight() + "\n"); dimensions.add(new Dimension(dm.getWidth(), dm.getHeight())); } dimensions.sort((a, b) -> b.width - a.width); return dimensions; } public static BufferedImage TransformColorToTransparency(BufferedImage image, Color c1, Color c2) { // Primitive test, just an example final int r1 = c1.getRed(); final int g1 = c1.getGreen(); final int b1 = c1.getBlue(); final int r2 = c2.getRed(); final int g2 = c2.getGreen(); final int b2 = c2.getBlue(); ImageFilter filter = new RGBImageFilter() { public final int filterRGB(int x, int y, int rgb) { int r = (rgb & 0xFF0000) >> 16; int g = (rgb & 0xFF00) >> 8; int b = rgb & 0xFF; if (r >= r1 && r <= r2 && g >= g1 && g <= g2 && b >= b1 && b <= b2) { // Set fully transparent but keep color return rgb & 0xFFFFFF; } return rgb; } }; ImageProducer ip = new FilteredImageSource(image.getSource(), filter); return ImageToBufferedImage(Toolkit.getDefaultToolkit().createImage(ip), image.getWidth(), image.getHeight()); } private static BufferedImage ImageToBufferedImage(Image image, int width, int height) { BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = dest.createGraphics(); g2.drawImage(image, 0, 0, null); g2.dispose(); return dest; } }
package utils; /** * Created by lamdevops on 7/22/17. */ public class ExceptionMailer { public static void send(Throwable e) { System.out.println(String.format("Sending email containing exception ", e)); } }
package com.pdd.pop.sdk.http.api.response; import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty; import com.pdd.pop.sdk.http.PopBaseHttpResponse; import java.util.List; public class PddSmsSendRecordListQueryResponse extends PopBaseHttpResponse{ /** * response */ @JsonProperty("sms_send_record_list_query_response") private SmsSendRecordListQueryResponse smsSendRecordListQueryResponse; public SmsSendRecordListQueryResponse getSmsSendRecordListQueryResponse() { return smsSendRecordListQueryResponse; } public static class SmsSendRecordListQueryResponse { /** * 总量 */ @JsonProperty("total") private Integer total; /** * 结果 */ @JsonProperty("result") private List<ResultItem> result; public Integer getTotal() { return total; } public List<ResultItem> getResult() { return result; } } public static class ResultItem { /** * 收件人 */ @JsonProperty("receiver") private String receiver; /** * 手机号 */ @JsonProperty("phone") private String phone; /** * 发送时间 */ @JsonProperty("send_time") private Long sendTime; /** * 短信内容 */ @JsonProperty("content") private String content; /** * 条数 */ @JsonProperty("items_num") private Long itemsNum; /** * 字数 */ @JsonProperty("words_num") private Long wordsNum; /** * 发送状态 */ @JsonProperty("status") private Integer status; public String getReceiver() { return receiver; } public String getPhone() { return phone; } public Long getSendTime() { return sendTime; } public String getContent() { return content; } public Long getItemsNum() { return itemsNum; } public Long getWordsNum() { return wordsNum; } public Integer getStatus() { return status; } } }
package com.appspot.smartshop.mock; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import com.appspot.smartshop.dom.ProductInfo; import com.appspot.smartshop.map.MapService; import com.appspot.smartshop.utils.Utils; import com.google.android.maps.GeoPoint; public class MockProduct { private static final int NUM_OF_PRODUCTS = 20; public static LinkedList<ProductInfo> getProducts() { String[] usernames = {"hieu", "tam", "nghia", "duc", "loi"}; String[] origins = {"vietnam", "campuchia", "lao", "thai lan", "my"}; String[] cats = {"lap", "net", "soft", "comp"}; LinkedList<ProductInfo> list = new LinkedList<ProductInfo>(); ProductInfo productInfo; int len = MockLocation.getPoints().length; for (int i = 1; i <= NUM_OF_PRODUCTS; ++i) { productInfo = new ProductInfo("name " + i, i * 1E4, "description " + i); GeoPoint point = MockLocation.getPoints()[Utils.random(len)]; productInfo.lat = (double)point.getLatitudeE6() / 1E6; productInfo.lng = (double)point.getLongitudeE6() / 1E6; productInfo.username = usernames[Utils.random(5)]; productInfo.date_post = new Date(2010 - 1900, Utils.random(12), Utils.random(31)); productInfo.is_vat = Utils.random(10) > 5 ? true : false; productInfo.origin = origins[Utils.random(5)]; productInfo.price = Utils.random(1000); productInfo.quantity = Utils.random(100); productInfo.warranty = "12 thang"; productInfo.setCategoryKeys = new HashSet<String>(); int numCats = 1 + Utils.random(4); for (int j = 0; j < numCats; ++j) { productInfo.setCategoryKeys.add(cats[j]); } list.add(productInfo); } return list; } public static LinkedList<ProductInfo> getSearchOnMapProducts() { LinkedList<ProductInfo> list = new LinkedList<ProductInfo>(); ProductInfo productInfo = null; productInfo = new ProductInfo("product 1", 10000, "description 1"); productInfo.lat = 10.771766; productInfo.lng = 106.664969; productInfo.username = MockUserInfo.getUsers()[Utils.random(4)].username; list.add(productInfo); productInfo = new ProductInfo("product 2", 20000, "description 2"); productInfo.lat = 10.770227; productInfo.lng = 106.668466; productInfo.username = MockUserInfo.getUsers()[Utils.random(4)].username; list.add(productInfo); productInfo = new ProductInfo("product 3", 30000, "description 3"); productInfo.lat = 10.766054; productInfo.lng = 106.664025; productInfo.username = MockUserInfo.getUsers()[Utils.random(4)].username; list.add(productInfo); productInfo = new ProductInfo("product 4", 40000, "description 4"); productInfo.lat = 10.774380; productInfo.lng = 106.662050; productInfo.username = MockUserInfo.getUsers()[Utils.random(4)].username; list.add(productInfo); return list; } }
/** * Copyright (C) 2014-2017 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * 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.helger.settings; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.helger.commons.annotation.Nonempty; import com.helger.commons.state.EChange; /** * Writable settings interface. * * @author philip */ public interface IMutableSettings extends ISettings { /** * {@inheritDoc} */ @Nullable IMutableSettings getSettingsValue (@Nullable String sFieldName); /** * Restore a value from serialization. Does not trigger an event! * * @param sFieldName * The name of the field. * @param aNewValue * The value to be set. May be <code>null</code> . */ void restoreValue (@Nonnull @Nonempty String sFieldName, @Nonnull Object aNewValue); /** * Copy all settings from another settings object. Existing values are not * erased, only additional values are added and existing values may be * changed. * * @param aOtherSettings * The settings from which we want to copy stuff. May not be * <code>null</code>. * @return {@link EChange}. Is changed if at least one value has been changed. */ @Nonnull EChange setValues (@Nonnull ISettings aOtherSettings); /** * Remove the value identified by the given field name. If the value was * successfully removed a change event is triggered, where the old value is * passed in and the new value is <code>null</code>. * * @param sFieldName * The field name to be removed. May be <code>null</code>. * @return {@link EChange}. */ @Nonnull EChange removeValue (@Nullable String sFieldName); /** * Remove all values from this settings object. * * @return {@link EChange#CHANGED} if at least one value was removed. */ @Nonnull EChange clear (); /** * Set the value of a settings field. * * @param sFieldName * The name of the field to be set. May neither be <code>null</code> * nor empty. * @param aNewValue * The new value to be set. If the value is <code>null</code> the value * is removed. * @return {@link EChange#CHANGED} if the value changed, * {@link EChange#UNCHANGED} if no change was performed. */ @Nonnull EChange setValue (@Nonnull @Nonempty String sFieldName, @Nullable Object aNewValue); /** * Set the value of a settings field. * * @param sFieldName * The name of the field to be set. May neither be <code>null</code> * nor empty. * @param bNewValue * The new value to be set. * @return {@link EChange#CHANGED} if the value changed, * {@link EChange#UNCHANGED} if no change was performed. */ @Nonnull default EChange setValue (@Nonnull @Nonempty final String sFieldName, final boolean bNewValue) { return setValue (sFieldName, Boolean.valueOf (bNewValue)); } /** * Set the value of a settings field. * * @param sFieldName * The name of the field to be set. May neither be <code>null</code> * nor empty. * @param nNewValue * The new value to be set. * @return {@link EChange#CHANGED} if the value changed, * {@link EChange#UNCHANGED} if no change was performed. */ @Nonnull default EChange setValue (@Nonnull @Nonempty final String sFieldName, final int nNewValue) { return setValue (sFieldName, Integer.valueOf (nNewValue)); } /** * Set the value of a settings field. * * @param sFieldName * The name of the field to be set. May neither be <code>null</code> * nor empty. * @param nNewValue * The new value to be set. * @return {@link EChange#CHANGED} if the value changed, * {@link EChange#UNCHANGED} if no change was performed. */ @Nonnull default EChange setValue (@Nonnull @Nonempty final String sFieldName, final long nNewValue) { return setValue (sFieldName, Long.valueOf (nNewValue)); } /** * Set the value of a settings field. * * @param sFieldName * The name of the field to be set. May neither be <code>null</code> * nor empty. * @param fNewValue * The new value to be set. * @return {@link EChange#CHANGED} if the value changed, * {@link EChange#UNCHANGED} if no change was performed. */ @Nonnull default EChange setValue (@Nonnull @Nonempty final String sFieldName, final float fNewValue) { return setValue (sFieldName, Float.valueOf (fNewValue)); } /** * Set the value of a settings field. * * @param sFieldName * The name of the field to be set. May neither be <code>null</code> * nor empty. * @param dNewValue * The new value to be set. * @return {@link EChange#CHANGED} if the value changed, * {@link EChange#UNCHANGED} if no change was performed. */ @Nonnull default EChange setValue (@Nonnull @Nonempty final String sFieldName, final double dNewValue) { return setValue (sFieldName, Double.valueOf (dNewValue)); } }
package com.biblio.api.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.biblio.api.core.Emprunt; @Repository public interface EmpruntRepository extends JpaRepository<Emprunt, Long> { public Iterable<Emprunt> findByUtilisateur_Id(long id); }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ui; import java.util.Collection; import java.util.Map; import org.springframework.lang.Nullable; /** * Interface that defines a holder for model attributes. * * <p>Primarily designed for adding attributes to the model. * * <p>Allows for accessing the overall model as a {@code java.util.Map}. * * @author Juergen Hoeller * @since 2.5.1 */ public interface Model { /** * Add the supplied attribute under the supplied name. * @param attributeName the name of the model attribute (never {@code null}) * @param attributeValue the model attribute value (can be {@code null}) */ Model addAttribute(String attributeName, @Nullable Object attributeValue); /** * Add the supplied attribute to this {@code Map} using a * {@link org.springframework.core.Conventions#getVariableName generated name}. * <p><i>Note: Empty {@link java.util.Collection Collections} are not added to * the model when using this method because we cannot correctly determine * the true convention name. View code should check for {@code null} rather * than for empty collections as is already done by JSTL tags.</i> * @param attributeValue the model attribute value (never {@code null}) */ Model addAttribute(Object attributeValue); /** * Copy all attributes in the supplied {@code Collection} into this * {@code Map}, using attribute name generation for each element. * @see #addAttribute(Object) */ Model addAllAttributes(Collection<?> attributeValues); /** * Copy all attributes in the supplied {@code Map} into this {@code Map}. * @see #addAttribute(String, Object) */ Model addAllAttributes(Map<String, ?> attributes); /** * Copy all attributes in the supplied {@code Map} into this {@code Map}, * with existing objects of the same name taking precedence (i.e. not getting * replaced). */ Model mergeAttributes(Map<String, ?> attributes); /** * Does this model contain an attribute of the given name? * @param attributeName the name of the model attribute (never {@code null}) * @return whether this model contains a corresponding attribute */ boolean containsAttribute(String attributeName); /** * Return the attribute value for the given name, if any. * @param attributeName the name of the model attribute (never {@code null}) * @return the corresponding attribute value, or {@code null} if none * @since 5.2 */ @Nullable Object getAttribute(String attributeName); /** * Return the current set of model attributes as a Map. */ Map<String, Object> asMap(); }
package com.javarush.test.level15.lesson12.home04; import static com.javarush.test.level15.lesson12.home04.Solution.readKeyFromConsoleAndInitPlanet; /** * Created by nik on 14.01.2017. */ public class Earth implements Planet { private static Earth earth; private Earth(){} static{ try{ earth = new Earth(); }catch(Exception e){ throw new RuntimeException("При создании объекта «Singleton» произошла ошибка"); } } public static Earth getInstance(){ return earth; } }
package com.ywd.blog.dao; import java.util.List; import java.util.Map; import com.ywd.blog.entity.BlogType; public interface BlogTypeDao { public List<BlogType> countList(); public BlogType findById(Integer id); public List<BlogType> list(Map<String, Object> map); public Long getTotal(Map<String, Object> map); public Integer add(BlogType blogType); public Integer update(BlogType blogType); public Integer delete(Integer id); }
package com.pointinside.android.api.dao; import android.database.Cursor; import android.net.Uri; public class PIMapAddressDataCursor extends AbstractDataCursor { private static final AbstractDataCursor.Creator<PIMapAddressDataCursor> CREATOR = new AbstractDataCursor.Creator() { public PIMapAddressDataCursor init(Cursor paramAnonymousCursor) { return new PIMapAddressDataCursor(paramAnonymousCursor); } }; private int mColumnAddress1; private int mColumnAddress2; private int mColumnCity; private int mColumnCountry; private int mColumnPostalCode; private int mColumnStateCode; private PIMapAddressDataCursor(Cursor paramCursor) { super(paramCursor); this.mColumnAddress1 = paramCursor.getColumnIndex("address_line1"); this.mColumnAddress2 = paramCursor.getColumnIndex("address_line2"); this.mColumnCity = paramCursor.getColumnIndex("city"); this.mColumnCountry = paramCursor.getColumnIndex("country"); this.mColumnPostalCode = paramCursor.getColumnIndex("postal_code"); this.mColumnStateCode = paramCursor.getColumnIndex("state_code"); } public static PIMapAddressDataCursor getInstance(Cursor paramCursor) { return (PIMapAddressDataCursor)CREATOR.newInstance(paramCursor); } public static PIMapAddressDataCursor getInstance(PIMapDataset paramPIMapDataset, Uri paramUri) { return (PIMapAddressDataCursor)CREATOR.newInstance(paramPIMapDataset, paramUri); } public String getAddress1() { return this.mCursor.getString(this.mColumnAddress1); } public String getAddress2() { return this.mCursor.getString(this.mColumnAddress2); } public String getCity() { return this.mCursor.getString(this.mColumnCity); } public String getCountry() { return this.mCursor.getString(this.mColumnCountry); } public String getFormattedCityStateZip() { return getCity() + ", " + getState() + " " + getPostalCode(); } public String getPostalCode() { return this.mCursor.getString(this.mColumnPostalCode); } public String getState() { return this.mCursor.getString(this.mColumnStateCode); } public Uri getUri() { return PIVenue.getAddressUri(getId()); } } /* Location: D:\xinghai\dex2jar\classes-dex2jar.jar * Qualified Name: com.pointinside.android.api.dao.PIMapAddressDataCursor * JD-Core Version: 0.7.0.1 */
package com.sbs.sbsattend; import com.sbs.tool.MySignal; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; public class AdminActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 去除标题 this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.admin); } //审批请假 public void review_leave(View v) { Intent intent = new Intent(AdminActivity.this, ReivewLeaveActivity.class); AdminActivity.this.startActivity(intent); } public void review_over(View v) { Intent intent = new Intent(AdminActivity.this, ReivewOverTimeActvity.class); AdminActivity.this.startActivity(intent); } //本月班次网页接口,已废弃 public void watch_web(View v) { Intent intent = new Intent(AdminActivity.this, WatchTableActivity.class); AdminActivity.this.startActivity(intent); } //本月班次,暂时作废 public void watch_table(View v) { Intent intent = new Intent(AdminActivity.this, QueryWorkInfoActivity.class); AdminActivity.this.startActivity(intent); } //显示本月值班表,用日历的方式 public void watch_shift(View v){ Intent intent = new Intent(AdminActivity.this, QueryShiftActivity.class); AdminActivity.this.startActivity(intent); } //显示本月调休表,日历形式 public void watch_rest(View v){ Intent intent = new Intent(AdminActivity.this, QueryShiftActivity.class); intent.putExtra("FLAG", MySignal.GETREST); AdminActivity.this.startActivity(intent); } //显示本月请假表,列表形式 public void watch_leaveall(View v){ Intent intent = new Intent(AdminActivity.this, QueryShiftActivity.class); intent.putExtra("FLAG", MySignal.GETLEAVE); AdminActivity.this.startActivity(intent); } }
package kim.aleksandr.backendless; import android.util.Log; import com.backendless.Backendless; import com.backendless.BackendlessCollection; import com.backendless.persistence.BackendlessDataQuery; /** * Created by User on 14.07.2016. */ public class CheckForConflictsThread extends Thread{ long time, time2; BackendlessCollection<Orders> result, result2; String test = "not changed"; CheckForConflictsThread (long time, long time2) { this.time = time; this.time2 = time2; } public boolean goodToBook () { Log.d("totalObjects1", Integer.toString(result.getTotalObjects())); Log.d("totalObjects2", Integer.toString(result2.getTotalObjects())); Log.d("String check", test); return result.getTotalObjects() == 0 && result2.getTotalObjects() == 0; } public void run () { String firstCheck = "end_time >= " + Long.toString(time); BackendlessDataQuery firstQuery = new BackendlessDataQuery(); firstQuery.setWhereClause(firstCheck); result = Backendless.Persistence.of(Orders.class).find(firstQuery); String secondCheck = "start_time <= " + Long.toString(time2); BackendlessDataQuery secondQuery = new BackendlessDataQuery(); secondQuery.setWhereClause(secondCheck); Log.d("Check for startTime < ", "+"); result2 = Backendless.Persistence.of(Orders.class).find(secondQuery); test = "changed"; } }
package com.tyler_hoffman.ventriloquist.common; import java.util.Arrays; import java.util.Hashtable; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.CompoundControl; import javax.sound.sampled.Control; import javax.sound.sampled.DataLine; import javax.sound.sampled.Line; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.Mixer; import javax.sound.sampled.Port; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; /** * LineManager performs basic indexing of available lines. * After initialization, scanLines() should be called. This performs the line indexing. * For info on Line types, check Oracle's Sound API documentation: * http://docs.oracle.com/javase/tutorial/sound/accessing.html * * @author Tyler Hoffman */ public class LineManager { private static final int MAX_COUNT = 64; private Mixer[] mixers; private TargetDataLine[] targetDataLines; private SourceDataLine[] sourceDataLines; private Port[] targetPorts; private Port[] sourcePorts; private Hashtable<Line, Mixer> lineToMixerTable; public LineManager() { targetDataLines = new TargetDataLine[0]; sourceDataLines = new SourceDataLine[0]; targetPorts = new Port[0]; sourcePorts = new Port[0]; lineToMixerTable = new Hashtable<Line, Mixer>(); } /** * Index all available lines. * This must be called before getters for lines will work. */ public void scanLines() { // initially 0 of everything found int numMixers = 0; int numTargetLines = 0; int numSourceLines = 0; int numTargetPorts = 0; int numSourcePorts = 0; lineToMixerTable.clear(); // start arrays with tons of room (truncated later) mixers = new Mixer[MAX_COUNT]; targetDataLines = new TargetDataLine[MAX_COUNT]; sourceDataLines = new SourceDataLine[MAX_COUNT]; targetPorts = new Port[MAX_COUNT]; sourcePorts = new Port[MAX_COUNT]; // cycle through mixers Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); for (int i = 0; i < mixerInfo.length; i++) { Mixer mixer = AudioSystem.getMixer(mixerInfo[i]); mixers[numMixers++] = mixer; Line.Info[] targetInfo = mixer.getTargetLineInfo(); Line.Info[] sourceInfo = mixer.getSourceLineInfo(); int j; // target lines for (j = 0; j < targetInfo.length; j++) { Line line; try { line = mixer.getLine(targetInfo[j]); lineToMixerTable.put(line, mixer); if (line instanceof TargetDataLine) { TargetDataLine targetLine = (TargetDataLine)line; targetDataLines[numTargetLines++] = targetLine; } else if (line instanceof Port) { Port targetPort = (Port)line; targetPorts[numTargetPorts++] = targetPort; } } catch (LineUnavailableException e) { System.out.println("unable to open line.."); } } // source lines for (j = 0; j < sourceInfo.length; j++) { Line line; try { line = mixer.getLine(sourceInfo[j]); lineToMixerTable.put(line, mixer); if (line instanceof SourceDataLine) { SourceDataLine sourceLine = (SourceDataLine)line; sourceDataLines[numSourceLines++] = sourceLine; } else if (line instanceof Port) { Port sourcePort = (Port)line; sourcePorts[numSourcePorts++] = sourcePort; } } catch (LineUnavailableException e) { System.out.println("unable to open line.."); } } } // truncate mixers = Arrays.copyOf(mixers, numMixers); targetDataLines = Arrays.copyOf(targetDataLines, numTargetLines); sourceDataLines = Arrays.copyOf(sourceDataLines, numSourceLines); targetPorts = Arrays.copyOf(targetPorts, numTargetPorts); sourcePorts = Arrays.copyOf(sourcePorts, numSourcePorts); } /** * Print available controls, including subcontrols if a control is compound * @param controls Array of controls to look at. * example: examineControls(line.getControls()); */ public static void examineControls(Control[] controls) { examineControls(controls, 1); } /** * Print available controls, including subcontrols if a control is compound * @param controls Array of controls to look at * @param depth Determines spacing (used for nested controls) */ public static void examineControls(Control[] controls, int depth) { // build whitespace for indentation String whiteSpace = ""; for (int i = 0; i < depth; i++) whiteSpace += " "; // print each control for (Control control: controls) { System.out.println(whiteSpace + control); // if it's compound, do some controlception if (control instanceof CompoundControl) examineControls(((CompoundControl)control).getMemberControls(), depth + 1); } } /** * Get a line meeting the desired criteria * @param info Desired port type * @throws LineUnavailableException */ public void getLine(Port.Info info) throws LineUnavailableException { Line line = null; if (AudioSystem.isLineSupported(info)) line = AudioSystem.getLine(info); if (line != null) { System.out.println("desired line: " + line); boolean wasOpen = line.isOpen(); if (!wasOpen) line.open(); examineControls(line.getControls()); if (!wasOpen) line.close(); } } /** * Check if audio format is supported by line * @param line Line to check * @param audioFormat AudioFormat to check * @return Returns true if line supports audioFormat */ public static boolean isAudioFormatSupported(Line line, AudioFormat audioFormat) { boolean isSupported = false; AudioFormat[] supportedFormats = null; Line.Info info = line.getLineInfo(); // get the supported audioFormats for line.Info if (line instanceof DataLine) { DataLine.Info dataLine = (DataLine.Info)info; supportedFormats = dataLine.getFormats(); } else { // TODO: figure out how to deal with finding supported formats for Ports } // check to see if given audioFormat is a supported format for (AudioFormat format: supportedFormats) { // so a few variables in given audioFormats are often unspecified. // if that happens, clone format and change said variables to those of audioFormat // this is probably a bad idea, but whatev.. boolean somethingNotSpecified = false; float sampleRate = format.getSampleRate(); float frameRate = format.getFrameRate(); if (format.getSampleRate() == AudioSystem.NOT_SPECIFIED) { somethingNotSpecified = true; sampleRate = audioFormat.getSampleRate(); } if (format.getFrameRate() == AudioSystem.NOT_SPECIFIED) { somethingNotSpecified = true; frameRate = audioFormat.getFrameRate(); } // something unspecified.. make copy of format w/ specifics from requested format if (somethingNotSpecified) format = new AudioFormat(format.getEncoding(), sampleRate, format.getSampleSizeInBits(), format.getChannels(), format.getFrameSize(), frameRate, format.isBigEndian()); // if (audioFormat.getEncoding() == format.getEncoding() && audioFormat.getSampleRate() == format.getSampleRate() && audioFormat.getSampleSizeInBits() == format.getSampleSizeInBits() && audioFormat.getChannels() == format.getChannels() && audioFormat.getFrameSize() == format.getFrameSize() && audioFormat.getFrameRate() == format.getFrameRate() && audioFormat.isBigEndian() == format.isBigEndian()) { // win isSupported = true; break; } } return isSupported; } /** * Get a Mixer * @param index index of mixer * @return Returns the desired mixer */ public Mixer getMixer(int index) { return mixers[index]; } /** * Get a TargetDataLine * @param index Index of the TargetDataLine * @return Returns the desired line */ public TargetDataLine getTargetLine(int index) { return targetDataLines[index]; } /** * Get a SourceDataLine * @param index Index of the SourceDataLine * @return Returns the desired line */ public SourceDataLine getSourceLine(int index) { return sourceDataLines[index]; } /** * Get a target Port * @param index Index of the target Port * @return Returns the desired port */ public Port getTargetPort(int index) { return targetPorts[index]; } /** * Get a source Port * @param index Index of the source Port * @return Returns the desired port */ public Port getSourcePort(int index) { return sourcePorts[index]; } /** * @return Returns the number of mixers */ public int getNumMixers() { return mixers.length; } /** * @return Returns the number of TargetDataLines */ public int getNumTargetLines() { return targetDataLines.length; } /** * @return Returns the number of SourceDataLines */ public int getNumSourceLines() { return sourceDataLines.length; } /** * @return Returns the number target Ports */ public int getNumTargetPorts() { return targetPorts.length; } /** * @return Returns the number source Ports */ public int getNumSourcePorts() { return sourcePorts.length; } }
package com.imooc.weixin6_0; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.comyou.qrscandemo.R; public class HomeFragment extends Fragment { private static Spinner Sele_logis; private static EditText order_no; private static String sele_logis_str; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View home_view = inflater.inflate(R.layout.home_tab, container, false); Button home_btn = (Button) home_view.findViewById(R.id.home_btn); Sele_logis = (Spinner) home_view.findViewById(R.id.home_spin); sele_logis_str = Sele_logis.getSelectedItem().toString(); order_no = (EditText) home_view.findViewById(R.id.home_order_no); Sele_logis.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { sele_logis_str = Sele_logis.getSelectedItem().toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); home_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String content = sele_logis_str + "\n" + order_no.getText().toString(); Toast.makeText(getActivity(), R.string.search_result,Toast.LENGTH_SHORT).show(); } }); return home_view; } }
/* Test 45: * * Ancora sull'invocazione di metodi. * * In questo test, facciamo riferimento alla forma: * * TypeName.MethodName */ package gimnasium; class gemini { static void pippo() {} int pluto() { } private static void cake() { } public static void paperino() { } protected static int hugo() { } } class jenny { void gabriel () { int i; gemini.pippo(); i=gemini.pluto(); // errore!!! pluto in gemini non e' static. gemini.cake(); // errore!!! cake in gemini e' private. gemini.paperino(); } } class dino extends gemini { void sandokan() { float k; k=gemini.hugo(); } }
package com.itheima.day_06.demo_03; import java.util.HashSet; import java.util.Random; import java.util.Set; public class HashSetDemo_01 { /* 产生十个不同的随机数,存储到Set中 */ public static void main(String[] args) { Random random = new Random(); Set<Integer> set = new HashSet<>(); while (set.size() < 10) set.add(random.nextInt(10) + 1); System.out.println(set); } }
package c.c.quadraticfunction; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.List; import c.c.quadraticfunction.solvers.PolynomialEquation; import c.c.quadraticfunction.solvers.SolverFactory; public class MainActivity extends AppCompatActivity { private EditText editTextA,editTextB,editTextC; private Double parameterA = 0.0,parameterB = 0.0,parameterC = 0.0, x1=null,x2=null; private TextView textViewResults; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextA = (EditText) findViewById(R.id.editTextA); editTextB = (EditText) findViewById(R.id.editTextB); editTextC = (EditText) findViewById(R.id.editTextC); textViewResults = (TextView) findViewById(R.id.textViewResults); Button buttonOk = (Button) findViewById(R.id.buttonCompute); Button buttonDraw = (Button) findViewById(R.id.buttonDraw); /** * Akcja wywoływana po naciśnięciu klawisza. * Parsuje wartości z editTextów na liczby, a następnie wywołuje funkcję obliczającą */ buttonOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { compute(); } }); buttonDraw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { compute(); Intent intent = new Intent(getApplicationContext(),Drawing.class); intent.putExtra("a",parameterA); intent.putExtra("b",parameterB); intent.putExtra("c",parameterC); intent.putExtra("x1",x1); intent.putExtra("x2",x2); startActivity(intent); } }); /** * Akcja wywołana przy tworzeniu widoku (po zmianie orientacji). * Przywraca zapisane wartości współczynników. */ if (savedInstanceState != null) { parameterA = getBundleDouble(savedInstanceState, "paramA", 0.0); parameterB = getBundleDouble(savedInstanceState, "paramB", 0.0); parameterC = getBundleDouble(savedInstanceState, "paramC", 0.0); compute(); } } /** * Funkcja rozwiązująca równanie */ public void compute(){ parameterA = parseEditText(editTextA); parameterB = parseEditText(editTextB); parameterC = parseEditText(editTextC); PolynomialEquation solver = SolverFactory.getSolver(parameterC,parameterB,parameterA); x1=null; x2=null; try { List results = solver.compute(); showResults(results); } catch (Exception e) { showExceptionMessage(e); } } /** * Funkcja wyświetlająca rozwiązania równania * @param results */ private void showResults(List<Double> results ){ StringBuilder sb = new StringBuilder(); int i=1; try{ x1 = results.get(0); } catch (Exception e){ } try{ x2 = results.get(1); } catch (Exception e){ } for(double result:results){ sb.append("X<sub><small> "); sb.append(i); sb.append("</small></sub> = "); sb.append(result); sb.append("<br/>"); i++; } textViewResults.setText(Html.fromHtml(sb.toString())); } /** * Funkcja wyświetlająca komunikaty, wyrzucone w wyjątkach przez rozwiązywacze * @param e */ private void showExceptionMessage(Exception e){ try { String packageName = getPackageName(); int resId = getResources().getIdentifier(e.getMessage(), "string", packageName); textViewResults.setText(getString(resId)); } catch (Exception exc){ Toast.makeText(this, getResources().getString(R.string.ApplicationError), Toast.LENGTH_LONG).show(); } } /** * Zapisywanie współczynników * @param savedInstanceState */ @Override public void onSaveInstanceState(Bundle savedInstanceState){ super.onSaveInstanceState(savedInstanceState); savedInstanceState.putDouble("paramA", parameterA); savedInstanceState.putDouble("paramB", parameterB); savedInstanceState.putDouble("paramC", parameterC); } /** * Funkcja parsująca tekst na liczby. W przypadku zerowego ciągu znaków zwraca 0 * @param editText * @return */ private double parseEditText(EditText editText){ String text = editText.getText().toString(); text = text.equals("")? "0":text; double d; try { d = Double.parseDouble(text); } catch (Exception e){ d = 0.0; } return d; } /** * Funkcja zwracająca zapisane w Bundle liczby. W przypadku nieistniejącego klucza, zwraca wartość domyślną * @param b * Bundle * @param key * Klucz * @param def * Wartość domyślna * @return * Zapisana liczba w Bundle albo 0 */ public Double getBundleDouble(Bundle b, String key, Double def) { Double value = b.getDouble(key); if (value == null) value = def; return value; } }
package com.szakdolgozat.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import com.szakdolgozat.domain.Delivery; import com.szakdolgozat.domain.Order; import com.szakdolgozat.domain.Role; import com.szakdolgozat.domain.User; import com.szakdolgozat.repository.UserRepository; @Service public class UserServiceImpl implements UserService, UserDetailsService{ private UserRepository userRepo; private RoleService roleService; private BCryptPasswordEncoder passwordEncoder; private static final String USER_ROLE = "USER"; private static final String EMPLOYEE_ROLE = "EMPLOYEE"; private static final Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class); public UserServiceImpl() { } @Autowired public void setUserRepo(UserRepository userRepo) { this.userRepo = userRepo; } @Autowired public void setRoleRepo(RoleService roleService) { this.roleService = roleService; } @Autowired public void setPasswordEncoder(BCryptPasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = findByEmail(username); if (user == null) { throw new UsernameNotFoundException(username); } return new UserDetailsImpl(user); } @Override public User findByEmail(String email) { return userRepo.findByEmail(email); } @Override public int registerUser(User userToRegister) { User userCheck = findByEmail(userToRegister.getEmail()); if (userCheck != null) return 0; userToRegister.setRole(roleService.findRoleByName(USER_ROLE)); userToRegister.setPhoneNumber(userToRegister.getPhoneNumber()); userToRegister.setPassword(passwordEncoder.encode(userToRegister.getPassword())); userRepo.save(userToRegister); return 1; } @Override public List<User> findAllEmployees() throws Exception { List<User> employees = userRepo.findAllByRole(roleService.findRoleByName(EMPLOYEE_ROLE)); if(employees.isEmpty()) throw new Exception("No employee found"); return employees; } @Override public List<User> findAllUsers() throws Exception { List<User> users = userRepo.findAllByRole(roleService.findRoleByName(USER_ROLE)); if(users.isEmpty()) throw new Exception("No user found"); return users; } @Override public Set<Order> findOrdersOfUser(long userId) throws Exception { User user = userRepo.findById(userId).get(); Set<Order> ordersOfUserSet = user.getOrdersOfUser(); if(ordersOfUserSet.isEmpty()) throw new Exception("No orders for user"); return ordersOfUserSet; } @Override public Set<Delivery> findDeliveriesOfEmployee(long employeeId) throws Exception { User employee = userRepo.findById(employeeId).get(); Set<Delivery> deliveriesOfEmployeeSet = employee.getDeliveriesOfEmployee(); if(deliveriesOfEmployeeSet.isEmpty()) throw new Exception("No delivery to employee"); return deliveriesOfEmployeeSet; } @Override public void editUser(User userToEdit) throws Exception{ User user = userRepo.findById(userToEdit.getId()).get(); if( !user.getEmail().equals(userToEdit.getEmail()) && userRepo.findByEmail(userToEdit.getEmail())!=null) throw new Exception("Az email cím (" + userToEdit.getEmail() + ") már foglalt."); if(!userToEdit.getPassword().isEmpty()) user.setPassword(passwordEncoder.encode(userToEdit.getPassword())); user.setAddress(userToEdit.getAddress()); user.setBirthday(userToEdit.getBirthday()); user.setCity(userToEdit.getCity()); user.setEmail(userToEdit.getEmail()); user.setHouseNumber(userToEdit.getHouseNumber()); user.setName(userToEdit.getName()); user.setPhoneNumber(userToEdit.getPhoneNumber()); user.setPostCode(userToEdit.getPostCode()); if(userToEdit.getRole() != null)user.setRole(userToEdit.getRole()); user.setSex(userToEdit.getSex()); userRepo.save(user); } @Override @Transactional public String deleteUser(long id) { Optional<User> userToRemove = userRepo.findById(id); if(userToRemove.isPresent()) { removeUserFromRoles(userToRemove.get()); userRepo.deleteById(id); return "deleted"; }else { return "not exists"; } } @Override public Object getAllUserNameAndId(boolean isUser) throws Exception { Map<Long, String> users = new HashMap<Long, String>(); List<User> userList; if (isUser) { userList = findAllUsers(); }else { userList = findAllEmployees(); } for (User user : userList) { users.put(user.getId(), user.getName()); } return users; } private void removeUserFromRoles(User userToRemove) { Role role = userToRemove.getRole(); Set<User> userSet = role.getUsersWithRole(); if(userSet.contains(userToRemove)) { userSet.remove(userToRemove); role.setUsersWithRole(userSet); } else LOG.error("User " + userToRemove.getName() + " does not have role: " + role.getName()); } @Override public User findUserById(long userId) throws Exception { Optional<User> user = userRepo.findById(userId); if(user.isPresent()) { return user.get(); } else { throw new Exception("Nincs felhasználó " + userId + " ezzel az id-vel"); } } public boolean hasActiveDelivery(User user) { Set<Delivery> deliveryList = user.getDeliveriesOfEmployee(); if (deliveryList.isEmpty()) return false; for (Delivery delivery : deliveryList) { if(!delivery.isDone()) return true; } return false; } @Override public List<Order> findOrdersOfUser(String email) { User user = findByEmail(email); List<Order> orderList = new ArrayList<Order>(); try { orderList.addAll(findOrdersOfUser(user.getId())); orderList.sort((Order o1, Order o2) -> o2.getDeadLine().compareTo(o1.getDeadLine())); return orderList; } catch (Exception e) { LOG.warn(e.getMessage()); return null; } } }
package com.joalib.controller; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //import com.jaolib.book.manager.action.BookInfoAddAction; import com.joalib.DTO.ActionForward; import com.joalib.DTO.BookInfoDTO; import com.joalib.DTO.LoanDTO; import com.joalib.bookinfo.action.Action; import com.joalib.bookinfo.action.BookInfoDetailAction; import com.joalib.bookinfo.action.BookInfoDetailDBAction; import com.joalib.bookinfo.svc.BookInfoDetailDBService; import com.joalib.loan.service.BookLoanService; @WebServlet("*.bk") public class BookInfoContr extends javax.servlet.http.HttpServlet{ protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String RequestURI=request.getRequestURI(); String contextPath=request.getContextPath(); String command=RequestURI.substring(contextPath.length()); ActionForward forward=null; Action action=null; if(command.equals("/bookInfoAdd.bk")){ // action = new BookInfoAddAction(); ///////////////////북정보 관리자 페이지 try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/bookInfoDetail.bk")){ action = new BookInfoDetailAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if(command.equals("/bookInfoDetailDB.bk")){ action = new BookInfoDetailDBAction(); try{ forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } } // BookInfoDetailDBService bookInfoDetailDBService = new BookInfoDetailDBService(); // BookInfoDTO bookInfoDTO = new BookInfoDTO(); // // String member_id = request.getParameter("member_id"); // String isbn = request.getParameter("isbn"); // // bookInfoDTO.setIsbn(isbn); // bookInfoDTO.setMember_id(member_id); // // request.setAttribute("book", bookInfoDetailDBService.getBook(bookInfoDTO)); if(forward != null) { if(forward.isRedirect()) { response.sendRedirect(forward.getPath()); }else{ RequestDispatcher dispatcher= request.getRequestDispatcher(forward.getPath()); dispatcher.forward(request, response); } } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request,response); } }
package net.awesomekorean.podo.lesson.lessonReviewRewards; import net.awesomekorean.podo.lesson.lessons.Lesson; import net.awesomekorean.podo.lesson.lessons.Lesson36; import net.awesomekorean.podo.lesson.lessons.Lesson37; import net.awesomekorean.podo.lesson.lessons.Lesson38; import net.awesomekorean.podo.lesson.lessons.Lesson39; import net.awesomekorean.podo.lesson.lessons.Lesson40; import net.awesomekorean.podo.lesson.lessons.Lesson41; import net.awesomekorean.podo.lesson.lessons.Lesson42; import net.awesomekorean.podo.lesson.lessons.Lesson43; import net.awesomekorean.podo.lesson.lessons.Lesson44; import net.awesomekorean.podo.lesson.lessons.Lesson45; import net.awesomekorean.podo.lesson.lessons.LessonInit; import net.awesomekorean.podo.lesson.lessons.LessonItem; import java.io.Serializable; public class LessonReview06 extends LessonInit implements LessonItem, LessonReview, Serializable { private String lessonId = "LR_06"; private String lessonTitle = ""; private String lessonSubTitle = ""; private Lesson[] lessons = { new Lesson41(), new Lesson42(), new Lesson43(), new Lesson44(), new Lesson45() }; private String[] baseForm = { "돌아가다", "앉다", "입다", "벗다", "바꾸다", "확인하다", "전화하다" }; private String[][] conjugation = { {"돌아가기로 했어요", "돌아갈래요?", "돌아갈까요?"}, {"앉을래요?", "앉을까요?", "앉으시다", "앉습니다"}, {"입을래요?", "입을까요?", "입으시다", "입습니다"}, {"벗을래요?", "벗을까요?", "벗으시다", "벗습니다"}, {"바꾸기로 했어요", "바꿀래요?", "바꿀까요?", "바꾸시다", "바꿉니다"}, {"확인하기로 했어요", "확인할래요?", "확인할까요?", "확인하시다", "확인합니다"}, {"전화하기로 했어요", "전화할래요?", "전화할까요?", "전화하시다", "전화합니다"} }; private String[][] translate = { {"I decided to go back", "Would you like to go back?", "Should I(Shall we) go back?"}, {"Would you like to sit down?", "Should I(Shall we) sit down?", "Sit down (honorific)", "Sit down (formal)"}, {"Would you like to put it on?", "Should I(Shall we) put it on?", "Put on (honorific)", "Put on (formal)"}, {"Would you like to take it off?", "Should I(Shall we) take it off?", "Take off (honorific)", "Take off (formal)"}, {"I decided to change it", "Would you like to change it?", "Should I(Shall we) change it?", "Change (honorific)", "Change (formal)"}, {"I decided to check it", "Would you like to check it?", "Should I(Shall we) check it?", "Check (honorific)", "Check (formal)"}, {"I decided to call", "Would you like to call?", "Should I call you? (Shall we call him?)", "Call (honorific)", "Call (formal) "} }; public String[] getBaseForm() { return baseForm; } public String[][] getConjugation() { return conjugation; } public String[][] getTranslate() { return translate; } public Lesson[] getLessons() { return lessons; } @Override public String getLessonId() { return lessonId; } @Override public String getLessonTitle() { return lessonTitle; } @Override public String getLessonSubTitle() { return lessonSubTitle; } }
package com.example.Springsecurity.service; import com.example.Springsecurity.domain.Book; import java.util.List; public interface BookService { List<Book> getAllBooks(); Book insertBook(Book book); Book updateBook(Book book); Book getBookById(String id); }
package cn.edu.cugb.information_program.go_test; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class MatchingActivity extends AppCompatActivity { private List<matching> matchingList = new ArrayList<matching>(); public EditText origin; public EditText destination; public EditText month; public EditText day; public EditText number; public EditText comment; public static String []usernames; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_matching); Intent intent = getIntent(); String origin = intent.getStringExtra("origin"); String destination = intent.getStringExtra("destination"); String number = intent.getStringExtra("number"); String month = intent.getStringExtra("month"); String day = intent.getStringExtra("day"); String comment=intent.getStringExtra("comment"); String date="2018-"+month+"-"+day; HttpUtil.sendTravelInformation(origin,destination,number,date,comment,new HttpCallbackListener() { @Override public void onFinish(String response) { if(response!=""){ usernames=response.split(" "); initusers();} }public void onError(Exception e){ e.printStackTrace(); } }); try { Thread.currentThread().sleep(100);//阻断0.1秒 } catch (InterruptedException e) { e.printStackTrace(); } MatchingAdapter adapter = new MatchingAdapter(MatchingActivity.this, R.layout.user_item, matchingList); ListView listView = (ListView) findViewById(R.id.list_view); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { matching user = matchingList.get(position); Intent intent_introduce = new Intent(MatchingActivity.this, introduction.class); intent_introduce.putExtra("username",user.getName()); startActivity(intent_introduce); } }); } private void initusers() { matching []a=new matching[usernames.length]; for(int j=0;j<usernames.length;j++) { a[j] = new matching(usernames[j]); matchingList.add(a[j]); } } }
package net.lshift.lee.jaxb.xml.adapter; import javax.xml.bind.annotation.adapters.XmlAdapter; import net.lshift.lee.jaxb.pojo.Parent; import net.lshift.lee.jaxb.xml.ParentElement; public class ParentAdapter extends XmlAdapter<ParentElement, Parent> { @Override public Parent unmarshal(ParentElement v) throws Exception { return new Parent(v.getParentName(), v.getChild()); } @Override public ParentElement marshal(Parent v) throws Exception { throw new Exception("Not implemented"); } }
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.wso2.appcloud.core.dto; public class Subscription { private int tenantId; private String plan; private int maxApplicationCount; private int maxDatabaseCount; private String cloudType; private int maxReplicaCount; private int maxMemory; private int maxCpu; private String startDate; private String endDate; private int isWhiteListed; private String status; public int getTenantId() { return tenantId; } public void setTenantId(int tenantId) { this.tenantId = tenantId; } public String getPlan() { return plan; } public void setPlan(String plan) { this.plan = plan; } public int getMaxApplicationCount() { return maxApplicationCount; } public void setMaxApplicationCount(int maxApplicationCount) { this.maxApplicationCount = maxApplicationCount; } public int getMaxDatabaseCount() { return maxDatabaseCount; } public void setMaxDatabaseCount(int maxDatabaseCount) { this.maxDatabaseCount = maxDatabaseCount; } public String getCloudType() { return cloudType; } public void setCloudType(String cloudType) { this.cloudType = cloudType; } public int getMaxReplicaCount() { return maxReplicaCount; } public void setMaxReplicaCount(int maxReplicaCount) { this.maxReplicaCount = maxReplicaCount; } public int getMaxMemory() { return maxMemory; } public void setMaxMemory(int maxMemory) { this.maxMemory = maxMemory; } public int getMaxCpu() { return maxCpu; } public void setMaxCpu(int maxCpu) { this.maxCpu = maxCpu; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public int getIsWhiteListed() { return isWhiteListed; } public void setIsWhiteListed(int isWhiteListed) { this.isWhiteListed = isWhiteListed; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
package com.lzw; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JToggleButton; public class ControlFormStatus extends JFrame { /** * */ private static final long serialVersionUID = 3916932450920717576L; private JPanel contentPane; private Point pressedPoint; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ControlFormStatus frame = new ControlFormStatus(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ControlFormStatus() { setUndecorated(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(null); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); BackgroundPanel topPanel = new BackgroundPanel(); topPanel.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { do_topPanel_mouseDragged(e); } }); topPanel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { do_topPanel_mousePressed(e); } }); Image centerImage = new ImageIcon(getClass() .getResource("frameTop.png")).getImage(); Dimension dimension = new Dimension(centerImage.getWidth(this), centerImage.getHeight(this)); topPanel.setPreferredSize(dimension); topPanel.setImage(centerImage); contentPane.add(topPanel, BorderLayout.NORTH); topPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5)); JPanel panel = new JPanel(); panel.setPreferredSize(new Dimension(60, 22)); panel.setOpaque(false); topPanel.add(panel); panel.setLayout(new GridLayout(1, 0, 0, 0)); JButton button = new JButton(""); button.setRolloverIcon(new ImageIcon(ControlFormStatus.class .getResource("/com/lzw/minBH.jpg"))); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_button_itemStateChanged(e); } }); button.setFocusPainted(false);// 取消焦点绘制 button.setBorderPainted(false);// 取消边框绘制 button.setContentAreaFilled(false);// 取消内容绘制 button.setIcon(new ImageIcon(ControlFormStatus.class .getResource("/com/lzw/minB.jpg"))); panel.add(button); JToggleButton button_1 = new JToggleButton(""); button_1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { do_button_1_itemStateChanged(e); } }); button_1.setRolloverIcon(new ImageIcon(ControlFormStatus.class .getResource("/com/lzw/maxBH.jpg"))); button_1.setSelectedIcon(new ImageIcon(ControlFormStatus.class .getResource("/com/lzw/maxBH.jpg"))); button_1.setIcon(new ImageIcon(ControlFormStatus.class .getResource("/com/lzw/maxB.jpg"))); button_1.setContentAreaFilled(false); button_1.setBorderPainted(false); button_1.setFocusPainted(false); panel.add(button_1); JButton button_2 = new JButton(""); button_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_button_2_actionPerformed(e); } }); button_2.setRolloverIcon(new ImageIcon(ControlFormStatus.class .getResource("/com/lzw/closeBH.jpg"))); button_2.setFocusPainted(false); button_2.setContentAreaFilled(false); button_2.setBorderPainted(false); button_2.setIcon(new ImageIcon(ControlFormStatus.class .getResource("/com/lzw/closeB.jpg"))); panel.add(button_2); BackgroundPanel backgroundPanel_1 = new BackgroundPanel(); Image topImage = new ImageIcon(getClass() .getResource("frameCenter.png")).getImage(); backgroundPanel_1.setImage(topImage); contentPane.add(backgroundPanel_1, BorderLayout.CENTER); } protected void do_button_itemStateChanged(ActionEvent e) { setExtendedState(JFrame.ICONIFIED);// 窗体最小化 } protected void do_button_2_actionPerformed(ActionEvent e) { dispose();// 销毁窗体 } protected void do_button_1_itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { setExtendedState(JFrame.MAXIMIZED_BOTH);// 最大化窗体 } else { setExtendedState(JFrame.NORMAL);// 恢复普通窗体状态 } } protected void do_topPanel_mousePressed(MouseEvent e) { pressedPoint = e.getPoint();// 记录鼠标坐标 } protected void do_topPanel_mouseDragged(MouseEvent e) { Point point = e.getPoint();// 获取当前坐标 Point locationPoint = getLocation();// 获取窗体坐标 int x = locationPoint.x + point.x - pressedPoint.x;// 计算移动后的新坐标 int y = locationPoint.y + point.y - pressedPoint.y; setLocation(x, y);// 改变窗体位置 } }
package com.code; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class JoinedPipes { public static void main(String[] args) { // initialize Input 1 : Length of pipes // initialize Input 2 : No. of pipes int input1[] = new int[] { 4, 7, 2, 5, 6, 3, 8, 12, 3 }; //int input1[] = new int[] { 4, 3, 2}; int input2 = 9; // Get the minimum length of joined pipes in ascending order int[] value = JoinedPipes.getJoinedPipes(input1, input2); for (int v:value) { System.out.print(v + " "); } } private static int[] getJoinedPipes(int[] input1, int input2) { try { validateInput(input1, input2); return minPipeCost(input1); } catch (IllegalArgumentException ex) { throw ex; } } /** * Validate the Given inputs * * @param input1 * @param input2 */ private static void validateInput(int[] input1, int input2) { if (input2 <= 0) { throw new IllegalArgumentException("The input cannot be zero"); } if (input1 == null) { throw new IllegalArgumentException("Input Array is Null, Please check"); } if (input1.length != input2) { throw new IllegalArgumentException("Invalid Input for the array 1 Please check"); } } /** * To find the minimum length of the Pipes in the given input * * @param input1 * @param input2 * @return output - array(minimum length of joined pipes in ascending * order) */ public static int[] minPipeCost(int[] input1) { if (input1.length == 1) { return new int[] { 0 }; } if (input1.length == 2) { return new int[] { input1[0] + input1[1] }; } // sort input array Arrays.sort(input1); List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < input1.length; i++) { list.add(Integer.valueOf(input1[i])); } // Output array int[] output = new int[input1.length - 1]; int j = 0; do { int value = list.get(0) + list.get(1); list.remove(0); list.remove(0); addItemToSortedList(value, list); output[j++] = value; if (list.size()<3) { output[j] = list.get(0) + list.get(1); break; } } while (true); return output; } private static void addItemToSortedList(int item, List<Integer> list) { for (int i = 0; i < list.size(); i++) { if (item <= list.get(i)) { list.add(i, item); return; } else { continue; } } list.add(item); } }
package com.jyn.language.Java学习.集合; import java.util.HashMap; import java.util.IdentityHashMap; /* * 你真的了解IdentityHashMap与HashMap区别吗? * https://blog.csdn.net/zzg1229059735/article/details/78991200 */ public class IdentityHashMapTest { /** * 判断是否为同一Entry? * * HashMap * if (e.hash == hash && ((k = e.key) == key || key.equals(k))) * * IdentityHashMap * if (item == k) */ public static void main(String[] args) { identityTest(); } private static void identityTest() { IdentityHashMap<Integer, String> identityHashMap = new IdentityHashMap<>(); HashMap<Integer, String> hashMap = new HashMap<>(); Integer integer0 = new Integer(0); Integer integer1 = new Integer(0); Integer integer2 = new Integer(0); identityHashMap.put(integer0, "0"); identityHashMap.put(integer1, "1"); identityHashMap.put(integer2, "2"); hashMap.put(integer0, "0"); hashMap.put(integer1, "1"); hashMap.put(integer2, "2"); System.out.println("identityHashMap size:" + identityHashMap.size()); System.out.println("hashMap size:" + hashMap.size()); } }
package com.trump.auction.back.userRecharge.model; import lombok.Data; import java.util.Date; /** * Created by wangYaMin on 2018/1/10. */ @Data public class AccountRechargeOrder { private Integer id; private Integer userId; private String userName; private String userPhone; private Integer outMoney; private Integer intoCoin; private Integer rechargeType; private String rechargeTypeName; private Integer tradeStatus; private Integer payStatus; private String payRemark; private String resultJson; private String orderNo; private String outTradeNo; private Integer orderStatus; private Date createTime; private Date updateTime; }
package com.flower.api.handler; import com.flower.common.bean.ResponseResult; import com.flower.common.exception.BizException; import com.flower.common.exception.SysException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /** * @author cyk * @date 2018/8/15/015 09:34 * @email choe0227@163.com * @desc 全局异常处理 * @modifier * @modify_time * @modify_remark */ @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(BizException.class) @ResponseBody ResponseResult handleBizException(BizException biz){ ResponseResult result = new ResponseResult(); result.setStatusCode(biz.getErrorCode().getCode()); result.setStatusString(biz.getErrorCode().getReturnMsg()); biz.printStackTrace(); return result; } @ExceptionHandler(SysException.class) @ResponseBody ResponseResult handleSysException(SysException sysException){ ResponseResult result = new ResponseResult(); result.setStatusCode(-1); result.setStatusString(sysException.getMessage()); sysException.printStackTrace(); return result; } @ExceptionHandler(Exception.class) @ResponseBody ResponseResult handleException(Exception exception){ exception.printStackTrace(); return ResponseResult.error(); } }
package com.kinsella.people.business.service; import com.kinsella.people.data.entity.Address; import java.util.List; import java.util.Optional; public interface AddressService { Optional<Address> create(long id, long personId, String street, String city, String state, String postalCode); Optional<Address> create(Address address); Optional<Address> get(long id); List<Address> getAll(); Optional<Address> update(long id, String street, String city, String state, String postalCode); boolean delete(long id); }
package com.mediafire.sdk.log; import java.util.LinkedList; import java.util.List; /** * Created by Chris on 5/26/2015. */ public class DefaultApiTransactionStore implements MFLogStore<ApiTransaction> { public final LinkedList<ApiTransaction> apiTransactions = new LinkedList<ApiTransaction>(); private final Object lock = new Object(); @Override public long deleteAll() { synchronized (lock) { int size = apiTransactions.size(); apiTransactions.clear(); return size; } } @Override public long getCount() { synchronized (lock) { return apiTransactions.size(); } } @Override public long addLog(ApiTransaction apiTransaction) { synchronized (lock) { boolean added = apiTransactions.add(apiTransaction); if (added) { return apiTransactions.size(); } else { return -1; } } } public void addLogs(List<ApiTransaction> apiTransactions) { synchronized (lock) { apiTransactions.addAll(apiTransactions); } } public LinkedList<ApiTransaction> getAll() { synchronized (lock) { return apiTransactions; } } }
package cn.itcast.core.controller; import cn.itcast.core.pojo.entity.PageResult; import cn.itcast.core.pojo.entity.Result; import cn.itcast.core.pojo.good.Brand; import cn.itcast.core.service.BrandService; import com.alibaba.dubbo.config.annotation.Reference; import org.apache.ibatis.io.ResolverUtil; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; /** * 品牌管理 */ @RestController @RequestMapping("/brand") public class BrandController { @Reference private BrandService brandService; /** * 查询品牌所有数据 * @return 品牌集合 */ @RequestMapping("/findAll") public List<Brand> findAll() { return brandService.findAll(); } /** * 分页查询 * @param page 当前页 * @param rows 每页展示多少条数据 * @return */ @RequestMapping("/findPage") public PageResult findPage(Integer page, Integer rows) { PageResult pageResult= brandService.findPage(null ,page, rows); return pageResult; } /** * 添加 * @param brand 品牌对象 * @return */ @RequestMapping("/add") public Result add(@RequestBody Brand brand) { try { brandService.add(brand); return new Result(true, "添加成功!"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "添加失败!"); } } /** * 修改回显数据 * @param id * @return */ @RequestMapping("/findOne") public Brand findOne(Long id) { Brand one = brandService.findOne(id); return one; } /** * 修改 * @param brand * @return */ @RequestMapping("/update") public Result update(@RequestBody Brand brand) { try { brandService.update(brand); return new Result(true, "修改成功!"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "修改失败!"); } } /** * 删除 * @param ids * @return */ @RequestMapping("/delete") public Result delete(Long[] ids) { try { brandService.delete(ids); return new Result(true, "删除成功!"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "删除失败!"); } } /** * 高级查询(分页, 高级查询) * @param page 当前页 * @param rows 每页展示多少条数据 * @param brand 需要查询的条件品牌对象 * @return */ @RequestMapping("/search") public PageResult search(Integer page, Integer rows, @RequestBody Brand brand) { PageResult pageResult = brandService.findPage(brand, page, rows); return pageResult; } /** * 查询品牌所有数据, 返回, 给模板中select2下拉框使用, 数据格式是select2下拉框规定的 * 例如: $scope.brandList={data:[{id:1,text:'联想'},{id:2,text:'华为'},{id:3,text:'小米'}]} */ @RequestMapping("/selectOptionList") public List<Map> selectOptionList() { return brandService.selectOptionList(); } }
package de.evoila.cf.model.api.endpoint; import de.evoila.cf.broker.model.ServiceInstance; import de.evoila.cf.model.enums.BackupType; import org.springframework.data.mongodb.core.mapping.DBRef; import java.util.Map; /** * @author Johannes Hiemer. */ public class EndpointCredential { @DBRef private ServiceInstance serviceInstance; private String host; private int port; private String username; private String password; private String backupUsername; private String backupPassword; private String database; private BackupType type; private Map<String, Object> parameters; public ServiceInstance getServiceInstance() { return serviceInstance; } public void setServiceInstance(ServiceInstance serviceInstance) { this.serviceInstance = serviceInstance; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getBackupUsername() { return backupUsername; } public void setBackupUsername(String backupUsername) { this.backupUsername = backupUsername; } public String getBackupPassword() { return backupPassword; } public void setBackupPassword(String backupPassword) { this.backupPassword = backupPassword; } public String getDatabase() { return database; } public void setDatabase(String database) { this.database = database; } public BackupType getType() { return type; } public void setType(BackupType type) { this.type = type; } public void setTypeFromString(String type) { this.type = BackupType.valueOf(type); } public Map<String, Object> getParameters() { return parameters; } public void setParameters(Map<String, Object> parameters) { this.parameters = parameters; } }
/* $Id$ */ package djudge.utils; public class XMLConfigurable implements XMLConfigurableInterface { @Override public String getConfigFilename() { return this.getClass().toString(); } }
package com.aforo255.exam.repository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.aforo255.exam.domain.Invoice; @Repository public interface InvoiceRepository extends CrudRepository<Invoice, Integer> , JpaSpecificationExecutor<Invoice> { }
import Framework.Settings; public class Main { public static void main (String[] args) throws InstantiationException, IllegalAccessException { Settings Settings = new Settings(); Settings.setMutationRate(0.03); Settings.setPopulationSize(50); Settings.setNumberOfSurvivalInGeneration(5); GeneticAlgorithm<DNAMathFunction> geneticAlgorithm = new GeneticAlgorithm(Settings, DNAMathFunction.class); geneticAlgorithm.initilizeAlgorithm(); } }
package com.hunger.rpc.serialize; import io.netty.buffer.ByteBuf; import java.io.IOException; /** * Created by 小排骨 on 2018/1/10. */ public interface MessageCodecUtil { int MESSAGE_LENGTH = 4; /** * 编码 * @param out * @param message * @throws IOException */ void encode(final ByteBuf out, final Object message) throws IOException; /** * 解码 * @param body * @return * @throws IOException */ Object decode(byte[] body) throws IOException; }
package com.organisation.library.repository; import com.organisation.library.entities.Author; import org.springframework.data.repository.CrudRepository; public interface AuthorRepository extends CrudRepository<Author, Long> { }
/* * AlleleDepthUtil */ package net.maizegenetics.dna.snp.depth; import java.util.Arrays; /** * Depth compression utility. Depths are scored in byte (256 states). 0 to 127 are used for exact depth vaules. * -128 to -1 are used for log approximations (1.0746^(-x)). This permits depths upto 10,482 to be stored * with exact precision for low values, and <3% error for high depths. * @author Terry Casstevens * @author Robert Bukowski */ public class AlleleDepthUtil { private static final double LOG_BASE = 1.0746; // LOG_BASE^128 = 10,482 private static final double R_LOG_CONV = 1.0 / Math.log(LOG_BASE); private static final double LOG_CONV = 1.0 / R_LOG_CONV; private static final int[] BYTE_TO_INT = new int[256]; private static final int MAX_ACC_DEPTH = 182; private static final int MIN_ACC_BYTE = 127 - MAX_ACC_DEPTH; private static final int OFFSET = 126; private static final double ADJ = 0.5; static { Arrays.fill(BYTE_TO_INT, -1); for (int i = 0; i < 256; i++) { BYTE_TO_INT[i] = decode((byte) i); } } private AlleleDepthUtil() { // utility } /** * Returns the depth combined depths in byte format. Converts both to integers, adds, and reconverts back. * @param depth1 first depth in byte format * @param depth2 second depth in byte format * @return byte version of combined depth */ public static byte addByteDepths(byte depth1, byte depth2) { return depthIntToByte(depthByteToInt(depth1)+depthByteToInt(depth2)); } /** * Converts integer depth to byte version. Positive return values are exact, * negative return values are log approximations */ public static byte depthIntToByte(int depth) { byte bdepth; int itd; if (depth <= 127) { itd = depth; } else if (depth <= MAX_ACC_DEPTH) { itd = 127 - depth; } else { itd = (int) (-R_LOG_CONV * Math.log(depth - OFFSET)); if (itd < -128) { itd = -128; } } bdepth = (byte) itd; return bdepth; } /** * Converts integer array of depth to byte array version. Positive return values are exact, * negative return values are log approximations */ public static byte[] depthIntToByte(int[] depth) { byte[] result=new byte[depth.length]; for (int i=0; i<result.length; i++) { result[i]=depthIntToByte(depth[i]); } return result; } /** * Converts a two dimensional integer array of depths to a 2D byte array version. * Positive return values are exact, negative return values are log approximations */ public static byte[][] depthIntToByte(int[][] depth) { byte[][] result = new byte[depth.length][depth[0].length]; for (int i=0; i<result.length; i++) { result[i]=depthIntToByte(depth[i]); } return result; } /** * Converts byte depth to integer version. Positive depths value are exact, negative depths are log approximations */ public static int depthByteToInt(byte depth) { return BYTE_TO_INT[depth & 0xFF]; } /** * Converts byte arrays of depth to integer array version. * Positive depths value are exact, negative depths are log approximations */ public static int[] depthByteToInt(byte[] depth) { int[] result=new int[depth.length]; for (int i=0; i<result.length; i++) { result[i]=depthByteToInt(depth[i]); } return result; } private static int decode(byte bdepth) { int depth; if (bdepth >= 0) { depth = bdepth; } else if (bdepth >= MIN_ACC_BYTE) { depth = 127 - bdepth; } else { depth = OFFSET + (int) (Math.exp(-LOG_CONV * (bdepth - ADJ))); } return depth; } }
package de.cuuky.varo.listener.saveable; import org.bukkit.block.Chest; import org.bukkit.block.DoubleChest; import org.bukkit.block.Furnace; import org.bukkit.block.Hopper; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryMoveItemEvent; import de.cuuky.varo.Main; import de.cuuky.varo.player.stats.stat.inventory.VaroSaveable; public class InventoryMoveListener implements Listener { @EventHandler public void onInventoryMove(InventoryMoveItemEvent e) { if(!Main.getGame().isStarted()) return; if(!(e.getInitiator().getHolder() instanceof Hopper)) return; if(!(e.getSource().getHolder() instanceof Chest) && !(e.getSource().getHolder() instanceof Furnace) && !(e.getSource().getHolder() instanceof DoubleChest)) return; if(e.getSource().getHolder() instanceof Chest) { Chest chest = (Chest) e.getSource().getHolder(); if(VaroSaveable.getByLocation(chest.getLocation()) != null) { e.setCancelled(true); return; } } else if(e.getSource().getHolder() instanceof DoubleChest) { DoubleChest dc = (DoubleChest) e.getSource().getHolder(); Chest r = (Chest) dc.getRightSide(); Chest l = (Chest) dc.getLeftSide(); if(VaroSaveable.getByLocation(l.getLocation()) != null || VaroSaveable.getByLocation(r.getLocation()) != null) { e.setCancelled(true); return; } } else { Furnace f = (Furnace) e.getSource().getHolder(); if(VaroSaveable.getByLocation(f.getLocation()) != null) { e.setCancelled(true); return; } } } }
package iotwearable.editor.factory; import org.eclipse.gef.requests.CreationFactory; import iotwearable.model.iotw.DHT11; import iotwearable.model.iotw.IotwFactory; /** * Used to create new DHT11 */ public class DHT11Factory implements CreationFactory{ @Override public Object getNewObject() { return IotwFactory.eINSTANCE.createDHT11(); } @Override public Object getObjectType() { return DHT11.class; } }
package Patterns; /** * 工厂方法 * Created by Administrator on 2017/9/23. */ public class FactoryMehtod { //当一个类不知道它所必须创建的对象的类 //一个类希望由它的子类来指定它所创建的对象 //类将创建对象的职责委托给多个帮助子类中的某一个 //只有一个抽象产品类 //具体工厂类只能创建一个具体产品类的实例 public static void main(String[] args) { IFactory2 factory = new Factory2(); IProduct prodect = factory.createProduct(); prodect.productMethod(); } } interface IProduct { public void productMethod(); } class Product implements IProduct{ @Override public void productMethod() { System.out.println("产品"); } } interface IFactory2 { public IProduct createProduct(); } class Factory2 implements IFactory2 { public IProduct createProduct() { return new Product(); } }
package com.lenovohit.ssm.payment.hisModel; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Table; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import com.lenovohit.core.model.Model; /** * HIS - 住院预缴款 cw_zyyjk * * @author fanyang * */ @Entity @Table(name = "CW_ZYYJK") public class ZYYJKHis implements Model { /** * */ private static final long serialVersionUID = -5884173267505198107L; private Integer id;//JYID 交易ID private Integer zyid;//ZYID 住院ID private String zyh;//ZYH 住院号 private String sjh;//SJH 收据号 private BigDecimal yjje;//YJJE 预缴金额 private String fkfs;//FKFS private Integer khyh;//KHYH private Integer yhzh;//YHZH private String dwmc;//DWMC private Date yjsj;//YJSJ 预缴时间 private String yqdm;//YQDM private String ztbz;//ZTBZ 状态标志 private Integer czzid;//CZZID private String bzdm;//BZDM private String ly;//LY 来源 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getZyid() { return zyid; } public void setZyid(Integer zyid) { this.zyid = zyid; } public String getZyh() { return zyh; } public void setZyh(String zyh) { this.zyh = zyh; } public String getSjh() { return sjh; } public void setSjh(String sjh) { this.sjh = sjh; } public BigDecimal getYjje() { return yjje; } public void setYjje(BigDecimal yjje) { this.yjje = yjje; } public String getFkfs() { return fkfs; } public void setFkfs(String fkfs) { this.fkfs = fkfs; } public Integer getKhyh() { return khyh; } public void setKhyh(Integer khyh) { this.khyh = khyh; } public Integer getYhzh() { return yhzh; } public void setYhzh(Integer yhzh) { this.yhzh = yhzh; } public String getDwmc() { return dwmc; } public void setDwmc(String dwmc) { this.dwmc = dwmc; } public Date getYjsj() { return yjsj; } public void setYjsj(Date yjsj) { this.yjsj = yjsj; } public String getYqdm() { return yqdm; } public void setYqdm(String yqdm) { this.yqdm = yqdm; } public String getZtbz() { return ztbz; } public void setZtbz(String ztbz) { this.ztbz = ztbz; } public Integer getCzzid() { return czzid; } public void setCzzid(Integer czzid) { this.czzid = czzid; } public String getBzdm() { return bzdm; } public void setBzdm(String bzdm) { this.bzdm = bzdm; } public String getLy() { return ly; } public void setLy(String ly) { this.ly = ly; } @Override public boolean _newObejct() { return 0 == this.getId(); } /** * 重载toString; */ public String toString() { return ToStringBuilder.reflectionToString(this); } /** * 重载hashCode; */ public int hashCode() { return new HashCodeBuilder().append(this.getId()).toHashCode(); } /** * 重载equals */ public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } }
package com.gxtc.huchuan.im.itemview; import android.app.Activity; import android.view.View; import com.gxtc.commlibrary.recyclerview.base.ItemViewDelegate; import com.gxtc.commlibrary.recyclerview.base.ViewHolder; import com.gxtc.huchuan.R; import com.gxtc.huchuan.im.provide.RedPacketMessage; import com.gxtc.huchuan.pop.PopReward; import com.gxtc.huchuan.utils.StringUtil; import io.rong.imlib.model.Message; /** * Created by Gubr on 2017/2/21. * 红包 */ public class RedPacketMessageView implements ItemViewDelegate<Message> { private final Activity mActivity; private PopReward mPopReward; private View.OnClickListener l; public RedPacketMessageView(Activity activity) { mActivity = activity; } private static final String TAG = "RedPacketMessageView"; @Override public int getItemViewLayoutId() { return R.layout.item_chat_red_packet; } @Override public boolean isForViewType(Message item, int position) { return "XM:RpMsg".equals(item.getObjectName()); } @Override public void convert(ViewHolder holder, Message message, int position) { RedPacketMessage content = (RedPacketMessage) message.getContent(); String money = StringUtil.formatMoney(2,content.getPrice()); holder.setText(R.id.tv_message, content.getContent()).setText(R.id.tv_red_packet_info, money + "元红包").setTag(R.id.ll_red_packet_area, content).setOnClickListener(R.id.ll_red_packet_area, l); } public RedPacketMessageView setOnClickListener(View.OnClickListener l) { this.l = l; return this; } }
package com.cb.cbfunny.qb.task; import android.graphics.Bitmap; import android.os.AsyncTask; import android.widget.ImageView; import com.cb.cbfunny.qb.imgutils.AsyncImageGetUtil; public class ImgLoadTask extends AsyncTask<String, Void, Bitmap> { AsyncImageGetUtil loader; ImageView imgageView; String picUrl; private ImgLoadTaskCall callback; public ImgLoadTask(AsyncImageGetUtil loader,ImageView imgageView,String picUrl) { this.loader = loader; this.imgageView = imgageView; this.picUrl = picUrl; } /** * 调用异步任务的时候实现的接口 用来做图片的获取前后的工作 * @author yan * */ public interface ImgLoadTaskCall{ /** * 在获取图片之前 */ public void beforeImgGet(); /** * 在获取到图片之后 * @param bitmap */ public void afterImgGet(Bitmap bitmap); } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Bitmap doInBackground(String... params) { return loader.getImageByUrl(imgageView, picUrl); } @Override protected void onPostExecute(Bitmap bitmap) { imgageView.setImageBitmap(bitmap); super.onPostExecute(bitmap); } }
package com.example.jeremychen.musicapp.utils; /** * Created by jeremychen on 2018/7/25. */ public class Music { private String artistName; private String musicName; private String onlineMusicUrl; private String picUrl; private String collectionPrice; private String trackPrice; private String country; private String currency; private String kindMusic; private String releaseDate; private String trackViewUrl; private int trackTime; public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public int getTrackTime() { return trackTime; } public void setTrackTime(int trackTime) { this.trackTime = trackTime; } public String getArtistName() { return artistName; } public void setArtistName(String artistName) { this.artistName = artistName; } public String getMusicName() { return musicName; } public void setMusicName(String musicName) { this.musicName = musicName; } public String getOnlineMusicUrl() { return onlineMusicUrl; } public void setOnlineMusicUrl(String onlineMusicUrl) { this.onlineMusicUrl = onlineMusicUrl; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getCollectionPrice() { return collectionPrice; } public void setCollectionPrice(String collectionPrice) { this.collectionPrice = collectionPrice; } public String getTrackPrice() { return trackPrice; } public void setTrackPrice(String trackPrice) { this.trackPrice = trackPrice; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public String getKindMusic() { return kindMusic; } public void setKindMusic(String kindMusic) { this.kindMusic = kindMusic; } public String getReleaseDate() { return releaseDate; } public void setReleaseDate(String releaseDate) { this.releaseDate = releaseDate; } public String getTrackViewUrl() { return trackViewUrl; } public void setTrackViewUrl(String trackViewUrl) { this.trackViewUrl = trackViewUrl; } }
package cn.com.onlinetool.fastpay.pay.wxpay.util; import cn.com.onlinetool.fastpay.constants.EncryptionTypeConstants; import cn.com.onlinetool.fastpay.pay.wxpay.config.WXPayConfig; import cn.com.onlinetool.fastpay.pay.wxpay.constants.WXPayConstants; import cn.com.onlinetool.fastpay.pay.wxpay.domain.WXPayDomain; import cn.com.onlinetool.fastpay.pay.wxpay.domain.WXPayReport; import cn.com.onlinetool.fastpay.util.ConverterUtil; import cn.com.onlinetool.fastpay.util.OkHttpRequestUtil; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.util.EntityUtils; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.io.InputStream; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.security.KeyStore; import java.security.SecureRandom; import java.util.Map; import static cn.com.onlinetool.fastpay.pay.wxpay.constants.WXPayConstants.USER_AGENT; @Slf4j public class WXPayRequestUtil { private WXPayConfig config; public WXPayRequestUtil(WXPayConfig config) { this.config = config; } /** * 请求,只请求一次,不做重试 * @param domain * @param urlSuffix * @param uuid * @param data * @param connectTimeoutMs * @param readTimeoutMs * @param useCert 是否使用证书,针对退款、撤销等操作 * @return * @throws Exception */ private String requestOnce(final String domain, String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean useCert) throws Exception { BasicHttpClientConnectionManager connManager; if (useCert) { // 证书 char[] password = config.getMchId().toCharArray(); InputStream certStream = config.getCert(); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(certStream, password); // 实例化密钥库 & 初始化密钥工厂 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password); // 创建 SSLContext SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), null, new SecureRandom()); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContext, new String[]{"TLSv1"}, null, new DefaultHostnameVerifier()); connManager = new BasicHttpClientConnectionManager( RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory) .build(), null, null, null ); } else { connManager = new BasicHttpClientConnectionManager( RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", SSLConnectionSocketFactory.getSocketFactory()) .build(), null, null, null ); } HttpClient httpClient = HttpClientBuilder.create() .setConnectionManager(connManager) .build(); String url = "https://" + domain + urlSuffix; HttpPost httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build(); httpPost.setConfig(requestConfig); StringEntity postEntity = new StringEntity(data, "UTF-8"); httpPost.addHeader("Content-Type", "text/xml"); httpPost.addHeader("User-Agent", USER_AGENT + " " + config.getMchId()); httpPost.setEntity(postEntity); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); return EntityUtils.toString(httpEntity, "UTF-8"); } private String request(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean useCert, boolean autoReport) throws Exception { Exception exception = null; long elapsedTimeMillis = 0; long startTimestampMs = WXPayUtil.getCurrentTimestampMs(); boolean firstHasDnsErr = false; boolean firstHasConnectTimeout = false; boolean firstHasReadTimeout = false; WXPayDomain.DomainInfo domainInfo = config.getWxPayDomain().getDomain(config); if (domainInfo == null) { throw new Exception("WXPayConfig.getWXPayDomain().getDomain() is empty or null"); } try { // String result = requestOnce(domainInfo.domain, urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, useCert); String url = domainInfo.domain + urlSuffix; String contentType = "application/xml; charset=utf-8"; String result; if (null != config.getCert() && config.getRetryNum() > 0) { result = OkHttpRequestUtil.syncPostRequest(url, data, contentType, USER_AGENT, config.getRetryNum(), config.getCert(), "PKCS12", config.getMchId()).body().string(); } else if (null != config.getCert()) { result = OkHttpRequestUtil.syncPostRequest(url, data, contentType, USER_AGENT, config.getCert(), "PKCS12", config.getMchId()).body().string(); } else if (config.getRetryNum() > 0) { result = OkHttpRequestUtil.syncPostRequest(url, data, contentType, USER_AGENT, config.getRetryNum()).body().string(); } else { result = OkHttpRequestUtil.syncPostRequest(url, data, contentType, USER_AGENT).body().string(); } elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs() - startTimestampMs; config.getWxPayDomain().report(domainInfo.domain, elapsedTimeMillis, null); WXPayReport.getInstance(config).report( uuid, elapsedTimeMillis, domainInfo.domain, domainInfo.primaryDomain, connectTimeoutMs, readTimeoutMs, firstHasDnsErr, firstHasConnectTimeout, firstHasReadTimeout); return result; } catch (UnknownHostException ex) { // dns 解析错误,或域名不存在 exception = ex; firstHasDnsErr = true; elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs() - startTimestampMs; log.warn("UnknownHostException for domainInfo {}", domainInfo); WXPayReport.getInstance(config).report( uuid, elapsedTimeMillis, domainInfo.domain, domainInfo.primaryDomain, connectTimeoutMs, readTimeoutMs, firstHasDnsErr, firstHasConnectTimeout, firstHasReadTimeout ); } catch (SocketTimeoutException ex) { exception = ex; firstHasReadTimeout = true; elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs() - startTimestampMs; log.warn("timeout happened for domainInfo {}", domainInfo); WXPayReport.getInstance(config).report( uuid, elapsedTimeMillis, domainInfo.domain, domainInfo.primaryDomain, connectTimeoutMs, readTimeoutMs, firstHasDnsErr, firstHasConnectTimeout, firstHasReadTimeout); } catch (Exception ex) { exception = ex; elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs() - startTimestampMs; WXPayReport.getInstance(config).report( uuid, elapsedTimeMillis, domainInfo.domain, domainInfo.primaryDomain, connectTimeoutMs, readTimeoutMs, firstHasDnsErr, firstHasConnectTimeout, firstHasReadTimeout); } config.getWxPayDomain().report(domainInfo.domain, elapsedTimeMillis, exception); throw exception; } /** * 可重试的,非双向认证的请求 * * @param uuid * @param data * @return */ public String requestWithoutCert(String urlSuffix, String uuid, String data, boolean autoReport) throws Exception { return this.request(urlSuffix, uuid, data, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs(), false, autoReport); } /** * 可重试的,非双向认证的请求 * * @param uuid * @param data * @param connectTimeoutMs * @param readTimeoutMs * @return */ public String requestWithoutCert(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean autoReport) throws Exception { return this.request(urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, false, autoReport); } /** * 可重试的,双向认证的请求 * * @param urlSuffix * @param uuid * @param data * @return */ public String requestWithCert(String urlSuffix, String uuid, String data, boolean autoReport) throws Exception { return this.request(urlSuffix, uuid, data, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs(), true, autoReport); } /** * 可重试的,双向认证的请求 * * @param urlSuffix * @param uuid * @param data * @param connectTimeoutMs * @param readTimeoutMs * @return */ public String requestWithCert(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean autoReport) throws Exception { return this.request(urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, true, autoReport); } /** * 不需要证书的请求 * * @param reqData 向wxpay post的请求数据 * @return API返回数据 * @throws Exception */ public String requestWithoutCert(Map<String, String> reqData) throws Exception { String urlSuffix; if (config.isUseSandbox()) { urlSuffix = WXPayConstants.SANDBOX_UNIFIEDORDER_URL_SUFFIX; } else { urlSuffix = WXPayConstants.UNIFIEDORDER_URL_SUFFIX; } String msgUUID = reqData.get("nonce_str"); String reqBody = ConverterUtil.mapToXml(reqData); String resp = this.requestWithoutCert(urlSuffix, msgUUID, reqBody, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs(), config.isAutoReport()); return resp; } /** * 需要证书的请求 * * @param reqData 向wxpay post的请求数据 Map * @return API返回数据 * @throws Exception */ public String requestWithCert(Map<String, String> reqData) throws Exception { String urlSuffix; if (config.isUseSandbox()) { urlSuffix = WXPayConstants.SANDBOX_ORDERQUERY_URL_SUFFIX; } else { urlSuffix = WXPayConstants.ORDERQUERY_URL_SUFFIX; } String msgUUID = reqData.get("nonce_str"); String reqBody = ConverterUtil.mapToXml(reqData); String resp = this.requestWithCert(urlSuffix, msgUUID, reqBody, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs(), config.isAutoReport()); return resp; } /** * 向 Map 中添加 appid、mch_id、nonce_str、sign_type、sign <br> * 该函数适用于商户适用于统一下单等接口,不适用于红包、代金券接口 * * @param reqData * @return * @throws Exception */ public Map<String, String> fillRequestData(Map<String, String> reqData) throws Exception { reqData.put("appid", config.getAppid()); reqData.put("mch_id", config.getMchId()); reqData.put("nonce_str", WXPayUtil.generateNonceStr()); if (EncryptionTypeConstants.MD5.equals(config.getSignType())) { reqData.put("sign_type", WXPayConstants.MD5); } else if (EncryptionTypeConstants.HMACSHA256.equals(config.getSignType())) { reqData.put("sign_type", WXPayConstants.HMACSHA256); } reqData.put("sign", WXPayUtil.generateSignature(reqData, config.getKey(), config.getSignType())); return reqData; } }
package pl.jwrabel.trainings.javandwro2; import java.util.*; /** * Created by RENT on 2017-03-22. */ public class DateTest { public static void main(String[] args) { Date date1 = new Date(1, 12, 2016); Date date2 = new Date(4, 6, 2016); Date date3 = new Date(5, 6, 2010); Date date4 = new Date(4, 6, 2010); List<Date> dates = new ArrayList<>(); dates.add(date1); dates.add(date2); dates.add(date3); dates.add(date4); // System.out.println("Lista przed posortowaniem"); // dates.forEach((x -> System.out.println(x))); // Collections.sort(dates); // System.out.println("Lista po sortowaniu"); // dates.forEach(x -> System.out.println(x)); System.out.println("Lista przed posortowaniem"); dates.forEach((x -> System.out.println(x))); dates.sort(new Comparator<Date>() { @Override public int compare(Date d1, Date d2) { if (d1.getYear() > d2.getYear()) { return 1; } else if (d1.getYear() == d2.getYear()) { if (d1.getMonth() > d2.getMonth()) { return 1; } else if (d1.getMonth() == d2.getMonth()) { if (d1.getDay() > d2.getDay()) { return 1; } else if (d1.getDay() == d2.getDay()) { return 0; } else { return -1; } } else { return -1; } } else { return -1; } } }); System.out.println("Lista po sortowaniu"); dates.forEach(x -> System.out.println(x)); } }
package xml; import domain.Offer; import lombok.extern.slf4j.Slf4j; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.List; @Slf4j public class XmlExtractor { public static void extract() { List<Offer> offers = new ArrayList<>(); try { String keyWord = "boots"; String ABOUT_YOU_URL = "http://www.aboutyou.de/suche?term="; Document searchByKeyWord = Jsoup.connect(ABOUT_YOU_URL + keyWord).get(); Elements searchResultPage = searchByKeyWord.getElementsByClass("styles__tile--2s8XN col-sm-6 col-md-4 col-lg-4"); for (Element element : searchResultPage ) { Elements linkToProductPage = element.getElementsByTag("a"); String absHref = linkToProductPage.attr("abs:href"); Document productPage = Jsoup.connect(absHref).get(); Elements articleId = productPage.getElementsByClass("styles__articleNumber--1UszN"); Elements description = productPage.getElementsByClass("styles__textElement--3QlT_"); Elements productName = element.getElementsByClass("styles__productName--2z0ZU"); Elements brand = element.getElementsByClass("styles__brandName--2XS22"); Elements color = productPage.getElementsByClass("styles__title--UFKYd styles" + "__isHoveredState--2BBt9"); Elements price = element.getElementsByClass("productPrices prices__normal--3SBAf"); Elements initialPrice = element.getElementsByClass("prices__strike--Htmqx"); Offer offer = new Offer(); offer.setArticleId(articleId.text()); offer.setProductName(productName.text()); offer.setBrand(brand.text()); offer.setColor(color.text()); offer.setPrice(price.text()); offer.setInitialPrice(initialPrice.text()); offer.setDescription(description.text()); offers.add(offer); } } catch (Exception e) { log.error("Can't extract you xml file!"); } System.out.println(offers.size()); XmlWriter.writeToXmlFile(offers); System.out.println("Amount of extracted products: " + offers.size()); } }
package com.arduino.bluetooth; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.res.AssetManager; import android.content.res.Configuration; import android.graphics.Bitmap; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.telephony.SmsManager; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.Calendar; import java.util.Set; /** * 메인 엑티비티 */ public class MainActivity extends BaseActivity { private BluetoothAdapter mBluetoothAdapter = null; // 블루투스 아답터 // 블루투스 디바이스 객체 private BluetoothDevice mBluetoothDevice; // 연결 쓰레드 클래스 private ConnectedThread mConnectedThread; private Context mContext; protected static final int SHOW_TOAST = 0; private WebView mWebview; // 블루투스 장치 설정 private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (BluetoothDevice.ACTION_FOUND.equals(action)) { } else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) { } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { Log.i("TAGGGG", "ACTION_DISCOVERY_FINISHED"); } else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) { Log.i("TAGGGG", "ACTION_ACL_DISCONNECT_REQUESTED"); } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { Log.i(DEBUG_TAG, "ACTION_ACL_DISCONNECTED"); if (mBluetoothDevice != null) { if (device.getAddress().equals(mBluetoothDevice.getAddress())) { Toast.makeText(MainActivity.this, "장치가 끊겼습니다.", Toast.LENGTH_SHORT).show(); } } } } }; // ui 쓰레드용 // ui 메시지 전송을 위한 핸들러 Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_TOAST: { // 토스트 메시지 표시 Toast toast = Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT); toast.show(); break; } } } }; @SuppressLint("JavascriptInterface") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; // 화면이 꺼지지 않게 설정 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 블루투스 지원 여부 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // null 이면 지원하지 않음.. Toast.makeText(mContext, "단말기에서 블루투스를 지원하지 않습니다.", Toast.LENGTH_SHORT).show(); finish(); // 종료 } // 블루투스 상태 체크 리시버 checkBluetoothStatus(); mWebview = (WebView) findViewById(R.id.webview); mWebview.getSettings().setJavaScriptEnabled(true); mWebview.loadUrl("file:///android_asset/index.html"); mWebview.setWebViewClient(new myWebClient()); mWebview.addJavascriptInterface(new WebViewInterface(), "Android"); //JavascriptInterface 객체화 } public class WebViewInterface { @JavascriptInterface public void connect () { searchDeivce(); Log.i("tag", "aaa"); } @JavascriptInterface public void outDistance(final String distance) { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Log.i("tag", "out:" + distance); sendMessage("out:" + distance); } }); } @JavascriptInterface public void inDistance(final String distance) { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Log.i("tag", "in:" + distance); sendMessage("in:" + distance); } }); } @JavascriptInterface public void setting() { Intent intent = new Intent(getBaseContext(), SettingActivity.class); startActivityForResult(intent, SEARCH_DEVICE); } @JavascriptInterface public void finish () { finishConfrim(); } } private void initArduinoTime(){ Calendar cal = Calendar.getInstance(); cal.get(Calendar.HOUR_OF_DAY); String msg = String.format("s:%02d%02d%02d\n", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)); //Toast.makeText(mContext, msg +" 로 시간 설정", Toast.LENGTH_SHORT).show(); sendMessage(msg); } /** * 블루수트 상태 체크 리시버 등록 */ private void checkBluetoothStatus() { // 블루투스 상태 체크 리시버 IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); registerReceiver(mReceiver, filter1); registerReceiver(mReceiver, filter2); registerReceiver(mReceiver, filter3); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); } /** * 블루투스 검색 */ private void searchDeivce() { Intent intent = new Intent(getBaseContext(), SearchBluetoothDeviceActivity.class); startActivityForResult(intent, SEARCH_DEVICE); } /** * resume 되면 테이블상태 재조회 */ @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); // loadState(); // 블루투스가 활성화가 안되어 있으면 if (!mBluetoothAdapter.isEnabled()) { // 블루투스 권한요청하기 Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, REQUEST_ENABLE); } } /** * 블루투스 응답 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK) { return; } // TODO Auto-generated method stub if (requestCode == REQUEST_ENABLE) { // 블루투스 활성화가 정상이면 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { Log.i(DEBUG_TAG, "device name-->" + device.getName()); } } } else if (requestCode == REQUEST_ENABLE && resultCode == Activity.RESULT_CANCELED) { // Toast.makeText(this, "블루투스를 연결하지 않아 앱을 종료합니다.", Toast.LENGTH_SHORT).show(); // finish(); } else if (requestCode == SEARCH_DEVICE) { // Intent로 블루투스 디바이스 객체 얻기 mBluetoothDevice = data.getParcelableExtra("device"); mBluetoothDevice.getAddress(); Log.i("Tag", "bluetooth start"); // 연결 쓰레드 시작 ConnectThread c = new ConnectThread(mBluetoothDevice); c.start(); } } /* * back 버튼이면 타이머(2초)를 이용하여 다시한번 뒤로 가기를 * 누르면 어플리케이션이 종료 되도록한다. */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { if (keyCode == KeyEvent.KEYCODE_BACK) { finishConfrim(); } } return false; } /** * 연결 쓰레드로 상태 메세지 보내기 * * @param message */ private void sendMessage(String stateMessage) { if (mConnectedThread != null) { mConnectedThread.write(stateMessage.getBytes()); }else{ Toast.makeText(MainActivity.this, "블루투스가 연결되지 않았습니다.", Toast.LENGTH_SHORT).show(); } } /** * 받은 소캣을 통해 데이터송수신할 쓰레드 시작하기 * * @param socket ConnectThread 혹은 AcceptThread로부터 받은 소캣 */ private void startConnectedThread(BluetoothSocket socket) { mConnectedThread = new ConnectedThread(socket); mConnectedThread.start(); // 소캣 쓰레드 시작 MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { // 연결후 아두이노 시간 설정 new Handler().postDelayed(new Runnable() { @Override public void run() { initArduinoTime(); // 아두이노 시간 설정 } }, 2000); } }); } /** * 클라이언트 쓰레드로 서버와 연결이 되면 * ConnectedThread에 블루투스 소캣을 보낸다. */ private class ConnectThread extends Thread { private final BluetoothSocket socket; public ConnectThread(BluetoothDevice device) { BluetoothSocket tmp = null; try { // 클라이언트 소캣을 만들기 위한 메소드 // 서버 소캣의 UUID값이 같아야 한다. tmp = device.createRfcommSocketToServiceRecord(BT_UUID); } catch (IOException e) { } socket = tmp; if (socket == null) { finish(); } } public void run() { // 장치 검색이 실행되고 있는지 확인하여 종료합니다. 장치 검색이 // 실행 중일때 연결을 맺으면 연결 속도가 느려질 것입니다. mBluetoothAdapter.cancelDiscovery(); try { socket.connect(); // 서버와 연결 } catch (IOException connectException) { connectException.printStackTrace(); try { socket.close(); } catch (IOException closeException) { } return; } // ConnectedThread로 데이터 송수신을 하기 위해서 소캣을 보낸다. // 해당 소캣으로 소캣통신 시작 이하 tcp통신과 같음.. startConnectedThread(socket); } public void cancel() { try { socket.close(); } catch (IOException e) { } } } /** * 서버 소캣 혹은 클라이언트 소캣을 통해 * 데이터 송수신을 할 쓰레드 */ private class ConnectedThread extends Thread { private final BluetoothSocket socket; // 블루투스 소캣 private final InputStream mmInStream; // 입력 스트림 private final OutputStream mmOutStream; // 출력 스트림 public ConnectedThread(BluetoothSocket socket) { this.socket = socket; InputStream tmpIn = null; //임시 스트림 OutputStream tmpOut = null; try { // 소캣에서 입력 및 출력 스트림을 얻어온다. tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { // 토스트 메세지를 띄운다. showToast("아두이노에 연결되었습니다."); // InputStream 으로부터 입력을 읽어들입니다. String msg = ""; while (true) { try { byte[] buffer = new byte[4096]; // Read from the InputStream //mmInStream.read(buffer); // InputStreamReader isr = new InputStreamReader(mmInStream); mmInStream.read(buffer); msg += new String(buffer).trim(); //Log.i(DEBUG_TAG, "수신된 메세지->" + msg); if (msg.contains("tilt;")) { final String sendData = msg.trim(); MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { sendSms(); //mWebView.loadUrl("javascript:sendData('" + sendData + "');"); } }); Log.i(DEBUG_TAG, "수신된 메세지->" + sendData); msg = ""; } } catch (IOException e) { break; } } } /** * outputstream의 write를 통해 메세지 내용을 쓴다. * * @param bytes */ public void write(byte[] bytes) { try { mmOutStream.write(bytes); } catch (IOException e) { } } /** * 소캣 닫기 */ public void cancel() { try { socket.close(); } catch (IOException e) { } } } private void sendSms(){ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String tel = prefs.getString("tel", ""); if(TextUtils.isEmpty(tel)){ Toast.makeText(mContext, "연락처가 설정되지 않았습니다", Toast.LENGTH_SHORT).show(); return; } SmsManager mSmsManager = SmsManager.getDefault(); mSmsManager.sendTextMessage(tel, null, "사용자가 넘어졌습니다.", null, null); } /** * 서버 연결 쓰레드로 rfcomm 채널을 통해 서버 소캣을 만들어 준다. */ private class AcceptThread extends Thread { private final BluetoothServerSocket mmServerSocket; public AcceptThread(Context context) { BluetoothServerSocket tmp = null; // 임시 서버 소캣 try { // UUID를 사용하여 서버 소켓을 만듭니다. tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord( "My Bluetooth", BT_UUID); } catch (IOException e) { showToast("서버 소켓을 만드는데 실패하였습니다. " + e.toString()); } mmServerSocket = tmp; } public void run() { showToast("클라이언트를 기다리는 중입니다."); BluetoothSocket socket = null; // 클라이언트가 접속을 시도할때까지 기다립니다. while (true) { try { if (mmServerSocket != null) { socket = mmServerSocket.accept(); } } catch (IOException e) { break; } // If a connection was accepted if (socket != null) { // 클라이언트와 연결되고 소켓이 생성되면 // 소켓을 통해 데이터 송수신을 시작합니다. startConnectedThread(socket); showToast("클라이언트와 연결되었습니다."); try { if (mmServerSocket != null) { mmServerSocket.close(); } } catch (IOException e) { e.printStackTrace(); showToast("서버 소켓을 종료하는 중 에러가 발생하였습니다. " + e.toString()); } break; } } } // 리스닝 소켓을 닫고 스레드를 종료합니다. public void cancel() { try { if (mmServerSocket != null) { mmServerSocket.close(); } } catch (IOException e) { } } } /** * 핸들러를 통해 토스트 메세지 보여주기 * * @param msg 메세지 */ private void showToast(String msg) { Message message = handler.obtainMessage(); message.what = SHOW_TOAST; message.arg1 = 0; message.arg2 = 0; message.obj = msg; handler.sendMessage(message); } //flipscreen not loading again @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } private void finishConfrim() { /* * 앱 종료 다이얼로그 */ AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this); ad.setTitle("").setMessage("종료 하시겠습니까?") .setPositiveButton("종료", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { // TODO Auto-generated method stub // 서비스중지 /* * Intent serviceIntent = new * Intent(getApplicationContext(), * LocationService.class); stopService(serviceIntent); * Log.i(DEBUG_TAG, "service start!!"); */ if (mConnectedThread != null) { mConnectedThread.cancel(); } finishAffinity(); // android.os.Process.killProcess(android.os.Process.myPid() // ); } }).setNegativeButton("취소", null).show(); } private class myWebClient extends WebViewClient { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, String url) { // TODO Auto-generated method stub super.onPageFinished(view, url); //progressBar.setVisibility(View.GONE); } } public static String StreamToString(InputStream in) throws IOException { if(in == null) { return ""; } Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { } return writer.toString(); } }
package com.wired.base; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; public class ZipUtil { private static String startDir; public static void mkZip(String srcPath, String zipName) { File file = new File(srcPath); if (file.exists()) { System.out.println(" Starting to zip directory " + srcPath + "..."); try { FileOutputStream fos = new FileOutputStream(new File(zipName)); CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32()); ZipOutputStream zos = new ZipOutputStream(cos); String basedir = ""; startDir = file.getParent() + File.separator; compress(file, zos, basedir); zos.close(); cos.close(); fos.close(); System.out.println(" Finish zipping directory " + srcPath + "..."); } catch (IOException e) { e.printStackTrace(); } } else { throw new RuntimeException(" The file is not existed ! "); } } public static void unzip(String srcFile, String destDirPath) throws IOException { File file = new File(srcFile); if (file.exists()) { System.out.println(" Starting to unzip file " + srcFile + "..."); ZipFile zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry entry = zipEntries.nextElement(); File targetFile = new File(destDirPath + File.separator + entry.getName()); if (entry.isDirectory()) { targetFile.mkdirs(); } else { if (!targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdirs(); } targetFile.createNewFile(); BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); FileOutputStream fos = new FileOutputStream(targetFile); Integer len; while ((len = bis.read()) != -1) { fos.write(len); } fos.close(); bis.close(); } } zipFile.close(); System.out.println(" Finish unzipping file " + srcFile + "..."); } else { throw new RuntimeException(" The file is not existed ! "); } } private static void compress(File source, ZipOutputStream out, String basedir) throws IOException { if (!source.exists()) { return; } if (source.isDirectory()) { File[] files = source.listFiles(); for (File file : files) { compress(file, out, basedir); } } else { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source)); ZipEntry entry = new ZipEntry(basedir + source.getPath().substring(startDir.length())); out.putNextEntry(entry); Integer len; while ((len = bis.read()) != -1) { out.write(len); } out.closeEntry(); bis.close(); } } }
package com.sshfortress.service.system; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sshfortress.common.beans.SysRoleMenu; import com.sshfortress.dao.system.mapper.SysRoleMenuMapper; @Service("sysRoleMenuService") public class SysRoleMenuService { @Autowired SysRoleMenuMapper sysRoleMenuMapper; @Transactional public void add(Long roleId,Long[] menuIds) { List<SysRoleMenu> list = new ArrayList<SysRoleMenu>(); for (Long menuId : menuIds) { SysRoleMenu sysRoleMenu = new SysRoleMenu(); sysRoleMenu.setCreateTime(new Date()); sysRoleMenu.setMenuId(menuId); sysRoleMenu.setRoleId(roleId); list.add(sysRoleMenu); } sysRoleMenuMapper.deleteByRoleId(roleId); sysRoleMenuMapper.insertBatch(list); } }
package com.zantong.mobilecttx.common.fragment; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.zantong.mobilecttx.common.adapter.CommonTwoLevelMenuAdapter; import com.jcodecraeer.xrecyclerview.BaseAdapter; import com.zantong.mobilecttx.base.fragment.BaseListFragment; import com.zantong.mobilecttx.common.bean.CommonTwoLevelMenuBean; import java.util.ArrayList; import java.util.List; /** * Created by zhoujie on 2017/1/3. */ public class CommonTwoLevelMenuFragment extends BaseListFragment<CommonTwoLevelMenuBean> { public static CommonTwoLevelMenuFragment newInstance(int typeId) { CommonTwoLevelMenuFragment f = new CommonTwoLevelMenuFragment(); Bundle args = new Bundle(); args.putInt("type", typeId); f.setArguments(args); return f; } private List<CommonTwoLevelMenuBean> commonTwoLevelMenuBeanList; private int type; @Override public void initData() { super.initData(); Bundle bundle = getArguments(); type = bundle.getInt("type", 0); commonTwoLevelMenuBeanList = new ArrayList<>(); showData(); } @Override protected void onRecyclerItemClick(View view, Object data) { onItemClick(data); } private void onItemClick(Object data) { CommonTwoLevelMenuBean commonTwoLevelMenuBean = (CommonTwoLevelMenuBean) data; int resultcode = 0; if (type == 0) { //婚姻状况 resultcode = 1000; } else if (type == 1) {//教育程度 resultcode = 1001; } else if (type == 2) {//住宅类型 resultcode = 1002; } else if (type == 3) {//行业类别 resultcode = 1003; } else if (type == 4) {//职业 resultcode = 1004; } else if (type == 5) {//职务 resultcode = 1005; } else if (type == 6) {//单位性质 resultcode = 1006; } else if (type == 7) {//性别 resultcode = 1007; } else if (type == 8) {//联系人 resultcode = 1008; } else if (type == 9) {//自动还款类型 resultcode = 1009; } else if (type == 10) {//电子对账单标识 resultcode = 1010; } Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putSerializable("data", commonTwoLevelMenuBean); intent.putExtras(bundle); getActivity().setResult(resultcode, intent); getActivity().finish(); } /** * 显示数据 */ private void showData() { if (type == 0) { //婚姻状况 maritalStatus(); } else if (type == 1) {//教育程度 educationLevel(); } else if (type == 2) {//住宅类型 housingType(); } else if (type == 3) {//行业类别 industryCategories(); } else if (type == 4) {//职业 occupation(); } else if (type == 5) {//职务 post(); } else if (type == 6) {//单位性质 unitProperty(); } else if (type == 7) {//性别 gender(); } else if (type == 8) {//联系人 contacts(); } else if (type == 9) {//自动还款类型 automaticRepaymentType(); } else if (type == 10) {//电子对账单标识 ElectronicBillIdentification(); } setDataResult(commonTwoLevelMenuBeanList); } /** * 电子对账单标识 */ private void ElectronicBillIdentification() { commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(0, "否")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(1, "是")); } /** * 自动还款类型 */ private void automaticRepaymentType() { commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(9, "不开通")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(0, "人民币自动转存")); } /** * 联系人 */ private void contacts() { commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(1, "父子")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(2, "母子")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(3, "兄弟姐妹")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(5, "夫妻")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(8, "朋友")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(9, "同事")); } /** * 性别 */ private void gender() { commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(1, "男")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(2, "女")); } /** * 单位性质 */ private void unitProperty() { commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(20, "集体")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(30, "国有控股")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(40, "集体控股")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(50, "三资")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(60, "私营")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(70, "个体")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(80, "外贸")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(90, "股份合作")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(110, "民营")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(120, "联营")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(130, "乡镇企业;")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(190, "其它;")); } /** * 职务 */ private void post() { commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(2, "部、省级、副部、副省级")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(3, "董事/司、局、地、厅级 ")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(4, "总经理/县处级")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(5, "科级/部门经理")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(6, "职员/科员级")); } /** * 职业 */ private void occupation() { commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(1, "公务员")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(2, "事业单位员工;")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(3, "职员")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(4, "军人")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(5, "自由职业者")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(6, "工人")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(7, "农民")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(30, "私人业主")); } /** * 行业类别 */ private void industryCategories() { commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(1, "证券")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(2, "财政")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(3, "商业、个体、租赁")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(4, "机关团体")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(5, "工业")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(6, "保险")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(7, "房地产")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(8, "合资")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(9, "其他")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(10, "邮电、计算机、通讯")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(11, "水电气供应")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(12, "科教文卫")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(13, "部队系统")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(14, "农林牧渔")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(15, "社会服务业")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(16, "银行")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(17, "采矿业")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(18, "制造业")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(19, "建筑业")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(20, "交通、仓储、物流")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(21, "其它金融业")); } /** * 婚姻状况 */ private void maritalStatus() { commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(1, "未婚")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(2, "已婚")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(6, "其它")); } /** * 教育程度 */ private void educationLevel() { commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(1, "博士及以上")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(2, "硕士研究生")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(3, "大学本科")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(4, "大学大专/电大")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(5, "中专")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(6, "技工学校")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(7, "高中")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(8, "初中")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(9, "小学及以下")); } /** * 住宅类型 */ private void housingType() { commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(1, "自有住房")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(2, "分期付款购房")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(3, "租房")); commonTwoLevelMenuBeanList.add(new CommonTwoLevelMenuBean(4, "其它")); } @Override protected void onLoadMoreData() { } @Override protected void onRefreshData() { } @Override public BaseAdapter<CommonTwoLevelMenuBean> createAdapter() { return new CommonTwoLevelMenuAdapter(); } }
package com.hunger.service; /** * Created by 小排骨 on 2018/1/22. */ public interface HelloService extends Service{ String sayHello(String user); }
package ListaSimple; public class NewMain { public static void main(String[] args) { Lista ls=new Lista(); ls.Ingresar(5); ls.Ingresar(3); ls.Ingresar(7); ls.Ingresar(2); System.out.println(ls.Mostrar()); } }
package com.cqccc.common.web.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // registry.addResourceHandler("/component/**").addResourceLocations("classpath:/component/"); } }
package com.cakeworld.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import lombok.Data; @Entity @Data public class SubscribedEmail { @Id @GeneratedValue(strategy=GenerationType.AUTO) long id; String emailId; }
package com.revature.simple; public class JavaSimpleSolution implements JavaSimple { @Override public int castToInt(double n) { n = int (n); return 0; } @Override public byte castToByte(short n) { n = byte(n) return 0; } @Override public double divide(double operandOne, double operandTwo) throws IllegalArgumentException { int x = operandOne/operandTwo; return x; } @Override public boolean isEven(int n) { // TODO Auto-generated method stub int x = n/2; if( x = 1) { return false; } else { return true; } @Override public boolean isAllEven(int[] array) { for(int i = 0;i < array.length;i++){ if(int[i]%2 == 0) { return true; } else { return false; } } } @Override public double average(int[] array) throws IllegalArgumentException { for(int j = 0;j < array.length;j++) { int sum += array[j]; } else if{ array[] == null{ throw IllegalArgumentException; } } } @Override public int max(int[] array) throws IllegalArgumentException { // TODO Auto-generated method stub return 0; } @Override public int fibonacci(int n) throws IllegalArgumentException { // TODO Auto-generated method stub return 0; } @Override public int[] sort(int[] array) throws IllegalArgumentException { // TODO Auto-generated method stub return null; } @Override public int factorial(int n) throws IllegalArgumentException { // TODO Auto-generated method stub return 0; } @Override public int[] rotateLeft(int[] array, int n) throws IllegalArgumentException { // TODO Auto-generated method stub return null; } @Override public String isPrime(int n) { // TODO Auto-generated method stub return null; } @Override public boolean balancedBrackets(String brackets) throws IllegalArgumentException { // TODO Auto-generated method stub return false; } }
package com.daikit.graphql.test; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import com.daikit.graphql.dynamicattribute.GQLDynamicAttributeGetter; import com.daikit.graphql.dynamicattribute.GQLDynamicAttributeSetter; import com.daikit.graphql.dynamicattribute.IGQLAbstractDynamicAttribute; import com.daikit.graphql.enums.GQLMethodType; import com.daikit.graphql.enums.GQLScalarTypeEnum; import com.daikit.graphql.meta.GQLMetaModel; import com.daikit.graphql.meta.GQLMethod; import com.daikit.graphql.meta.GQLParam; import com.daikit.graphql.meta.attribute.GQLAttributeEntityMetaData; import com.daikit.graphql.meta.attribute.GQLAttributeEnumMetaData; import com.daikit.graphql.meta.attribute.GQLAttributeListEntityMetaData; import com.daikit.graphql.meta.attribute.GQLAttributeListEnumMetaData; import com.daikit.graphql.meta.attribute.GQLAttributeListScalarMetaData; import com.daikit.graphql.meta.attribute.GQLAttributeRightsMetaData; import com.daikit.graphql.meta.attribute.GQLAttributeScalarMetaData; import com.daikit.graphql.meta.entity.GQLEntityMetaData; import com.daikit.graphql.meta.entity.GQLEntityRightsMetaData; import com.daikit.graphql.meta.entity.GQLEnumMetaData; import com.daikit.graphql.test.data.AbstractEntity; import com.daikit.graphql.test.data.EmbeddedData1; import com.daikit.graphql.test.data.EmbeddedData2; import com.daikit.graphql.test.data.EmbeddedData3; import com.daikit.graphql.test.data.Entity1; import com.daikit.graphql.test.data.Entity2; import com.daikit.graphql.test.data.Entity3; import com.daikit.graphql.test.data.Entity4; import com.daikit.graphql.test.data.Entity5; import com.daikit.graphql.test.data.Entity6; import com.daikit.graphql.test.data.Entity7; import com.daikit.graphql.test.data.Entity8; import com.daikit.graphql.test.data.Entity9; import com.daikit.graphql.test.data.Enum1; import com.daikit.graphql.test.data.Roles; /** * Meta data for building test schema * * @author Thibaut Caselli */ public class GQLMetaModelBuilder { /** * Build the test GraphQL data model * * @param automatic * whether to build the test GraphQL meta model automatically * from classes * @return the built {@link GQLMetaModelBuilder} */ public GQLMetaModel build(boolean automatic) { final GQLMetaModel metaModel; if (automatic) { final Collection<Class<?>> entityClasses = Arrays.asList(Entity1.class, Entity2.class, Entity3.class, Entity4.class, Entity5.class, Entity6.class, Entity7.class, Entity8.class, Entity9.class); final Collection<Class<?>> availableEmbeddedEntityClasses = Arrays.asList(EmbeddedData1.class, EmbeddedData2.class, EmbeddedData3.class); metaModel = GQLMetaModel.createFromEntityClasses(entityClasses, availableEmbeddedEntityClasses, buildDynamicAttributes(), Arrays.asList(new GQLTestController())); } else { final Collection<GQLEntityMetaData> entityMetaDatas = Arrays.asList(buildEntity1(), buildEntity2(), buildEntity3(), buildEntity4(), buildEntity5(), buildEntity6(), buildEntity7(), buildEntity8(), buildEntity9(), buildEmbeddedData1(), buildEmbeddedData2(), buildEmbeddedData3()); final Collection<GQLEnumMetaData> enumMetaDatas = Arrays.asList(buildEnumMetaData()); metaModel = GQLMetaModel.createFromMetaDatas(enumMetaDatas, entityMetaDatas, buildDynamicAttributes(), Arrays.asList(new GQLTestController())); } return metaModel; } // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // PRIVATE UTILS // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- private GQLEntityMetaData buildEntity1() { final GQLEntityMetaData entity = new GQLEntityMetaData(Entity1.class.getSimpleName(), Entity1.class, AbstractEntity.class); // Fields from class entity.addAttribute(new GQLAttributeScalarMetaData("intAttr", GQLScalarTypeEnum.INT)); entity.addAttribute(new GQLAttributeScalarMetaData("longAttr", GQLScalarTypeEnum.LONG)); entity.addAttribute(new GQLAttributeScalarMetaData("doubleAttr", GQLScalarTypeEnum.FLOAT)); entity.addAttribute(new GQLAttributeScalarMetaData("stringAttr", GQLScalarTypeEnum.STRING)); entity.addAttribute(new GQLAttributeScalarMetaData("booleanAttr", GQLScalarTypeEnum.BOOLEAN)); entity.addAttribute(new GQLAttributeScalarMetaData("bigIntAttr", GQLScalarTypeEnum.BIG_INTEGER)); entity.addAttribute(new GQLAttributeScalarMetaData("bigDecimalAttr", GQLScalarTypeEnum.BIG_DECIMAL)); entity.addAttribute(new GQLAttributeScalarMetaData("bytesAttr", GQLScalarTypeEnum.BYTE)); entity.addAttribute(new GQLAttributeScalarMetaData("shortAttr", GQLScalarTypeEnum.SHORT)); entity.addAttribute(new GQLAttributeScalarMetaData("charAttr", GQLScalarTypeEnum.CHAR)); entity.addAttribute(new GQLAttributeScalarMetaData("dateAttr", GQLScalarTypeEnum.DATE)); entity.addAttribute(new GQLAttributeScalarMetaData("fileAttr", GQLScalarTypeEnum.FILE)); entity.addAttribute(new GQLAttributeScalarMetaData("localDateAttr", GQLScalarTypeEnum.LOCAL_DATE)); entity.addAttribute(new GQLAttributeScalarMetaData("localDateTimeAttr", GQLScalarTypeEnum.LOCAL_DATE_TIME)); entity.addAttribute(new GQLAttributeScalarMetaData("instantAttr", GQLScalarTypeEnum.INSTANT)); entity.addAttribute(new GQLAttributeListScalarMetaData("stringList", GQLScalarTypeEnum.STRING)); entity.addAttribute(new GQLAttributeListScalarMetaData("stringSet", GQLScalarTypeEnum.STRING)); entity.addAttribute(new GQLAttributeEnumMetaData("enumAttr", Enum1.class)); entity.addAttribute(new GQLAttributeListEnumMetaData("enumList", Enum1.class)); entity.addAttribute(new GQLAttributeListEnumMetaData("enumSet", Enum1.class)); entity.addAttribute(new GQLAttributeEntityMetaData("entity2", Entity2.class)); entity.addAttribute(new GQLAttributeListEntityMetaData("entity3s", Entity3.class)); entity.addAttribute(new GQLAttributeListEntityMetaData("entity4s", Entity4.class)); entity.addAttribute(new GQLAttributeEntityMetaData("embeddedData1", EmbeddedData1.class).setEmbedded(true)); entity.addAttribute( new GQLAttributeListEntityMetaData("embeddedData1s", EmbeddedData1.class).setEmbedded(true)); // Fields from super class entity.addAttribute(new GQLAttributeScalarMetaData("id", GQLScalarTypeEnum.ID) .addRights(new GQLAttributeRightsMetaData().setNullableForUpdate(false).setMandatoryForUpdate(true))); return entity; } private GQLEntityMetaData buildEntity2() { final GQLEntityMetaData entity = new GQLEntityMetaData(Entity2.class.getSimpleName(), Entity2.class, AbstractEntity.class); // Fields from class entity.addAttribute(new GQLAttributeListEntityMetaData("entity1s", Entity1.class)); // Fields from super class entity.addAttribute(new GQLAttributeScalarMetaData("id", GQLScalarTypeEnum.ID) .addRights(new GQLAttributeRightsMetaData().setNullableForUpdate(false).setMandatoryForUpdate(true))); return entity; } private GQLEntityMetaData buildEntity3() { final GQLEntityMetaData entity = new GQLEntityMetaData(Entity3.class.getSimpleName(), Entity3.class, AbstractEntity.class); // Fields from class entity.addAttribute(new GQLAttributeEntityMetaData("entity1", Entity1.class)); // Fields from super class entity.addAttribute(new GQLAttributeScalarMetaData("id", GQLScalarTypeEnum.ID) .addRights(new GQLAttributeRightsMetaData().setNullableForUpdate(false).setMandatoryForUpdate(true))); return entity; } private GQLEntityMetaData buildEntity4() { final GQLEntityMetaData entity = new GQLEntityMetaData(Entity4.class.getSimpleName(), Entity4.class, AbstractEntity.class); // Fields from class entity.addAttribute(new GQLAttributeListEntityMetaData("entity1s", Entity1.class)); // Fields from super class entity.addAttribute(new GQLAttributeScalarMetaData("id", GQLScalarTypeEnum.ID) .addRights(new GQLAttributeRightsMetaData().setNullableForUpdate(false).setMandatoryForUpdate(true))); return entity; } private GQLEntityMetaData buildEntity5() { final GQLEntityMetaData entity = new GQLEntityMetaData(Entity5.class.getSimpleName(), Entity5.class, AbstractEntity.class); // Fields from class entity.addAttribute(new GQLAttributeScalarMetaData("intAttr", GQLScalarTypeEnum.INT)); entity.addAttribute(new GQLAttributeScalarMetaData("stringAttr", GQLScalarTypeEnum.STRING)); // Fields from super class entity.addAttribute(new GQLAttributeScalarMetaData("id", GQLScalarTypeEnum.ID) .addRights(new GQLAttributeRightsMetaData().setNullableForUpdate(false).setMandatoryForUpdate(true))); return entity; } private GQLEntityMetaData buildEntity6() { final GQLEntityMetaData entity = new GQLEntityMetaData(Entity6.class.getSimpleName(), Entity6.class, AbstractEntity.class); // Fields from class entity.addAttribute(new GQLAttributeScalarMetaData("attr1", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setReadable(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr2", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setSaveable(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr3", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setNullable(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr4", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setNullableForUpdate(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr5", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setNullableForCreate(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr6", GQLScalarTypeEnum.STRING).setFilterable(false)); entity.addAttribute(new GQLAttributeScalarMetaData("attr7", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setMandatory(true))); entity.addAttribute(new GQLAttributeScalarMetaData("attr8", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setMandatoryForUpdate(true))); entity.addAttribute(new GQLAttributeScalarMetaData("attr9", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setMandatoryForCreate(true))); entity.addAttribute(new GQLAttributeScalarMetaData("attr10", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setReadable(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr11", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setSaveable(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr12", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setNullable(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr13", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setNullableForUpdate(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr14", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setNullableForCreate(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr15", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setMandatory(true))); entity.addAttribute(new GQLAttributeScalarMetaData("attr16", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setMandatoryForUpdate(true))); entity.addAttribute(new GQLAttributeScalarMetaData("attr17", GQLScalarTypeEnum.STRING) .addRights(new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setMandatoryForCreate(true))); entity.addAttribute(new GQLAttributeScalarMetaData("attr18", GQLScalarTypeEnum.STRING).addRights( new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setReadable(false), new GQLAttributeRightsMetaData().setRole(Roles.ROLE2).setReadable(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr19", GQLScalarTypeEnum.STRING).addRights( new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setReadable(false), new GQLAttributeRightsMetaData().setRole(Roles.ROLE2).setReadable(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr20", GQLScalarTypeEnum.STRING).addRights( new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setReadable(false), new GQLAttributeRightsMetaData().setRole(Roles.ROLE2).setSaveable(false))); entity.addAttribute(new GQLAttributeScalarMetaData("attr21", GQLScalarTypeEnum.STRING).addRights( new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setReadable(false).setNullable(false), new GQLAttributeRightsMetaData().setRole(Roles.ROLE2).setReadable(false).setNullable(false), new GQLAttributeRightsMetaData().setRole(Roles.ROLE3).setSaveable(false).setMandatory(true), new GQLAttributeRightsMetaData().setRole(Roles.ROLE4).setSaveable(false).setMandatory(true))); entity.addAttribute(new GQLAttributeScalarMetaData("attr22", GQLScalarTypeEnum.STRING).addRights( new GQLAttributeRightsMetaData().setReadable(false), new GQLAttributeRightsMetaData().setRole(Roles.ROLE1).setReadable(true))); // Fields from super class entity.addAttribute(new GQLAttributeScalarMetaData("id", GQLScalarTypeEnum.ID) .addRights(new GQLAttributeRightsMetaData().setNullableForUpdate(false).setMandatoryForUpdate(true))); return entity; } private GQLEntityMetaData buildEntity7() { final GQLEntityMetaData entity = new GQLEntityMetaData(Entity7.class.getSimpleName(), Entity7.class, AbstractEntity.class).addRights(new GQLEntityRightsMetaData().setSaveable(false)); // Fields from class // Fields from super class entity.addAttribute(new GQLAttributeScalarMetaData("id", GQLScalarTypeEnum.ID) .addRights(new GQLAttributeRightsMetaData().setNullableForUpdate(false).setMandatoryForUpdate(true))); return entity; } private GQLEntityMetaData buildEntity8() { final GQLEntityMetaData entity = new GQLEntityMetaData(Entity8.class.getSimpleName(), Entity8.class, AbstractEntity.class).addRights(new GQLEntityRightsMetaData().setDeletable(false)); // Fields from class // Fields from super class entity.addAttribute(new GQLAttributeScalarMetaData("id", GQLScalarTypeEnum.ID) .addRights(new GQLAttributeRightsMetaData().setNullableForUpdate(false).setMandatoryForUpdate(true))); return entity; } private GQLEntityMetaData buildEntity9() { final GQLEntityMetaData entity = new GQLEntityMetaData(Entity9.class.getSimpleName(), Entity9.class, AbstractEntity.class).addRights(new GQLEntityRightsMetaData().setReadable(false)); // Fields from class // Fields from super class entity.addAttribute(new GQLAttributeScalarMetaData("id", GQLScalarTypeEnum.ID) .addRights(new GQLAttributeRightsMetaData().setNullableForUpdate(false).setMandatoryForUpdate(true))); return entity; } private GQLEntityMetaData buildEmbeddedData1() { final GQLEntityMetaData entity = new GQLEntityMetaData(EmbeddedData1.class.getSimpleName(), EmbeddedData1.class) .setEmbedded(true); entity.addAttribute(new GQLAttributeScalarMetaData("intAttr", GQLScalarTypeEnum.INT)); entity.addAttribute(new GQLAttributeScalarMetaData("longAttr", GQLScalarTypeEnum.LONG)); entity.addAttribute(new GQLAttributeScalarMetaData("doubleAttr", GQLScalarTypeEnum.FLOAT)); entity.addAttribute(new GQLAttributeScalarMetaData("stringAttr", GQLScalarTypeEnum.STRING)); entity.addAttribute(new GQLAttributeScalarMetaData("booleanAttr", GQLScalarTypeEnum.BOOLEAN)); entity.addAttribute(new GQLAttributeScalarMetaData("bigIntAttr", GQLScalarTypeEnum.BIG_INTEGER)); entity.addAttribute(new GQLAttributeScalarMetaData("bigDecimalAttr", GQLScalarTypeEnum.BIG_DECIMAL)); entity.addAttribute(new GQLAttributeScalarMetaData("bytesAttr", GQLScalarTypeEnum.BYTE)); entity.addAttribute(new GQLAttributeScalarMetaData("shortAttr", GQLScalarTypeEnum.SHORT)); entity.addAttribute(new GQLAttributeScalarMetaData("charAttr", GQLScalarTypeEnum.CHAR)); entity.addAttribute(new GQLAttributeScalarMetaData("dateAttr", GQLScalarTypeEnum.DATE)); entity.addAttribute(new GQLAttributeScalarMetaData("fileAttr", GQLScalarTypeEnum.FILE)); entity.addAttribute(new GQLAttributeScalarMetaData("localDateAttr", GQLScalarTypeEnum.LOCAL_DATE)); entity.addAttribute(new GQLAttributeScalarMetaData("localDateTimeAttr", GQLScalarTypeEnum.LOCAL_DATE_TIME)); entity.addAttribute(new GQLAttributeScalarMetaData("instantAttr", GQLScalarTypeEnum.INSTANT)); entity.addAttribute(new GQLAttributeListScalarMetaData("stringList", GQLScalarTypeEnum.STRING)); entity.addAttribute(new GQLAttributeListScalarMetaData("stringSet", GQLScalarTypeEnum.STRING)); entity.addAttribute(new GQLAttributeEnumMetaData("enumAttr", Enum1.class)); entity.addAttribute(new GQLAttributeListEnumMetaData("enumList", Enum1.class)); entity.addAttribute(new GQLAttributeListEnumMetaData("enumSet", Enum1.class)); entity.addAttribute(new GQLAttributeEntityMetaData("data2", EmbeddedData2.class).setEmbedded(true)); entity.addAttribute(new GQLAttributeListEntityMetaData("data3s", EmbeddedData3.class).setEmbedded(true)); return entity; } private GQLEntityMetaData buildEmbeddedData2() { final GQLEntityMetaData entity = new GQLEntityMetaData(EmbeddedData2.class.getSimpleName(), EmbeddedData2.class) .setEmbedded(true); entity.addAttribute(new GQLAttributeScalarMetaData("intAttr", GQLScalarTypeEnum.INT)); return entity; } private GQLEntityMetaData buildEmbeddedData3() { final GQLEntityMetaData entity = new GQLEntityMetaData(EmbeddedData3.class.getSimpleName(), EmbeddedData3.class) .setEmbedded(true); entity.addAttribute(new GQLAttributeScalarMetaData("intAttr", GQLScalarTypeEnum.INT)); return entity; } private GQLEnumMetaData buildEnumMetaData() { return new GQLEnumMetaData(Enum1.class.getSimpleName(), Enum1.class); } private List<IGQLAbstractDynamicAttribute<?>> buildDynamicAttributes() { return Stream.of(new GQLDynamicAttributeGetter<Entity1, String>("dynamicAttribute1") { @Override public String getValue(final Entity1 source) { return "dynamicValue" + source.getId(); } }, new GQLDynamicAttributeSetter<Entity1, String>("dynamicAttribute2") { @Override public void setValue(final Entity1 source, final String valueToSet) { source.setStringAttr(valueToSet); } }, new GQLDynamicAttributeGetter<EmbeddedData1, String>("dynamicAttribute1") { @Override public String getValue(final EmbeddedData1 source) { return "dynamicValue" + source.getStringAttr(); } }, new GQLDynamicAttributeGetter<EmbeddedData1, Entity2>("dynamicAttribute2") { @Override public Entity2 getValue(final EmbeddedData1 source) { final Entity2 entity = new Entity2(); entity.setId("1000"); return entity; } }).collect(Collectors.toList()); } /** * Test controller for custom methods * * @author Thibaut Caselli */ public class GQLTestController { /** * Custom method query * * @param arg1 * first argument with type String * @return and {@link Entity1} */ @GQLMethod(type = GQLMethodType.QUERY) public Entity1 customMethodQuery1(@GQLParam("arg1") String arg1) { final Entity1 result = new Entity1(); result.setStringAttr(arg1); final EmbeddedData1 embeddedData1 = new EmbeddedData1(); embeddedData1.setStringAttr(arg1); result.setEmbeddedData1(embeddedData1); return result; } /** * Custom method query 2 * * @param arg1 * first argument with type String * @param arg2 * second argument with type EmbeddedData1 * @return an {@link Entity1} */ @GQLMethod(type = GQLMethodType.QUERY) public Entity1 customMethodQuery2(@GQLParam("arg1") String arg1, @GQLParam("arg2") EmbeddedData1 arg2) { final Entity1 result = new Entity1(); result.setIntAttr(5); result.setStringAttr(arg1); result.setEmbeddedData1(arg2); return result; } /** * Custom method query 3 * * @param arg1 * first argument with type String * @param arg2 * second argument with type List of String * @param arg3 * third argument with type List of Enum1 * @param arg4 * fourth argument with type List of EmbeddedData1 * @param arg5 * fifth argument with type String * @return an {@link Entity1} */ @GQLMethod(type = GQLMethodType.QUERY) public Entity1 customMethodQuery3(@GQLParam("arg1") Enum1 arg1, @GQLParam("arg2") List<String> arg2, @GQLParam("arg3") List<Enum1> arg3, @GQLParam("arg4") List<EmbeddedData1> arg4, @GQLParam("arg5") String arg5) { final Entity1 result = new Entity1(); result.setEnumAttr(arg1); result.setStringList(arg2); result.setEnumList(arg3); result.setEmbeddedData1s(arg4); if (arg5 == null) { result.setStringAttr("NULLVALUE"); } return result; } /** * Custom method mutation 1 * * @param arg1 * first argument of type String * @return an {@link Entity1} */ @GQLMethod(type = GQLMethodType.MUTATION) public Entity1 customMethodMutation1(@GQLParam("arg1") String arg1) { final Entity1 result = new Entity1(); result.setStringAttr(arg1); return result; } } }
package edu.athens.cs.gradegeneratortest; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import java.util.List; /** * Created by alewis on 3/2/17. */ public class StudentEditActivity extends FragmentActivity { // Add adapter for view paging public static class StudentViewPagerAdapter extends FragmentPagerAdapter { private Cohort mCohort = Cohort.getCohort(); public StudentViewPagerAdapter(android.support.v4.app.FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { List<String> studentList = mCohort.buildAList(); String studentName = studentList.get(position); return StudentMasterFragment.newInstance(studentName); } @Override public int getCount() { return mCohort.buildAList().size(); } } private String studentName; private ViewPager vpPager; private FragmentPagerAdapter adapterViewPager; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Setup the view pager for editing vpPager = (ViewPager) findViewById(R.id.studentvp); adapterViewPager = new StudentViewPagerAdapter(getSupportFragmentManager()); vpPager.setAdapter(adapterViewPager); } public void setDisplay(String name) { List<String> studentNames = Cohort.getCohort().buildAList(); int position = studentNames.indexOf(name); vpPager.setCurrentItem(position); } }
package hwl3; public class CheckPrimeNumber { public static void execute(int number) { String result = ""; if ((number % 2 > 0) && (number % 3 > 0) && (number % 5 > 0) && (number % 7 > 0)) { result =" " ; } else result = "не "; System.out.println(number + " это " + result+" простое число"); } }
package com.codigo.smartstore.xbase; import java.nio.ByteBuffer; import java.nio.charset.Charset; // https://www.clicketyclick.dk/databases/xbase/format/dbf.html#DBF_STRUCT /// struktura pliku XBAse // http://wiki.dbfmanager.com/dbf-structure // http://www.oocities.org/geoff_wass/dBASE/GaryWhite/dBASE/FAQ/qformt.htm // http://web.tiscali.it/SilvioPitti/ // PHP CLASS BUILDER // https://packagist.org/packages/org.majkel/dbase // http://fileformats.archiveteam.org/wiki/DBF#Specifications /** * What to check when opening a .DBF File * * Records: * * Length of record must be > 1 and < max length. (max length = 4000 B in dBASE * III and IV, can be 32KB in other systems). The number of records must be >= * 0. Fields: The .DBF file must have at least one field. The number of fields * must be <= the maximum allowable number of fields. File size: * * File size reported by the operating system must match the logical file size. * Logical file size = ( Length of header + ( Number of records * Length of each * record ) ) */ public class XbFieldFormat { // ----------------------------------------------------------------------------------------------------------------- private static final Charset COLUMN_CHARSET; // ----------------------------------------------------------------------------------------------------------------- private String fieldName; // 0-10 // ----------------------------------------------------------------------------------------------------------------- private byte fieldType; // 11 // ----------------------------------------------------------------------------------------------------------------- private byte[] fieldDisplacement; // 12-15 in bytes // ----------------------------------------------------------------------------------------------------------------- private byte fieldSize; // 16 in bytes // ----------------------------------------------------------------------------------------------------------------- private byte fieldDecimalPlaces; // 17 // ----------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------- // TOD: wymyslec sposób określania ile bajtów nalezy pobrać // ----------------------------------------------------------------------------------------------------------------- static { COLUMN_CHARSET = Charset.forName("ASCII"); } // ----------------------------------------------------------------------------------------------------------------- public XbFieldFormat(final ByteBuffer fieldData) { super(); this.initalize(fieldData); } // ----------------------------------------------------------------------------------------------------------------- private void initalize(final ByteBuffer fieldData) { this.readFieldName(fieldData); this.readFieldType(fieldData); this.readFieldDisplacment(fieldData); this.readFieldSize(fieldData); this.readFieldDecimalPlaces(fieldData); } // ----------------------------------------------------------------------------------------------------------------- private void readFieldName(final ByteBuffer fieldData) { final byte[] fieldName = new byte[11]; fieldData.get(fieldName); this.fieldName = new String(fieldName, XbFieldFormat.COLUMN_CHARSET); } // ----------------------------------------------------------------------------------------------------------------- public String getFieldName() { return this.fieldName.trim(); } // ----------------------------------------------------------------------------------------------------------------- private void readFieldType(final ByteBuffer fieldData) { this.fieldType = fieldData.get(); } // ----------------------------------------------------------------------------------------------------------------- public String getFieldType() { return String.valueOf((char) this.fieldType); } // ----------------------------------------------------------------------------------------------------------------- public int getFieldDisplacment() { final ByteBuffer buffer = ByteBuffer.wrap(this.fieldDisplacement); return buffer.getInt(); } // ----------------------------------------------------------------------------------------------------------------- private void readFieldDisplacment(final ByteBuffer fieldData) { this.fieldDisplacement = new byte[4]; fieldData.get(this.fieldDisplacement); } // ----------------------------------------------------------------------------------------------------------------- public byte getFieldSize() { return (byte) Math.abs(this.fieldSize); } // ----------------------------------------------------------------------------------------------------------------- private void readFieldSize(final ByteBuffer fieldData) { this.fieldSize = fieldData.get(); } // ----------------------------------------------------------------------------------------------------------------- private void readFieldDecimalPlaces(final ByteBuffer fieldData) { this.fieldDecimalPlaces = fieldData.get(); } // ----------------------------------------------------------------------------------------------------------------- /** * @return */ public byte getFieldDecimalPlaces() { return this.fieldDecimalPlaces; } // ----------------------------------------------------------------------------------------------------------------- public XbFieldType getFielSpec() { return null; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "XbFieldInfo [Name=" + this.getFieldName() + "]" + "[Type=" + this.getFieldType() + "]" + "[Size=" + this.getFieldSize() + "]" + "[Displacment=" + this.getFieldDisplacment() + "]" + "[DecimalCount=" + this.getFieldDecimalPlaces() + "]"; } // ----------------------------------------------------------------------------------------------------------------- }
package exceptions; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; public class NoEmptyClientAllowedException extends Exception { private static final long serialVersionUID = -566099652872901161L; public NoEmptyClientAllowedException() { Shell shell = new Shell(); MessageBox error = new MessageBox(shell); error.setText("Error"); error.setMessage("No empty clients allowed. Please enter the client information"); error.open(); } public NoEmptyClientAllowedException(String message) { super(message); } }
/** * This class is generated by jOOQ */ package schema.tables; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Identity; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import schema.BitnamiEdx; import schema.Keys; import schema.tables.records.EmbargoCountryRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.4" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class EmbargoCountry extends TableImpl<EmbargoCountryRecord> { private static final long serialVersionUID = 22039739; /** * The reference instance of <code>bitnami_edx.embargo_country</code> */ public static final EmbargoCountry EMBARGO_COUNTRY = new EmbargoCountry(); /** * The class holding records for this type */ @Override public Class<EmbargoCountryRecord> getRecordType() { return EmbargoCountryRecord.class; } /** * The column <code>bitnami_edx.embargo_country.id</code>. */ public final TableField<EmbargoCountryRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>bitnami_edx.embargo_country.country</code>. */ public final TableField<EmbargoCountryRecord, String> COUNTRY = createField("country", org.jooq.impl.SQLDataType.VARCHAR.length(2).nullable(false), this, ""); /** * Create a <code>bitnami_edx.embargo_country</code> table reference */ public EmbargoCountry() { this("embargo_country", null); } /** * Create an aliased <code>bitnami_edx.embargo_country</code> table reference */ public EmbargoCountry(String alias) { this(alias, EMBARGO_COUNTRY); } private EmbargoCountry(String alias, Table<EmbargoCountryRecord> aliased) { this(alias, aliased, null); } private EmbargoCountry(String alias, Table<EmbargoCountryRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return BitnamiEdx.BITNAMI_EDX; } /** * {@inheritDoc} */ @Override public Identity<EmbargoCountryRecord, Integer> getIdentity() { return Keys.IDENTITY_EMBARGO_COUNTRY; } /** * {@inheritDoc} */ @Override public UniqueKey<EmbargoCountryRecord> getPrimaryKey() { return Keys.KEY_EMBARGO_COUNTRY_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<EmbargoCountryRecord>> getKeys() { return Arrays.<UniqueKey<EmbargoCountryRecord>>asList(Keys.KEY_EMBARGO_COUNTRY_PRIMARY, Keys.KEY_EMBARGO_COUNTRY_COUNTRY); } /** * {@inheritDoc} */ @Override public EmbargoCountry as(String alias) { return new EmbargoCountry(alias, this); } /** * Rename this table */ public EmbargoCountry rename(String name) { return new EmbargoCountry(name, null); } }
/* * 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 Controlador; import Modelo.Empleado; import Modelo.Movimiento; import Modelo.ReporteReservacion; import Modelo.Reservacion; import Modelo.dbconecction.CRUD; import Vista.DialogAbrirCaja; import Vista.FrmRealizarPago2; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.ResultSet; import java.util.Date; import javax.swing.JOptionPane; /** * * @author Percy */ public class ControladorRealizarPago { private FrmRealizarPago2 vistaRP; private ControladorPagos contrPagos; private Reservacion Reserva; private Empleado Recepcionista; CRUD consulta= CRUD.getInstance(); public ControladorRealizarPago(FrmRealizarPago2 vistaRP, ControladorPagos contrPagos,Reservacion Reserva,Empleado Recepcionista) { this.vistaRP = vistaRP; this.contrPagos = contrPagos; this.Reserva=Reserva; this.Recepcionista=Recepcionista; InicializarEventos(); } private void InicializarEventos() { vistaRP.btnRealizarPago.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if(!Recepcionista.isCashierOpen()){ DialogAbrirCaja vistaACaja=new DialogAbrirCaja(vistaRP, true); ControladorAbrirCaja contrAc=new ControladorAbrirCaja(vistaACaja, Recepcionista); } int idMovimiento=0; try{ ResultSet rs= consulta.select("select MAX(idMovimiento) from Movimiento"); rs.next(); idMovimiento= rs.getInt(1) + 1; }catch(Exception ex){ idMovimiento=1; } int TipoPago=vistaRP.cbTipoPago.getSelectedIndex()+1; if(TipoPago == 2){ TipoPago*=10; TipoPago+=vistaRP.cbTipoTarjeta.getSelectedIndex()+1; } try{ Movimiento nuevoMovimiento = new Movimiento(idMovimiento,Float.parseFloat(vistaRP.txtpago.getText()),new Date(),vistaRP.txtdescripcion.getText(), TipoPago, Reserva.getIdBalance(), Recepcionista.getHistorialCajaEnUso().getIdHistorialCaja()); nuevoMovimiento.CreateMovimiento(); if(nuevoMovimiento.getTipoPago()==1){ Recepcionista.DoMovement(Float.parseFloat(vistaRP.txtpago.getText())); } int idReporteReservaciones=1; try{ ResultSet rs=consulta.select("select MAX(idReporteReservaciones) from ReporteReservaciones"); rs.next(); idReporteReservaciones=rs.getInt(1)+1; }catch(Exception ex){ idReporteReservaciones=1; } ReporteReservacion nuevoReporte= new ReporteReservacion(idReporteReservaciones, Reserva.getNroConfirmacion(),"Realizo un pago en " +vistaRP.cbTipoPago.getItemAt(vistaRP.cbTipoPago.getSelectedIndex()) +" de "+Float.parseFloat(vistaRP.txtpago.getText()) , Reserva.getIdCliente(),Recepcionista.getIdRecepcionista(), new Date()); nuevoReporte.createReporteReservacion(); contrPagos.InicializarDatos(); vistaRP.dispose(); }catch(Exception ex){ JOptionPane.showMessageDialog(null, "Datos Erroneos, intente denuevo." ); } } }); } }
public class Markov { private int[] salidas; private int[] estados; private double[] probI; private double[][] A; private double[][] B; private int[] observaciones; private double[][] alfa; private double[][] beta; public Markov() { } public int[] getSalidas() { return salidas; } public int[] getEstados() { return estados; } public double[] getProbI() { return probI; } public double[][] getpTrans() { return A; } public double[][] getPsalidas() { return B; } public void setSalidas(int[] salidas) { this.salidas = salidas; } public void setEstados(int[] estados) { this.estados = estados; } public void setProbI(double[] probI) { this.probI = probI; } public void setpTrans(double[][] pTrans) { this.A = pTrans; } public void setPsalidas(double[][] psalidas) { this.B = psalidas; } public double[][] getA() { return A; } public double[][] getB() { return B; } public int[] getObservaciones() { return observaciones; } public double[][] getAlfa() { return alfa; } public double[][] getBeta() { return beta; } public void setA(double[][] a) { A = a; } public void setB(double[][] b) { B = b; } public void setObservaciones(int[] observaciones) { this.observaciones = observaciones; } public void setAlfa(double[][] alfa) { this.alfa = alfa; } public void setBeta(double[][] beta) { this.beta = beta; } public void inicializar(double[][] a, double[][] b, double[] pi, int[] est, int[]salid, int[] o) { setA(a); setB(b); setProbI(pi); setEstados(est); setSalidas(salid); setObservaciones(o); this.alfa=new double[est.length][est.length]; this.beta=new double[est.length][o.length]; } public void forward() { double alpha=0; for(int i=0;i<estados.length;i++) { System.out.println(i+"alv"); alpha=probI[i]*B[observaciones[0]-1][i]; alfa[0][i]=alpha; System.out.println(alpha+"tu jefa"); } alpha=0; //int t=0; int tj=0; for(int i=0;i<estados.length;i++) { for(int j=0;j<estados.length;j++) { for(int k=0;k<estados.length;k++) { alpha += (alpha * estados[i] * A[j][i]); //alfa[t+1][j]=alpha[t+1]; //t++; tj = j; } alfa[j][i]=alpha; } } } public void backward() { } public void imprimir(double[][] m) { for(int i=0;i<m.length;i++) { for(int j=0;j<m[0].length;j++) { System.out.println(m[i][j]); } } } }
package com.qst.chapter03; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class ImageViewDemoActivity extends AppCompatActivity { ImageView flagImageView; TextView flagTxt; ImageButton backImageBtn; ImageButton forwardImageBtn; //国旗数组 中国 德国 英国 int[] flag = {R.drawable.china, R.drawable.germany, R.drawable.britain}; String[] flagNames = {"中国", "德国", "英国"}; //当前页 默认第一页 int currentPage = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.imageview_demo); flagImageView = findViewById(R.id.flagImageView); flagTxt = findViewById(R.id.flagTxt); backImageBtn = findViewById(R.id.backImageBtn); forwardImageBtn = findViewById(R.id.forwardImageBtn); backImageBtn.setOnClickListener(onClickListener); forwardImageBtn.setOnClickListener(onClickListener); } private OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.backImageBtn: if (currentPage == 0) { Toast.makeText(ImageViewDemoActivity.this, "第一页,前面没有了", Toast.LENGTH_SHORT).show(); return; } else { currentPage--; flagImageView.setImageResource(flag[currentPage]); flagTxt.setText(flagNames[currentPage]); } case R.id.forwardImageBtn: if (currentPage == (flag.length - 1)) { Toast.makeText(ImageViewDemoActivity.this, "最后一页,后面没有了", Toast.LENGTH_SHORT).show(); return; } else { currentPage++; flagImageView.setImageResource(flag[currentPage]); flagTxt.setText(flagNames[currentPage]); } } } }; }
package com.hhdb.csadmin.plugin.tree.ui; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; import java.util.Collection; import javax.swing.JOptionPane; import com.hh.frame.common.log.LM; import com.hh.frame.csv.writer.CsvWriter; import com.hh.frame.dbobj.hhdb.HHdbCk; import com.hh.frame.dbobj.hhdb.HHdbDatabase; import com.hh.frame.dbobj.hhdb.HHdbFk; import com.hh.frame.dbobj.hhdb.HHdbFun; import com.hh.frame.dbobj.hhdb.HHdbIndex; import com.hh.frame.dbobj.hhdb.HHdbPk; import com.hh.frame.dbobj.hhdb.HHdbSchema; import com.hh.frame.dbobj.hhdb.HHdbSeq; import com.hh.frame.dbobj.hhdb.HHdbTabSp; import com.hh.frame.dbobj.hhdb.HHdbTable; import com.hh.frame.dbobj.hhdb.HHdbUk; import com.hh.frame.dbobj.hhdb.HHdbUser; import com.hh.frame.dbobj.hhdb.HHdbView; import com.hh.frame.dbobj.hhdb.HHdbXk; import com.hhdb.csadmin.common.bean.ServerBean; import com.hhdb.csadmin.common.dao.ConnService; import com.hh.frame.swingui.event.CmdEvent; import com.hh.frame.swingui.event.HHEvent; import com.hhdb.csadmin.common.util.ExtendXmlLoader; import com.hhdb.csadmin.plugin.tree.HTree; import com.hhdb.csadmin.plugin.tree.util.TreeNodeUtil; /** * 鼠标单击处理 * * @author hyz * */ public class TreeClick { private HTree htree; public TreeClick(HTree htree){ this.htree = htree; } public void execute(BaseTreeNode treeNode) { String type = treeNode.getType(); if(type.equals(TreeNodeUtil.SERVER_TYPE)) { CmdEvent getsbEvent = new CmdEvent(htree.PLUGIN_ID, "com.hhdb.csadmin.plugin.conn", "GetServerBean"); HHEvent revent = htree.sendEvent(getsbEvent); ServerBean serverbean = (ServerBean)revent.getObj(); Collection<String[]> data = new ArrayList<>(); String[] str1 = new String[2]; str1[0] = "属性"; str1[1] = "值"; String[] str2 = new String[2]; str2[0] = "主机地址"; str2[1] = serverbean.getHost(); String[] str3 = new String[2]; str3[0] = "端口号"; str3[1] = serverbean.getPort(); String[] str4 = new String[2]; str4[0] = "用户名"; str4[1] = serverbean.getUserName(); String[] str5 = new String[2]; str5[0] = "数据库"; str5[1] = serverbean.getDBName(); data.add(str1); data.add(str2); data.add(str3); data.add(str4); data.add(str5); CsvWriter csvWriter = new CsvWriter(); StringBuffer sbf = new StringBuffer(); try { csvWriter.writeSbf(sbf, data); htree.treeService.sendAttr(sbf.toString(),""); } catch (IOException e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } htree.treeService.sendCreateSql(""); } else if(type.equals(TreeNodeUtil.DB_TYPE)) { defultsend(); } else if(type.equals(TreeNodeUtil.DB_ITEM_TYPE)) { try { HHdbDatabase hhdbDb = (HHdbDatabase)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbDb.getProp()); String createsql = hhdbDb.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); LM.error(LM.Model.CS.name(), e); } }else if(type.equals(TreeNodeUtil.SCHEMA_TYPE)) { try { String csvstr = htree.treeService.getAttrCollectionSchema(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(""); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.SCHEMA_ITEM_TYPE)) { try { HHdbSchema hhdbSchema = (HHdbSchema)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbSchema.getProp()); String createsql = hhdbSchema.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.TABLE_TYPE)) { try { String csvstr = htree.treeService.getAttrCollectionTable( treeNode.getParentBaseTreeNode().getMetaTreeNodeBean().getName()); htree.treeService.sendAttr(csvstr,"true"); htree.treeService.sendCreateSql(""); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.TABLE_ITEM_TYPE)) { try { HHdbTable hhdbTb = (HHdbTable)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbTb.getProp()); String createsql = hhdbTb.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.COL_TYPE)) { try { String csvstr = htree.treeService.getAttrCollectionCol( treeNode.getParentBaseTreeNode().getMetaTreeNodeBean().getId()); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(""); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.CONSTRAINT_TYPE)) { try { String csvstr = htree.treeService.getAttrCollectionConstraints( treeNode.getParentBaseTreeNode().getMetaTreeNodeBean().getId()); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(""); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.INDEX_TYPE)) { try { String csvstr = htree.treeService.getAttrCollectionIndex( treeNode.getParentBaseTreeNode().getMetaTreeNodeBean().getId()); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(""); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.INDEX_ITEM_TYPE)) { try { HHdbIndex hhdbindex = (HHdbIndex)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbindex.getProp()); String createsql = hhdbindex.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } else if(type.equals(TreeNodeUtil.CONSTRAINT_PK_ITEM_TYPE)) { try { HHdbPk hhdbpk = (HHdbPk)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbpk.getProp()); String createsql = hhdbpk.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } else if(type.equals(TreeNodeUtil.CONSTRAINT_FK_ITEM_TYPE)) { try { HHdbFk hhdbfk = (HHdbFk)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbfk.getProp()); String createsql = hhdbfk.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } else if(type.equals(TreeNodeUtil.CONSTRAINT_UK_ITEM_TYPE)) { try { HHdbUk hhdbuk = (HHdbUk)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbuk.getProp()); String createsql = hhdbuk.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } else if(type.equals(TreeNodeUtil.CONSTRAINT_CK_ITEM_TYPE)) { try { HHdbCk hhdbck = (HHdbCk)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbck.getProp()); String createsql = hhdbck.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } else if(type.equals(TreeNodeUtil.CONSTRAINT_XK_ITEM_TYPE)) { try { HHdbXk hhdbxk = (HHdbXk)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbxk.getProp()); String createsql = hhdbxk.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.RULE_TYPE)) { try { String csvstr = htree.treeService.getAttrCollectionRule( treeNode.getParentBaseTreeNode().getMetaTreeNodeBean().getId()); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(""); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.TABLE_TRIGGER_TYPE)) { try { String csvstr = htree.treeService.getAttrCollectionTrigger( treeNode.getParentBaseTreeNode().getMetaTreeNodeBean().getId()); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(""); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.VIEW_TYPE)) { try { String csvstr = htree.treeService.getAttrCollectionView( treeNode.getParentBaseTreeNode().getMetaTreeNodeBean().getName()); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(""); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.VIEW_ITEM_TYPE)) { try { HHdbView hhdbvw = (HHdbView)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbvw.getProp()); String createsql = hhdbvw.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.SEQ_TYPE)) { try { String csvstr = htree.treeService.getAttrCollectionSequence( treeNode.getParentBaseTreeNode().getMetaTreeNodeBean().getName()); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(""); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.SEQ_ITEM_TYPE)) { try { HHdbSeq hhdbseq = (HHdbSeq)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbseq.getProp()); String createsql = hhdbseq.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.FUN_TYPE)) { try { String csvstr = htree.treeService.getAttrCollectionFuction( treeNode.getParentBaseTreeNode().getMetaTreeNodeBean().getName()); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(""); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.FUN_ITEM_TYPE)) { try { HHdbFun hhdbfun = (HHdbFun)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbfun.getProp()); String createsql = hhdbfun.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.TYPE_TYPE)) { try { String csvstr = htree.treeService.getAttrCollectionTypes( treeNode.getParentBaseTreeNode().getMetaTreeNodeBean().getId()); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(""); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.TYPE_ITEM_TYPE)) { try { String csvstr = htree.treeService.getAttrType( treeNode.getParentBaseTreeNode().getParentBaseTreeNode().getMetaTreeNodeBean().getId(), treeNode.getMetaTreeNodeBean().getId()); String createsql = htree.treeService.getCreateSqlType(treeNode.getParentBaseTreeNode().getParentBaseTreeNode().getMetaTreeNodeBean().getName(), treeNode.getParentBaseTreeNode().getParentBaseTreeNode().getMetaTreeNodeBean().getId(), treeNode.getMetaTreeNodeBean().getId()); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.SELECT_TYPE)) { defultsend(); }else if(type.equals(TreeNodeUtil.SELECT_ITEM_TYPE)) { defultsend(); }else if(type.equals(TreeNodeUtil.EXTENSION_TYPE)) { try { CmdEvent getsbEvent = new CmdEvent(htree.PLUGIN_ID, "com.hhdb.csadmin.plugin.conn", "GetServerBean"); HHEvent revent = htree.sendEvent(getsbEvent); ServerBean serverbean = (ServerBean)revent.getObj(); serverbean.setDBName(treeNode.getParentBaseTreeNode().getMetaTreeNodeBean().getName()); Connection conn = ConnService.createConnection(serverbean); ExtendXmlLoader exl = new ExtendXmlLoader(conn); String csvstr = exl.getAttrExtendCollection(); conn.close(); String createsql = ""; htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.EXTENSION_PLUGIN_TYPE)) { try { CmdEvent getsbEvent = new CmdEvent(htree.PLUGIN_ID, "com.hhdb.csadmin.plugin.conn", "GetServerBean"); HHEvent revent = htree.sendEvent(getsbEvent); ServerBean serverbean = (ServerBean)revent.getObj(); serverbean.setDBName(treeNode.getParentBaseTreeNode().getParentBaseTreeNode().getMetaTreeNodeBean().getName()); Connection conn = ConnService.createConnection(serverbean); ExtendXmlLoader exl = new ExtendXmlLoader(conn); String csvstr = exl.getAttrExtend(treeNode); conn.close(); String createsql = ""; htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.PERFORMANCE_MONITORING_TYPE)) { defultsend(); }else if(type.equals(TreeNodeUtil.TAB_SPACE_TYPE)) { defultsend(); }else if(type.equals(TreeNodeUtil.TAB_SPACE_ITEM_TYPE)) { try { HHdbTabSp hhdbtabsp = (HHdbTabSp)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbtabsp.getProp()); String createsql = hhdbtabsp.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.LOGIN_ROLE_TYPE)) { defultsend(); }else if(type.equals(TreeNodeUtil.LOGIN_ROLE_ITEM_TYPE)) { try { HHdbUser hhdbuser = (HHdbUser)treeNode.getNodeObject(); String csvstr = htree.treeService.getAttrByMap(hhdbuser.getProp()); String createsql = hhdbuser.getCreateSql(); htree.treeService.sendAttr(csvstr,""); htree.treeService.sendCreateSql(createsql); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }else if(type.equals(TreeNodeUtil.GROUP_TYPE)) { defultsend(); }else if(type.equals(TreeNodeUtil.CPU_MONITORING_TYPE)) { defultsend(); }else if(type.equals(TreeNodeUtil.DISK_MONITORING_TYPE)) { defultsend(); }else if(type.equals(TreeNodeUtil.MEMORY_MONITORING_TYPE)) { defultsend(); }else if(type.equals(TreeNodeUtil.COURSE_MONITORING_TYPE)) { defultsend(); }else if(type.equals(TreeNodeUtil.NETWORK_MONITORING_TYPE)) { defultsend(); } } private void defultsend(){ htree.treeService.sendAttr("",""); htree.treeService.sendCreateSql(""); } }
package dk.webbies.tscreate.main; import com.google.javascript.jscomp.parsing.parser.Parser; import dk.webbies.tscreate.*; import dk.webbies.tscreate.analysis.TypeAnalysis; import dk.webbies.tscreate.analysis.declarations.*; import dk.webbies.tscreate.analysis.declarations.types.DeclarationType; import dk.webbies.tscreate.analysis.methods.NoTypeAnalysis; import dk.webbies.tscreate.analysis.methods.combined.CombinedTypeAnalysis; import dk.webbies.tscreate.analysis.methods.contextSensitive.combined.CombinedContextSensitiveTypeAnalysis; import dk.webbies.tscreate.analysis.methods.contextSensitive.mixed.MixedContextSensitiveTypeAnalysis; import dk.webbies.tscreate.analysis.methods.contextSensitive.pureSubsets.PureSubsetsContextSensitiveTypeAnalysis; import dk.webbies.tscreate.analysis.methods.mixed.MixedTypeAnalysis; import dk.webbies.tscreate.analysis.methods.old.analysis.OldTypeAnalysis; import dk.webbies.tscreate.analysis.methods.pureSubsets.PureSubsetsTypeAnalysis; import dk.webbies.tscreate.analysis.methods.unionEverything.UnionEverythingTypeAnalysis; import dk.webbies.tscreate.analysis.methods.unionRecursively.UnionRecursivelyTypeAnalysis; import dk.webbies.tscreate.cleanup.RedundantInterfaceCleaner; import dk.webbies.tscreate.evaluation.*; import dk.webbies.tscreate.jsnap.*; import dk.webbies.tscreate.jsnap.classes.*; import dk.webbies.tscreate.main.patch.*; import dk.webbies.tscreate.paser.AST.*; import dk.webbies.tscreate.paser.JavaScriptParser; import dk.webbies.tscreate.util.Util; import java.io.*; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import static dk.webbies.tscreate.BenchMark.*; import static dk.webbies.tscreate.declarationReader.DeclarationParser.*; import static dk.webbies.tscreate.util.Util.toFixed; public class Main { public static void main(String[] args) throws IOException, InterruptedException { long start = System.currentTimeMillis(); try { // All the currently configured Benchmarks can be seen in the BenchMark.java file, there is a lot, and some of them were never used for the paper. // The ones used in the paper are: List<BenchMark> paperBenchmarks = Arrays.asList(ace, angular, async142, backbone, D3, ember1, FabricJS15, hammer, handlebars30, jQuery, knockout, leaflet, moment, vue, jasmine22, PIXI, react15, polymer16, three, underscore17); // Analyzing some benchmarks can be very memory intensive, if you have under 16GB of ram available, some benchmarks might run very slow (PixiJS and Ember are the worst offenders). // The below benchmarks should only use up to 3GB of RAM, even when running TSEvolve. List<BenchMark> fastBenchmarks = Arrays.asList(async142, backbone, hammer, handlebars30, jasmine22, knockout, moment, underscore17); // To run TSInfer on a benchmark, uncomment the below line, and TSInfer will run on the given benchmark. The declaration will both be printed to a file (name of which is printed in the beginning of the run), and to stdout. // runTSInfer(PIXI_4_0); // You can modify the options for a benchmark (see the options in Options.java, some of them are explained). // PIXI_4_0.getOptions().staticMethod = NONE; // PIXI_4_0.getOptions().createInstances = false; // runTSInfer(PIXI_4_0); // To run TSEvolve, use the runTSEvolve method (as seen below). // The first argument is the old JavaScript implementation, the second argument is the new implementation, and the last argument is the path were the resulting .json file should be saved. // The diff can be viewed by copying the .json you want to view to "diffViewer/diff.json", and then running the "View TSEvolve diff" configuration (dropdown in top-right corder of IntelliJ). (or view the index.html in the diffViewer folder using some webserver). // The TSEvolve runs used in the paper, uncomment to run // runTSEvolve(ember1, ember20, "diffViewer/ember-1-2.json"); // runTSEvolve(ember20, ember27, "diffViewer/ember-20-27.json"); // runTSEvolve(backbone, backbone133, "diffViewer/backbone-10-13.json"); // runTSEvolve(async142, async201, "diffViewer/async-1-2.json"); // runTSEvolve(handlebars30, handlebars4, "diffViewer/handlebars-3-4.json"); // runTSEvolve(moment, moment_214, "diffViewer/moment-to-214.json"); // runTSEvolve(PIXI, PIXI_4_0, "diffViewer/pixi-3-4.json"); // VERY memory intensive! Allocates up to 26GB, but should run on machines with 16GB of RAM that has an SSD. // Other TSEvolve runs. // runTSEvolve(jasmine22, jasmine25, "diffViewer/jasmine-22-25.json"); // runTSEvolve(react014, react15, "diffViewer/react-014-15.json"); // runTSEvolve(underscore17, underscore18, "diffViewer/underscore-17-18.json"); // runTSEvolve(polymer11, polymer16, "diffViewer/polymer-11-16.json"); // runTSEvolve(jasmine22, jasmine25, "diffViewer/jasmine-22-25.json"); // runTSEvolve(FabricJS15, FabricJS16, "diffViewer/fabric-15-16.json"); } catch (Throwable e) { System.err.println("Crashed: "); e.printStackTrace(System.err); } finally { long end = System.currentTimeMillis(); System.out.println("Ran in " + toFixed((end - start) / 1000.0, 1) + "s"); System.exit(0); } } public static void runTSEvolve(BenchMark oldVersion, BenchMark newVersion, String jsonPath) throws Throwable { PatchFile patchFile = PatchFileFactory.fromImplementation(oldVersion, newVersion); savePatchFile(patchFile, jsonPath); } public static void savePatchFile(PatchFile patchFile, String path) throws IOException { String printed = patchFile.toJSON().toString(); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path))); writer.write(printed); writer.close(); } public static Score makeSuperEval(BenchMark benchMark) throws IOException { if (benchMark.declarationPath == null) { throw new RuntimeException(); } Set<String> resultingDeclarationFilePaths = new HashSet<>(); for (Options.StaticAnalysisMethod method : Options.StaticAnalysisMethod.values()) { benchMark.getOptions().staticMethod = method; String resultDeclarationFilePath = getResultingDeclarationPath(benchMark); if (new File(resultDeclarationFilePath).exists()) { resultingDeclarationFilePaths.add(resultDeclarationFilePath); } } System.out.println("Getting a \"best\" possible evaluation from " + resultingDeclarationFilePaths.size() + " evaluations"); FunctionExpression AST = new JavaScriptParser(benchMark.languageLevel).parse(benchMark.name, getScript(benchMark)).toTSCreateAST(); Snap.Obj globalObject = JSNAPUtil.getStateDump(JSNAPUtil.getJsnapRaw(benchMark.scriptPath, benchMark.getOptions(), benchMark.dependencyScripts(), benchMark.testFiles, benchMark.getOptions().asyncTest), AST); Snap.Obj emptySnap = JSNAPUtil.getEmptyJSnap(benchMark.getOptions(), benchMark.dependencyScripts(), AST); // Not empty, just the one without the library we are analyzing. HashMap<Snap.Obj, LibraryClass> libraryClasses = new ClassHierarchyExtractor(globalObject, benchMark.getOptions()).extract(); Evaluation evaluation = new DeclarationEvaluator(resultingDeclarationFilePaths, benchMark, globalObject, libraryClasses, benchMark.getOptions(), emptySnap).getEvaluation(); System.out.println(evaluation); System.out.println("best : " + Util.toFixed(evaluation.score().fMeasure, 4) + " - " + Util.toFixed(evaluation.score().recall, 4) + " - " + Util.toFixed(evaluation.score().precision, 4)); return null; } public static Evaluation runTSInfer(BenchMark benchMark) throws IOException { String resultDeclarationFilePath = getResultingDeclarationPath(benchMark); System.out.println("Analysing " + benchMark.name + " - output: " + resultDeclarationFilePath); FunctionExpression AST = new JavaScriptParser(benchMark.languageLevel).parse(benchMark.name, getScript(benchMark)).toTSCreateAST(); Snap.Obj globalObject = JSNAPUtil.getStateDump(JSNAPUtil.getJsnapRaw(benchMark.scriptPath, benchMark.getOptions(), benchMark.dependencyScripts(), benchMark.testFiles, benchMark.getOptions().asyncTest), AST); Snap.Obj emptySnap = JSNAPUtil.getEmptyJSnap(benchMark.getOptions(), benchMark.dependencyScripts(), AST); // Not empty, just the one without the library we are analyzing. HashMap<Snap.Obj, LibraryClass> libraryClasses = new ClassHierarchyExtractor(globalObject, benchMark.getOptions()).extract(); NativeClassesMap nativeClasses = parseNatives(globalObject, benchMark.languageLevel.environment, benchMark.dependencyDeclarations(), libraryClasses, emptySnap); Map<String, DeclarationType> declaration = createDeclaration(benchMark, AST, globalObject, emptySnap, libraryClasses, nativeClasses); System.out.println("Printing declaration"); String printedDeclaration = new DeclarationPrinter(declaration, nativeClasses, benchMark.getOptions()).print(); System.out.println(printedDeclaration); Util.writeFile(resultDeclarationFilePath, printedDeclaration); Evaluation evaluation = null; if (benchMark.declarationPath != null) { evaluation = new DeclarationEvaluator(resultDeclarationFilePath, benchMark, globalObject, libraryClasses, benchMark.getOptions(), emptySnap).getEvaluation(); // System.out.println(evaluation); } if (benchMark.getOptions().tsCheck) { System.out.println("TSCheck: "); System.out.println(Util.tsCheck(benchMark.scriptPath, resultDeclarationFilePath)); System.out.println("----------"); } if (evaluation == null) { return null; } else { String evaluationString = "\n\n/*\n" + evaluation.toString() + "\n*/\n"; if (benchMark.getOptions().debugPrint) { evaluationString = "\n\n/*\n" + ((DebugEvaluation)evaluation).debugPrint() + "\n\n*/\n" + evaluationString; } Util.writeFile(resultDeclarationFilePath, printedDeclaration + evaluationString); return evaluation; } } public static Map<String, DeclarationType> createDeclaration(BenchMark benchMark) throws IOException { String resultDeclarationFilePath = getResultingDeclarationPath(benchMark); System.out.println("Analysing " + benchMark.name + " - output: " + resultDeclarationFilePath); FunctionExpression AST = new JavaScriptParser(benchMark.languageLevel).parse(benchMark.name, getScript(benchMark)).toTSCreateAST(); Snap.Obj globalObject = JSNAPUtil.getStateDump(JSNAPUtil.getJsnapRaw(benchMark.scriptPath, benchMark.getOptions(), benchMark.dependencyScripts(), benchMark.testFiles, benchMark.getOptions().asyncTest), AST); Snap.Obj emptySnap = JSNAPUtil.getEmptyJSnap(benchMark.getOptions(), benchMark.dependencyScripts(), AST); // Not empty, just the one without the library we are analyzing. Map<Snap.Obj, LibraryClass> libraryClasses = new ClassHierarchyExtractor(globalObject, benchMark.getOptions()).extract(); NativeClassesMap nativeClasses = parseNatives(globalObject, benchMark.languageLevel.environment, benchMark.dependencyDeclarations(), libraryClasses, emptySnap); return createDeclaration(benchMark, AST, globalObject, emptySnap, libraryClasses, nativeClasses); } public static long staticAnalysisTime = 0; // ugly ugly ugly, i know. public static Map<String, DeclarationType> createDeclaration(BenchMark benchMark, FunctionExpression AST, Snap.Obj globalObject, Snap.Obj emptySnap, Map<Snap.Obj, LibraryClass> libraryClasses, NativeClassesMap nativeClasses) { Map<AstNode, Set<Snap.Obj>> callsites = Collections.EMPTY_MAP; if (benchMark.getOptions().recordCalls && globalObject.getProperty("__jsnap__callsitesToClosures") != null && benchMark.getOptions().useCallsiteInformation) { callsites = JSNAPUtil.getCallsitesToClosures((Snap.Obj) globalObject.getProperty("__jsnap__callsitesToClosures").value, AST); } long startTime = System.currentTimeMillis(); TypeAnalysis typeAnalysis = createTypeAnalysis(benchMark, globalObject, libraryClasses, nativeClasses, callsites); typeAnalysis.analyseFunctions(); Map<String, DeclarationType> declaration = new DeclarationBuilder(emptySnap, globalObject, typeAnalysis.getTypeFactory()).buildDeclaration(); if (benchMark.getOptions().combineInterfacesAfterAnalysis) { System.out.println("Comnbining types"); new RedundantInterfaceCleaner(declaration, nativeClasses, typeAnalysis.getTypeFactory().typeReducer).runHeuristics(); } else { System.out.println("Cleaning up types"); new RedundantInterfaceCleaner(declaration, nativeClasses, typeAnalysis.getTypeFactory().typeReducer).cleanDeclarations(); } Main.staticAnalysisTime = System.currentTimeMillis() - startTime; typeAnalysis.getTypeFactory().typeReducer.originals.clear(); typeAnalysis.getTypeFactory().typeReducer.combinationTypeCache.clear(); return declaration; } public static Score getScore(BenchMark benchMark, long timeout) throws IOException { String resultDeclarationFilePath = getResultingDeclarationPath(benchMark); Score readFromFile = readScoreFromDeclaration(resultDeclarationFilePath); if (readFromFile != null) { return readFromFile; } Evaluation evaluation = getEvaluation(benchMark, getResultingDeclarationPath(benchMark), timeout); if (evaluation == null) { throw new RuntimeException(); } else { return evaluation.score(); } } static Evaluation getEvaluation(BenchMark benchMark, String generatedDeclarationPath, long timeout) throws IOException { System.out.println("Get evaluation of " + benchMark.name + " - from: " + generatedDeclarationPath); if (!new File(generatedDeclarationPath).exists()) { if (timeout > 0) { return runAnalysisWithTimeout(benchMark, timeout); } else { return runTSInfer(benchMark); } } FunctionExpression AST = new JavaScriptParser(benchMark.languageLevel).parse(benchMark.name, getScript(benchMark)).toTSCreateAST(); Snap.Obj globalObject = JSNAPUtil.getStateDump(JSNAPUtil.getJsnapRaw(benchMark.scriptPath, benchMark.getOptions(), benchMark.dependencyScripts(), benchMark.testFiles, benchMark.getOptions().asyncTest), AST); Snap.Obj emptySnap = JSNAPUtil.getEmptyJSnap(benchMark.getOptions(), benchMark.dependencyScripts(), AST); // Not empty, just the one without the library we are analyzing. HashMap<Snap.Obj, LibraryClass> libraryClasses = new ClassHierarchyExtractor(globalObject, benchMark.getOptions()).extract(); Evaluation evaluation = null; if (benchMark.declarationPath != null) { evaluation = new DeclarationEvaluator(generatedDeclarationPath, benchMark, globalObject, libraryClasses, benchMark.getOptions(), emptySnap).getEvaluation(); } return evaluation; } private static Score readScoreFromDeclaration(String filePath) throws FileNotFoundException { if (!new File(filePath).exists()) { return null; } List<String> lines = new BufferedReader(new FileReader(new File(filePath))).lines().collect(Collectors.toList()); Collections.reverse(lines); Double fMeasure = null; Double precision = null; Double recall = null; int counter = 0; for (String line : lines) { if (counter++ > 10) { break; } if (line.startsWith("Score: ")) { fMeasure = Double.parseDouble(line.substring("Score: ".length(), line.length())); } if (line.startsWith("Precision: ")) { precision = Double.parseDouble(line.substring("Precision: ".length(), line.length())); } if (line.startsWith("Recall: ")) { recall = Double.parseDouble(line.substring("Recall: ".length(), line.length())); } } if (fMeasure != null && precision != null && recall != null) { return new Score(fMeasure, precision, recall); } else { return null; } } public static String getResultingDeclarationPath(BenchMark benchMark) { Options options = benchMark.getOptions(); String fileSuffix = options.staticMethod.fileSuffix; if (options.combineInterfacesAfterAnalysis) { fileSuffix += "_smaller"; } switch (options.evaluationMethod) { case ONLY_FUNCTIONS: fileSuffix += "_evalFunc"; break; case ONLY_HEAP: fileSuffix += "_evalHeap"; break; case EVERYTHING: break; default: throw new RuntimeException(); } if (options.disableFlowFromArgsToParams) { fileSuffix += "_noArgPar"; } if (options.disableFlowFromParamsToArgs) { fileSuffix += "_noParArg"; } if (options.disableFlowFromCallsiteToReturn) { fileSuffix += "_noCalRet"; } if (options.disableFlowFromReturnToCallsite) { fileSuffix += "_noRetCal"; } if (options.useJSDoc) { fileSuffix += "_jsDoc"; } return benchMark.scriptPath + "." + fileSuffix + ".gen.d.ts"; } private static TypeAnalysis createTypeAnalysis(BenchMark benchMark, Snap.Obj globalObject, Map<Snap.Obj, LibraryClass> libraryClasses, NativeClassesMap nativeClasses, Map<AstNode, Set<Snap.Obj>> callsites) { switch (benchMark.getOptions().staticMethod) { case MIXED: return new MixedTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, false, callsites); case UPPER: return new MixedTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, true, callsites); case ANDERSON: return new PureSubsetsTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, callsites); case UNIFICATION: return new UnionEverythingTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, callsites); case UNIFICATION_CONTEXT_SENSITIVE: return new UnionRecursivelyTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, callsites); case OLD_UNIFICATION_CONTEXT_SENSITIVE: return new OldTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses); case OLD_UNIFICATION: return new OldTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses); case COMBINED: return new CombinedTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, false, callsites); case UPPER_LOWER: return new CombinedTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, true, callsites); case MIXED_CONTEXT_SENSITIVE: return new MixedContextSensitiveTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, false, callsites); case LOWER_CONTEXT_SENSITIVE: return new MixedContextSensitiveTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, true, callsites); case ANDERSON_CONTEXT_SENSITIVE: return new PureSubsetsContextSensitiveTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, callsites); case COMBINED_CONTEXT_SENSITIVE: return new CombinedContextSensitiveTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, false, callsites); case UPPER_LOWER_CONTEXT_SENSITIVE: return new CombinedContextSensitiveTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, true, callsites); case NONE: return new NoTypeAnalysis(libraryClasses, benchMark.getOptions(), globalObject, nativeClasses, false, callsites); default: throw new RuntimeException("I don't even know this static analysis method. "); } } public static String getScript(BenchMark benchMark) throws IOException { StringBuilder result = new StringBuilder(); result.append(Util.readFile(benchMark.scriptPath)).append("\n"); for (String testFile : benchMark.testFiles) { result.append(Util.readFile(testFile)).append("\n"); } return result.toString(); } private static void generateDeclarations(List<BenchMark> benchMarks) throws IOException { for (BenchMark benchmark : benchMarks) { benchmark.declarationPath = null; runTSInfer(benchmark); } System.out.println("Generated all declarations"); } public static Evaluation runAnalysisWithTimeout(BenchMark benchMark, long timeout) { AtomicReference<Evaluation> result = new AtomicReference<>(null); Thread benchThread = new Thread(() -> { try { result.set(runTSInfer(benchMark)); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }); benchThread.start(); Thread killThread = new Thread(() -> { try { Thread.sleep(timeout); } catch (InterruptedException e) { return; } if (result.get() != null) { return; } if (benchThread.isAlive()) { System.err.println("Stopping benchmark because of timeout."); //noinspection deprecation benchThread.stop(); // <- Deprecated, and i know it. } }); killThread.start(); try { benchThread.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } killThread.interrupt(); return result.get(); } @SuppressWarnings("Duplicates") public static Map<String, DeclarationType> createDeclarationWithTimeout(BenchMark benchMark, long timeout) { AtomicReference<Map<String, DeclarationType>> result = new AtomicReference<>(null); Thread benchThread = new Thread(() -> { try { result.set(createDeclaration(benchMark)); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }); benchThread.start(); Thread killThread = new Thread(() -> { try { Thread.sleep(timeout); } catch (InterruptedException e) { return; } if (result.get() != null) { return; } if (benchThread.isAlive()) { System.err.println("Stopping benchmark because of timeout."); benchThread.interrupt(); //noinspection deprecation benchThread.stop(); // <- Deprecated, and i know it. } }); killThread.start(); try { benchThread.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } killThread.interrupt(); return result.get(); } public enum LanguageLevel { ES5(Parser.Config.Mode.ES5, Environment.ES5DOM), ES6(Parser.Config.Mode.ES6, Environment.ES6DOM); public final Parser.Config.Mode closureCompilerMode; public final Environment environment; LanguageLevel(Parser.Config.Mode closure, Environment declaration) { this.closureCompilerMode = closure; this.environment = declaration; } } }
package testing.ingtest; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import java.util.Set; @Entity public class Customers { @Id private int customerid; private String name; private String region; private String brand; private int phnumber; private String email; private String startDate; public Customers() { } public Customers(int customerid, String name, String region, String brand, int phnumber, String email, String startDate) { this.customerid = customerid; this.name = name; this.region = region; this.brand = brand; this.phnumber = phnumber; this.email = email; this.startDate = startDate; } public int getCustomerid() { return customerid; } public void setCustomerid(int customerid) { this.customerid = customerid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getPhnumber() { return phnumber; } public void setPhnumber(int phnumber) { this.phnumber = phnumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jdbc.datasource.lookup; import java.sql.Connection; import java.sql.SQLException; import java.util.Collections; import java.util.Map; import javax.sql.DataSource; import org.springframework.beans.factory.InitializingBean; import org.springframework.jdbc.datasource.AbstractDataSource; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; /** * Abstract {@link javax.sql.DataSource} implementation that routes {@link #getConnection()} * calls to one of various target DataSources based on a lookup key. The latter is usually * (but not necessarily) determined through some thread-bound transaction context. * * @author Juergen Hoeller * @since 2.0.1 * @see #setTargetDataSources * @see #setDefaultTargetDataSource * @see #determineCurrentLookupKey() */ public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean { @Nullable private Map<Object, Object> targetDataSources; @Nullable private Object defaultTargetDataSource; private boolean lenientFallback = true; private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup(); @Nullable private Map<Object, DataSource> resolvedDataSources; @Nullable private DataSource resolvedDefaultDataSource; /** * Specify the map of target DataSources, with the lookup key as key. * The mapped value can either be a corresponding {@link javax.sql.DataSource} * instance or a data source name String (to be resolved via a * {@link #setDataSourceLookup DataSourceLookup}). * <p>The key can be of arbitrary type; this class implements the * generic lookup process only. The concrete key representation will * be handled by {@link #resolveSpecifiedLookupKey(Object)} and * {@link #determineCurrentLookupKey()}. */ public void setTargetDataSources(Map<Object, Object> targetDataSources) { this.targetDataSources = targetDataSources; } /** * Specify the default target DataSource, if any. * <p>The mapped value can either be a corresponding {@link javax.sql.DataSource} * instance or a data source name String (to be resolved via a * {@link #setDataSourceLookup DataSourceLookup}). * <p>This DataSource will be used as target if none of the keyed * {@link #setTargetDataSources targetDataSources} match the * {@link #determineCurrentLookupKey()} current lookup key. */ public void setDefaultTargetDataSource(Object defaultTargetDataSource) { this.defaultTargetDataSource = defaultTargetDataSource; } /** * Specify whether to apply a lenient fallback to the default DataSource * if no specific DataSource could be found for the current lookup key. * <p>Default is "true", accepting lookup keys without a corresponding entry * in the target DataSource map - simply falling back to the default DataSource * in that case. * <p>Switch this flag to "false" if you would prefer the fallback to only apply * if the lookup key was {@code null}. Lookup keys without a DataSource * entry will then lead to an IllegalStateException. * @see #setTargetDataSources * @see #setDefaultTargetDataSource * @see #determineCurrentLookupKey() */ public void setLenientFallback(boolean lenientFallback) { this.lenientFallback = lenientFallback; } /** * Set the DataSourceLookup implementation to use for resolving data source * name Strings in the {@link #setTargetDataSources targetDataSources} map. * <p>Default is a {@link JndiDataSourceLookup}, allowing the JNDI names * of application server DataSources to be specified directly. */ public void setDataSourceLookup(@Nullable DataSourceLookup dataSourceLookup) { this.dataSourceLookup = (dataSourceLookup != null ? dataSourceLookup : new JndiDataSourceLookup()); } @Override public void afterPropertiesSet() { if (this.targetDataSources == null) { throw new IllegalArgumentException("Property 'targetDataSources' is required"); } this.resolvedDataSources = CollectionUtils.newHashMap(this.targetDataSources.size()); this.targetDataSources.forEach((key, value) -> { Object lookupKey = resolveSpecifiedLookupKey(key); DataSource dataSource = resolveSpecifiedDataSource(value); this.resolvedDataSources.put(lookupKey, dataSource); }); if (this.defaultTargetDataSource != null) { this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource); } } /** * Resolve the given lookup key object, as specified in the * {@link #setTargetDataSources targetDataSources} map, into * the actual lookup key to be used for matching with the * {@link #determineCurrentLookupKey() current lookup key}. * <p>The default implementation simply returns the given key as-is. * @param lookupKey the lookup key object as specified by the user * @return the lookup key as needed for matching */ protected Object resolveSpecifiedLookupKey(Object lookupKey) { return lookupKey; } /** * Resolve the specified data source object into a DataSource instance. * <p>The default implementation handles DataSource instances and data source * names (to be resolved via a {@link #setDataSourceLookup DataSourceLookup}). * @param dataSourceObject the data source value object as specified in the * {@link #setTargetDataSources targetDataSources} map * @return the resolved DataSource (never {@code null}) * @throws IllegalArgumentException in case of an unsupported value type */ protected DataSource resolveSpecifiedDataSource(Object dataSourceObject) throws IllegalArgumentException { if (dataSourceObject instanceof DataSource dataSource) { return dataSource; } else if (dataSourceObject instanceof String dataSourceName) { return this.dataSourceLookup.getDataSource(dataSourceName); } else { throw new IllegalArgumentException( "Illegal data source value - only [javax.sql.DataSource] and String supported: " + dataSourceObject); } } /** * Return the resolved target DataSources that this router manages. * @return an unmodifiable map of resolved lookup keys and DataSources * @throws IllegalStateException if the target DataSources are not resolved yet * @since 5.2.9 * @see #setTargetDataSources */ public Map<Object, DataSource> getResolvedDataSources() { Assert.state(this.resolvedDataSources != null, "DataSources not resolved yet - call afterPropertiesSet"); return Collections.unmodifiableMap(this.resolvedDataSources); } /** * Return the resolved default target DataSource, if any. * @return the default DataSource, or {@code null} if none or not resolved yet * @since 5.2.9 * @see #setDefaultTargetDataSource */ @Nullable public DataSource getResolvedDefaultDataSource() { return this.resolvedDefaultDataSource; } @Override public Connection getConnection() throws SQLException { return determineTargetDataSource().getConnection(); } @Override public Connection getConnection(String username, String password) throws SQLException { return determineTargetDataSource().getConnection(username, password); } @Override @SuppressWarnings("unchecked") public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(this)) { return (T) this; } return determineTargetDataSource().unwrap(iface); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return (iface.isInstance(this) || determineTargetDataSource().isWrapperFor(iface)); } /** * Retrieve the current target DataSource. Determines the * {@link #determineCurrentLookupKey() current lookup key}, performs * a lookup in the {@link #setTargetDataSources targetDataSources} map, * falls back to the specified * {@link #setDefaultTargetDataSource default target DataSource} if necessary. * @see #determineCurrentLookupKey() */ protected DataSource determineTargetDataSource() { Assert.notNull(this.resolvedDataSources, "DataSource router not initialized"); Object lookupKey = determineCurrentLookupKey(); DataSource dataSource = this.resolvedDataSources.get(lookupKey); if (dataSource == null && (this.lenientFallback || lookupKey == null)) { dataSource = this.resolvedDefaultDataSource; } if (dataSource == null) { throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]"); } return dataSource; } /** * Determine the current lookup key. This will typically be * implemented to check a thread-bound transaction context. * <p>Allows for arbitrary keys. The returned key needs * to match the stored lookup key type, as resolved by the * {@link #resolveSpecifiedLookupKey} method. */ @Nullable protected abstract Object determineCurrentLookupKey(); }
package 序列化; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; /** * Linkedlist * HashMap自行实现序列化与反序列化 */ public class SerializableArray { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("实现"); list.add("序"); list.add("需要"); try { FileOutputStream fileOut = new FileOutputStream("D:\\program\\ProgramOfIdea\\MyJavaStudy2\\src" + "\\序列化\\mySerialize.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(list); out.close(); fileOut.close(); System.out.printf("Serialized list is saved in mySerialize.txt"); } catch (IOException i) { i.printStackTrace(); } } }
package com.example.pepi.calculatorapp; /** * Created by pepi_ on 08/19/2018. */ public class Calculator { private double first,second; public void setFirst(double first) { this.first = first; } public void setSecond(double second) { this.second = second; } public double Adition(){ return first+second; } public double Subtraction(){ return first-second; } public double Multiplication(){ return first*second; } public double Division() throws Exception { if(second == 0) { throw new Exception("Nuk lejohet pjestimi me zero"); } return first/second; } public double Mod(){ if(second == 0) return 1; double amount=1; for(int i=1;i<=(int) second;i++){ amount=amount*first; } return amount; } }
package org.infinispan.distribution; import org.infinispan.Cache; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.interceptors.base.CommandInterceptor; import org.infinispan.interceptors.distribution.L1NonTxInterceptor; import org.infinispan.interceptors.distribution.NonTxDistributionInterceptor; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.test.TestingUtil; import org.infinispan.tx.dld.ControlledRpcManager; import org.testng.annotations.Test; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @Test(groups = "functional", testName = "distribution.DistSyncL1FuncTest") public class DistSyncL1FuncTest extends BaseDistSyncL1Test { public DistSyncL1FuncTest() { sync = true; tx = false; testRetVals = true; } @Override protected Class<? extends CommandInterceptor> getDistributionInterceptorClass() { return NonTxDistributionInterceptor.class; } @Override protected Class<? extends CommandInterceptor> getL1InterceptorClass() { return L1NonTxInterceptor.class; } protected void assertL1PutWithConcurrentUpdate(final Cache<Object, String> nonOwnerCache, Cache<Object, String> ownerCache, final boolean replace, final Object key, final String originalValue, final String nonOwnerValue, String updateValue) throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { CyclicBarrier barrier = new CyclicBarrier(2); addBlockingInterceptorBeforeTx(nonOwnerCache, barrier, replace ? ReplaceCommand.class : PutKeyValueCommand.class); try { Future<String> future = fork(new Callable<String>() { @Override public String call() throws Exception { if (replace) { // This should always be true if (nonOwnerCache.replace(key, originalValue, nonOwnerValue)) { return originalValue; } return nonOwnerCache.get(key); } else { return nonOwnerCache.put(key, nonOwnerValue); } } }); // Now wait for the put/replace to return and block it for now barrier.await(5, TimeUnit.SECONDS); // Owner should have the new value assertEquals(nonOwnerValue, ownerCache.put(key, updateValue)); // Now let owner key->updateValue go through barrier.await(5, TimeUnit.SECONDS); // This should be originalValue still as we did the get assertEquals(originalValue, future.get(5, TimeUnit.SECONDS)); // Remove the interceptor now since we don't want to block ourselves - if using phaser this isn't required removeAllBlockingInterceptorsFromCache(nonOwnerCache); assertL1StateOnLocalWrite(nonOwnerCache, ownerCache, key, updateValue); // The nonOwnerCache should retrieve new value as it isn't in L1 assertEquals(updateValue, nonOwnerCache.get(key)); assertIsInL1(nonOwnerCache, key); } finally { removeAllBlockingInterceptorsFromCache(nonOwnerCache); } } @Test public void testNoEntryInL1PutWithConcurrentInvalidation() throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { final Cache<Object, String> nonOwnerCache = getFirstNonOwner(key); final Cache<Object, String> ownerCache = getFirstOwner(key); // Put the first value in the owner, so the L1 is empty ownerCache.put(key, firstValue); assertL1PutWithConcurrentUpdate(nonOwnerCache, ownerCache, false, key, firstValue, "intermediate-put", secondValue); } @Test public void testEntryInL1PutWithConcurrentInvalidation() throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { final Cache<Object, String> nonOwnerCache = getFirstNonOwner(key); final Cache<Object, String> ownerCache = getFirstOwner(key); // Put the first value in a non owner, so the L1 has the key ownerCache.put(key, firstValue); nonOwnerCache.get(key); assertIsInL1(nonOwnerCache, key); assertL1PutWithConcurrentUpdate(nonOwnerCache, ownerCache, false, key, firstValue, "intermediate-put", secondValue); } @Test public void testNoEntryInL1PutWithConcurrentPut() throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { final Cache<Object, String> nonOwnerCache = getFirstNonOwner(key); final Cache<Object, String> ownerCache = getFirstOwner(key); // Put the first value in the owner, so the L1 is empty ownerCache.put(key, firstValue); assertL1PutWithConcurrentUpdate(nonOwnerCache, nonOwnerCache, false, key, firstValue, "intermediate-put", secondValue); } @Test public void testEntryInL1PutWithConcurrentPut() throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { final Cache<Object, String> nonOwnerCache = getFirstNonOwner(key); final Cache<Object, String> ownerCache = getFirstOwner(key); // Put the first value in a non owner, so the L1 has the key ownerCache.put(key, firstValue); nonOwnerCache.get(key); assertIsInL1(nonOwnerCache, key); assertL1PutWithConcurrentUpdate(nonOwnerCache, nonOwnerCache, false, key, firstValue, "intermediate-put", secondValue); } @Test public void testNoEntryInL1ReplaceWithConcurrentInvalidation() throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { final Cache<Object, String> nonOwnerCache = getFirstNonOwner(key); final Cache<Object, String> ownerCache = getFirstOwner(key); // Put the first value in the owner, so the L1 is empty ownerCache.put(key, firstValue); assertL1PutWithConcurrentUpdate(nonOwnerCache, ownerCache, true, key, firstValue, "intermediate-put", secondValue); } @Test public void testEntryInL1ReplaceWithConcurrentInvalidation() throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { final Cache<Object, String> nonOwnerCache = getFirstNonOwner(key); final Cache<Object, String> ownerCache = getFirstOwner(key); // Put the first value in a non owner, so the L1 has the key ownerCache.put(key, firstValue); nonOwnerCache.get(key); assertIsInL1(nonOwnerCache, key); assertL1PutWithConcurrentUpdate(nonOwnerCache, ownerCache, true, key, firstValue, "intermediate-put", secondValue); } @Test public void testNoEntryInL1ReplaceWithConcurrentPut() throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { final Cache<Object, String> nonOwnerCache = getFirstNonOwner(key); final Cache<Object, String> ownerCache = getFirstOwner(key); // Put the first value in the owner, so the L1 is empty ownerCache.put(key, firstValue); assertL1PutWithConcurrentUpdate(nonOwnerCache, nonOwnerCache, true, key, firstValue, "intermediate-put", secondValue); } @Test public void testEntryInL1ReplaceWithConcurrentPut() throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { final Cache<Object, String> nonOwnerCache = getFirstNonOwner(key); final Cache<Object, String> ownerCache = getFirstOwner(key); // Put the first value in a non owner, so the L1 has the key ownerCache.put(key, firstValue); nonOwnerCache.get(key); assertIsInL1(nonOwnerCache, key); assertL1PutWithConcurrentUpdate(nonOwnerCache, nonOwnerCache, true, key, firstValue, "intermediate-put", secondValue); } @Test public void testNoEntryInL1GetWithConcurrentReplace() throws InterruptedException, ExecutionException, TimeoutException, BrokenBarrierException { final Cache<Object, String> nonOwnerCache = getFirstNonOwner(key); final Cache<Object, String> ownerCache = getFirstOwner(key); // Put the first value in a non owner, so the L1 has the key ownerCache.put(key, firstValue); nonOwnerCache.get(key); assertIsInL1(nonOwnerCache, key); assertL1PutWithConcurrentUpdate(nonOwnerCache, nonOwnerCache, true, key, firstValue, "intermediate-put", secondValue); } @Test public void testNoEntryInL1PutReplacedNullValueConcurrently() throws InterruptedException, ExecutionException, TimeoutException { final Cache<Object, String> nonOwnerCache = getFirstNonOwner(key); final Cache<Object, String> ownerCache = getFirstOwner(key); RpcManager rm = TestingUtil.extractComponent(nonOwnerCache, RpcManager.class); ControlledRpcManager crm = new ControlledRpcManager(rm); // Make our node block and not return the get yet crm.blockAfter(PutKeyValueCommand.class); TestingUtil.replaceComponent(nonOwnerCache, RpcManager.class, crm, true); try { Future<String> future = nonOwnerCache.putIfAbsentAsync(key, firstValue); // Now wait for the get to return and block it for now crm.waitForCommandToBlock(5, TimeUnit.SECONDS); // Owner should have the new value assertEquals(firstValue, ownerCache.remove(key)); // Now let owner key->updateValue go through crm.stopBlocking(); // This should be originalValue still as we did the get assertNull(future.get(5, TimeUnit.SECONDS)); // Remove the interceptor now since we don't want to block ourselves - if using phaser this isn't required removeAllBlockingInterceptorsFromCache(nonOwnerCache); assertIsNotInL1(nonOwnerCache, key); // The nonOwnerCache should retrieve new value as it isn't in L1 assertNull(nonOwnerCache.get(key)); assertIsNotInL1(nonOwnerCache, key); } finally { TestingUtil.replaceComponent(nonOwnerCache, RpcManager.class, rm, true); } } }
package br.com.senac.Interface; public interface Animais { public int getId(); public void setId(int id); public String getEspecie(); public void setEspecie(String especie); public String getLocomocao(); public void setLocomocao(String locomocao); public float getTamanho(); public void setTamanho(float tamanho); public float getPeso(); public void setPeso(float peso); public String getGenero(); public void setGenero(String genero); public int getQuantidade(); public void setQuantidade(int quantidade); public float getQuantidadeComida(); public void setQuantidadeComida(float peso); }
/** * This class is generated by jOOQ */ package schema.tables; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Identity; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import schema.BitnamiEdx; import schema.Keys; import schema.tables.records.StudentManualenrollmentauditRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.4" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class StudentManualenrollmentaudit extends TableImpl<StudentManualenrollmentauditRecord> { private static final long serialVersionUID = 1773817745; /** * The reference instance of <code>bitnami_edx.student_manualenrollmentaudit</code> */ public static final StudentManualenrollmentaudit STUDENT_MANUALENROLLMENTAUDIT = new StudentManualenrollmentaudit(); /** * The class holding records for this type */ @Override public Class<StudentManualenrollmentauditRecord> getRecordType() { return StudentManualenrollmentauditRecord.class; } /** * The column <code>bitnami_edx.student_manualenrollmentaudit.id</code>. */ public final TableField<StudentManualenrollmentauditRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>bitnami_edx.student_manualenrollmentaudit.enrolled_email</code>. */ public final TableField<StudentManualenrollmentauditRecord, String> ENROLLED_EMAIL = createField("enrolled_email", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.student_manualenrollmentaudit.time_stamp</code>. */ public final TableField<StudentManualenrollmentauditRecord, Timestamp> TIME_STAMP = createField("time_stamp", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); /** * The column <code>bitnami_edx.student_manualenrollmentaudit.state_transition</code>. */ public final TableField<StudentManualenrollmentauditRecord, String> STATE_TRANSITION = createField("state_transition", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.student_manualenrollmentaudit.reason</code>. */ public final TableField<StudentManualenrollmentauditRecord, String> REASON = createField("reason", org.jooq.impl.SQLDataType.CLOB, this, ""); /** * The column <code>bitnami_edx.student_manualenrollmentaudit.enrolled_by_id</code>. */ public final TableField<StudentManualenrollmentauditRecord, Integer> ENROLLED_BY_ID = createField("enrolled_by_id", org.jooq.impl.SQLDataType.INTEGER, this, ""); /** * The column <code>bitnami_edx.student_manualenrollmentaudit.enrollment_id</code>. */ public final TableField<StudentManualenrollmentauditRecord, Integer> ENROLLMENT_ID = createField("enrollment_id", org.jooq.impl.SQLDataType.INTEGER, this, ""); /** * Create a <code>bitnami_edx.student_manualenrollmentaudit</code> table reference */ public StudentManualenrollmentaudit() { this("student_manualenrollmentaudit", null); } /** * Create an aliased <code>bitnami_edx.student_manualenrollmentaudit</code> table reference */ public StudentManualenrollmentaudit(String alias) { this(alias, STUDENT_MANUALENROLLMENTAUDIT); } private StudentManualenrollmentaudit(String alias, Table<StudentManualenrollmentauditRecord> aliased) { this(alias, aliased, null); } private StudentManualenrollmentaudit(String alias, Table<StudentManualenrollmentauditRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return BitnamiEdx.BITNAMI_EDX; } /** * {@inheritDoc} */ @Override public Identity<StudentManualenrollmentauditRecord, Integer> getIdentity() { return Keys.IDENTITY_STUDENT_MANUALENROLLMENTAUDIT; } /** * {@inheritDoc} */ @Override public UniqueKey<StudentManualenrollmentauditRecord> getPrimaryKey() { return Keys.KEY_STUDENT_MANUALENROLLMENTAUDIT_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<StudentManualenrollmentauditRecord>> getKeys() { return Arrays.<UniqueKey<StudentManualenrollmentauditRecord>>asList(Keys.KEY_STUDENT_MANUALENROLLMENTAUDIT_PRIMARY); } /** * {@inheritDoc} */ @Override public List<ForeignKey<StudentManualenrollmentauditRecord, ?>> getReferences() { return Arrays.<ForeignKey<StudentManualenrollmentauditRecord, ?>>asList(Keys.STUDENT_MANUALENR_ENROLLED_BY_ID_729CECDC9F746E2_FK_AUTH_USER_ID, Keys.ST_ENROLLMENT_ID_60349E74284DF0D6_FK_STUDENT_COURSEENROLLMENT_ID); } /** * {@inheritDoc} */ @Override public StudentManualenrollmentaudit as(String alias) { return new StudentManualenrollmentaudit(alias, this); } /** * Rename this table */ public StudentManualenrollmentaudit rename(String name) { return new StudentManualenrollmentaudit(name, null); } }
package usc.cs310.ProEvento.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import usc.cs310.ProEvento.model.Invitation; import java.util.List; @Repository public class InvitationDao { @Autowired private SessionFactory sessionFactory; public boolean createInvitation(Invitation invitation) { Session session = sessionFactory.openSession(); try { session.beginTransaction(); session.saveOrUpdate(invitation); session.getTransaction().commit(); return true; } catch (Exception e) { e.printStackTrace(); if (session != null) { session.getTransaction().rollback(); } return false; } finally { if (session != null) { session.close(); } } } public Invitation selectInvitationsById(long invitationId) { try (Session session = sessionFactory.openSession()) { session.beginTransaction(); Invitation invitations = (Invitation) session.get(Invitation.class, invitationId); session.getTransaction().commit(); return invitations; } catch (Exception e) { e.printStackTrace(); return null; } } public List<Invitation> selectInvitationsByReceiverId(long receiverId) { try (Session session = sessionFactory.openSession()) { session.beginTransaction(); Query query = session.createQuery("SELECT i FROM Invitation i JOIN i.receivers r WHERE r.id = :receiverId"); query.setParameter("receiverId", receiverId); List<Invitation> invitations = (List<Invitation>) query.list(); session.getTransaction().commit(); return invitations; } catch (Exception e) { e.printStackTrace(); return null; } } public boolean updateInvitation(Invitation invitation) { return createInvitation(invitation); } public boolean deleteInvitation(Invitation invitation) { Session session = sessionFactory.openSession(); try { session.getTransaction().begin(); session.delete(invitation); session.getTransaction().commit(); return true; } catch (Exception e) { e.printStackTrace(); if (session != null) { session.getTransaction().rollback(); } return false; } finally { if (session != null) { session.close(); } } } }
package edu.udc.psw.modelo; public class FabricaFormas {// cria formas geometricas// public static FormaGeometrica fabricarFormaGeometrica(String forma) { int i = forma.indexOf(' '); String nome = forma.substring(0,i); FormaGeometrica formaGeometrica= null; if(nome.equals(Linha.class.getSimpleName())) formaGeometrica = new Linha(); else if(nome.equals(Retangulo.class.getSimpleName())) formaGeometrica = new Retangulo(); else if(nome.equals(Ponto2D.class.getSimpleName())) formaGeometrica = new Ponto2D(); System.out.println(formaGeometrica.getClass().getSimpleName() + " "+ formaGeometrica.toString()); return formaGeometrica; } public static Linha fabricarLinha(String linha) { int i = linha.indexOf(')'); Ponto2D p1 = fabricarPonto2D(linha.substring(0, i)); Ponto2D p2 = fabricarPonto2D(linha.substring(i+1)); Linha l = new Linha(p1,p2); //System.out.println(l.getClass().getSimpleName()+" "+ l.toString()); return l; } public static Ponto2D fabricarPonto2D(String ponto) { int i = ponto.indexOf(';'); double x = Double.parseDouble(ponto.substring(1,i).replace(',', '.')); double y = Double.parseDouble(ponto.substring(i+1, ponto.length()-1).replace(',', '.')); Ponto2D p = new Ponto2D(x,y); //System.out.println(ponto.getClass().getSimpleName()+" "+ p.toString()); return p; } public static Retangulo fabricarRertangulo(String Retangulo) { int i = Retangulo.indexOf(')'); Ponto2D p1 = fabricarPonto2D(Retangulo.substring(0, i)); Ponto2D p2 = fabricarPonto2D(Retangulo.substring(i+1)); Retangulo r = new Retangulo(); //System.out.println(r.getClass().getSimpleName()+" "+ r.toString()); return r; } }
package com.navarro.todo.core.service; import com.navarro.todo.core.dto.TodoDTO; public interface TodoService { Iterable<TodoDTO> list(); TodoDTO findById(Long id); TodoDTO createOrUpdate(TodoDTO todo); void delete(Long id); }
package com.lehvolk.xodus.web.vo; import java.io.Serializable; import java.util.List; import lombok.Getter; import lombok.Setter; /** * Light VO for entity presentation * @author Alexey Volkov * @since 12.11.2015 */ @Getter @Setter public class LightEntityVO extends BaseVO { private static final long serialVersionUID = 48319242411151430L; @Getter @Setter public static class BasePropertyVO implements Serializable { private static final long serialVersionUID = -4446983251527745550L; private String name; } @Getter @Setter public static class EntityPropertyVO extends BasePropertyVO { private static final long serialVersionUID = -4446983251527745550L; private String value; private EntityPropertyTypeVO type; } @Getter @Setter public static class EntityPropertyTypeVO implements Serializable { private static final long serialVersionUID = -4446983251527745550L; private boolean readonly; private String clazz; private String displayName; } private String label; private String type; private String typeId; private List<EntityPropertyVO> properties; }
package com.example.vplayer.fragment.adapter; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.PorterDuff; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.RadioButton; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import com.example.vplayer.R; import com.example.vplayer.dialog.RenameDialog; import com.example.vplayer.dialog.VideoDetailsDialog; import com.example.vplayer.fragment.utils.PreferencesUtility; import com.example.vplayer.fragment.utils.RxBus; import com.example.vplayer.fragment.utils.VideoPlayerUtils; import com.example.vplayer.model.Video; import java.util.List; import static android.view.View.GONE; public class OnMenuAdapter extends RecyclerView.Adapter<OnMenuAdapter.ViewHolder> { private List<String> mItems; private Integer[] mImages = {R.drawable.background_play, R.drawable.add_to_playlist, R.drawable.rename, R.drawable.ic_delete, R.drawable.is_share, R.drawable.ic_properties}; private Integer[] mImages1 = {R.drawable.background_play, R.drawable.add_to_playlist, R.drawable.rename, R.drawable.ic_delete, R.drawable.is_share}; private Integer[] mImages4 = {R.drawable.background_play, R.drawable.add_to_playlist, R.drawable.ic_delete, R.drawable.is_share}; private ItemListener itemListener; int selectedItem; Context context; Video video; int check; PreferencesUtility preferencesUtility; public OnMenuAdapter(Context context, List<String> items, ItemListener listener, Video video) { mItems = items; this.context = context; itemListener = listener; this.video = video; preferencesUtility = PreferencesUtility.getInstance(context); } public OnMenuAdapter(Context context,int check, List<String> items, ItemListener listener, Video video) { mItems = items; this.check = check; this.context = context; itemListener = listener; this.video = video; preferencesUtility = PreferencesUtility.getInstance(context); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item, parent, false)); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.text.setText(mItems.get(position)); if(check == -1 && position == 5){ holder.item_image.setImageResource(mImages1[position]); } if(check == -4 && position == 2){ holder.item_image.setImageResource(mImages4[position]); }else{ holder.item_image.setImageResource(mImages[position]); } holder.item_image.setColorFilter(ContextCompat.getColor(holder.item_image.getContext(), R.color.icon_color), PorterDuff.Mode.SRC_IN); // setOnPopupMenuListener(holder, position); } @Override public int getItemCount() { return mItems.size(); } /* private void setOnPopupMenuListener(ViewHolder itemHolder, final int position) { itemHolder.fragment_item.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final PopupMenu menu = new PopupMenu(context, v); menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (position) { case 2: RenameDialog.getInstance((Activity) context, video.getTitle(), video.getId(), video.getFullPath()) .show(((AppCompatActivity) context) .getSupportFragmentManager(), ""); break; case 4: VideoPlayerUtils.shareVideo(video.getId(), context); break; case 3: long[] videoId = {video.getId()}; VideoPlayerUtils.showDeleteDialog(context, video.getTitle(), videoId); break; case 5: VideoDetailsDialog.getInstance(video) .show(((AppCompatActivity) context) .getSupportFragmentManager(), ""); break; } return false; } }); } }); }*/ class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView text; String item; ImageView item_image; LinearLayout fragment_item; ViewHolder(View itemView) { super(itemView); text = itemView.findViewById(R.id.item_text); item_image = itemView.findViewById(R.id.item_image); fragment_item = itemView.findViewById(R.id.fragment_item); fragment_item.setOnClickListener(this); } @Override public void onClick(View v) { if (itemListener != null) { itemListener.onItemClick(getAdapterPosition()); } } } public interface ItemListener { void onItemClick(int item); } }
package jakebellotti.steamvrlauncher.model; import java.util.Optional; import javafx.scene.image.Image; /** * * @author Jake Bellotti * */ public class SteamApp { private final int id; private final int steamVRManifestFileID; private final Optional<Image> image; private final String appKey; private final String launchType; private final String name; private final String imagePath; private final String launchPath; private SteamAppSettings savedSettings; private SteamAppSettings currentSettings; public SteamApp(int id, int steamVRManifestFileID, final Optional<Image> image, String appKey, String launchType, String name, String imagePath, String launchPath, SteamAppSettings settings) { super(); this.id = id; this.steamVRManifestFileID = steamVRManifestFileID; this.image = image; this.appKey = appKey; this.launchType = launchType; this.name = name; this.imagePath = imagePath; this.launchPath = launchPath; this.savedSettings = settings; this.setCurrentSettings(settings.copy()); } public int getId() { return id; } public int getSteamVRManifestFileID() { return steamVRManifestFileID; } public Optional<Image> getImage() { return image; } public String getAppKey() { return appKey; } public String getLaunchType() { return launchType; } public String getName() { return name; } public String getImagePath() { return imagePath; } public String getLaunchPath() { return launchPath; } public final boolean isDirty() { final boolean rtmDirty = currentSettings.getRenderTargetMultiplier() != savedSettings.getRenderTargetMultiplier(); final boolean reprojectionDirty = currentSettings.isAllowReprojection() != savedSettings.isAllowReprojection(); return (rtmDirty || reprojectionDirty); } @Override public String toString() { return name; } public SteamAppSettings getSavedSettings() { return savedSettings; } public SteamAppSettings getCurrentSettings() { return currentSettings; } public void setCurrentSettings(SteamAppSettings currentSettings) { this.currentSettings = currentSettings; } public void setSavedSettings(SteamAppSettings savedSettings) { this.savedSettings = savedSettings; } }