id
stringlengths
36
36
text
stringlengths
1
1.25M
bfa82cb8-3873-4407-b031-a47db3aac2fa
public static long byte2Long(byte[] b) { ByteBuffer bb = ByteBuffer.wrap(b); return bb.getLong(); }
e3d93a9d-0b05-4b78-9e13-e5f718c4dc8b
public static byte[] int2Byte(int i) { ByteBuffer boeuf = ByteBuffer.allocate(4); boeuf.order(ByteOrder.BIG_ENDIAN); boeuf.putInt(i); return boeuf.array(); }
217aca6b-5e33-4bff-a500-770c746ea3e6
public static int byte2int(byte[] b) { ByteBuffer bb = ByteBuffer.wrap(b); return bb.getInt(); }
2f5b3d10-723c-4abb-9e17-0417003cb657
public static byte[] buildMessage(byte code, int... datas) { byte[] message = new byte[1 + datas.length * 4]; message[0] = code; int indice = 1; for (int i = 0; i < datas.length; i++) { byte[] data = Toolbox.int2Byte(datas[i]); for (int j = 0; j < data.length; j++) { message[indice++] = data[j]; } } return message; }
800596cd-c6b5-4ffc-9ccc-1bbb8e5eca49
public static int[] buildData(DatagramPacket packet) { return buildData(packet.getData(), packet.getLength(),0); }
d0fa0d43-b57c-45bb-ad71-647dec369891
public static int[] buildData(byte[] message, int length,int offset) { // Attention: Ne pas utiliser message.length, // renvoie la taille du buffer et pas du contenu if (length <= 1) throw new IllegalArgumentException(); // le code du message se trouve dans message[0]; // Le reste des donnees sont des entiers.. // Si pas de donnees, renvoie un tableau vide (eviter le null) if ((length - 1) % 4 != 0) { return new int[0]; } // Si des donnees int nbInt = (length - 1) / 4; int data[] = new int[nbInt]; if (message.length > 1) { for (int index = 0; index < nbInt; index++) { byte temp[] = new byte[4]; temp[0] = message[offset + 1 + index * 4]; temp[1] = message[offset + 2 + index * 4]; temp[2] = message[offset + 3 + index * 4]; temp[3] = message[offset + 4 + index * 4]; data[index] = Toolbox.byte2int(temp); } } return data; }
d5305c1d-8332-4dbf-a46f-2bb3cd81dfff
public static Byte getDataCode(DatagramPacket p) { if (p == null || p.getLength() == 0) return null; return p.getData()[0]; }
7ad09d85-2453-4bf2-9b16-b5883e8c6de2
public static byte[] concat(byte[] d1, byte[] d2) { byte[] data = new byte[d1.length + d2.length]; for (int i = 0; i < d1.length; i++) { data[i] = d1[i]; } for (int i = 0; i < d2.length; i++) { data[i + d2.length] = d2[i]; } return data; }
92136802-0141-4a66-9833-e4fba919ea26
public Lamport(Bank bank) throws SocketException { this.bank = bank; this.port = Config.bank2bankLamportPort[bank.getId()]; System.out.println("La banque " + bank.getId() + " ecoute sur le port " + port); socket = new DatagramSocket(port); // Initialise le tableau d'etat state = new LamportState[Config.banksAddresses.length]; for (int i = 0; i < state.length; i++) state[i] = new LamportState(); new Thread(this).start(); }
a925537f-3ab7-40c2-878c-5d5b3efc126d
private boolean localAccesGranted() { // Il peut si etat[bankid]=requete // et que son estampille est la plus ancienne ! if (state[bank.getId()].type != LamportMessages.REQUEST) return false; int myTimeStamp = state[bank.getId()].timestamp; for (int i = 0; i < state.length; i++) { if (myTimeStamp > state[i].timestamp) { return false; } else if (myTimeStamp == state[i].timestamp && i != bank.getId()) { if (bank.getId() > i) return false; } } return true; }
448d0231-f9b8-41ed-94f8-a472bd6ac433
public void lock() throws IOException { System.out.println("Lamport.lock()"); // Mise a jour de l'estampille // FIXME Synchronise a mettre localTimestamp++; // Envoi d'une requete state[bank.getId()].set(LamportMessages.REQUEST, localTimestamp); sendToAllOthersBank(state[bank.getId()].toByte(this.bank.getId())); // Indique si l'on peut avoir le mutex // Si on a pas le mutex, on est en attente ! synchronized (this) { hasMutex = localAccesGranted(); while (!hasMutex) { try { if (DEBUG) { System.out.println("Wait() sur la banque " + bank.getId()); } wait(); } catch (InterruptedException e) { e.printStackTrace(); } hasMutex = localAccesGranted(); } } }
d9eeeb2c-8c26-4dbc-9e34-a2e63a9241e6
public void accountCreated(int account, int money) throws IOException { // Infos de creation de compte byte[] temp = Toolbox.buildMessage( LamportMessages.NEW_ACCOUNT.getCode(), account, money); // Envoi sendToAllOthersBank(temp); }
5d55eaf8-dfaf-413f-b9dd-39b036bb1a1d
public void unlock(LamportUnlockMessage unlockType, int... data) throws IOException { System.out.println("Lamport.unlock()"); // Construction du message a envoyer state[bank.getId()].set(LamportMessages.RELEASE, localTimestamp); byte[] messageData = state[bank.getId()].toByte(bank.getId()); // Ajout des infos de liberation byte[] temp = Toolbox.buildMessage(unlockType.getCode(), data); // Envoi sendToAllOthersBank(Toolbox.concat(messageData, temp)); synchronized (this) { hasMutex = false; } }
22cbfe6c-26cc-4a7a-b0a7-faad67b8aeb1
public void sendToAllOthersBank(byte[] data) throws IOException { for (int i = 0; i < state.length; i++) { if (i != bank.getId()) { send(i, data); } } }
6c542454-34cf-4004-8557-a10741ef4bce
public void send(int bankId, byte[] data) throws IOException { // Construction de l'adresse et du datagramme int port = Config.bank2bankLamportPort[bankId]; InetAddress host = InetAddress.getByName(Config.banksAddresses[bankId]); DatagramPacket packet = new DatagramPacket(data, data.length, host, port); // Envoi socket.send(packet); }
4c8b3f24-c935-46b8-adae-a97860a58d0a
public void run() { byte[] buffer = new byte[Config.bufferSize]; DatagramPacket data = new DatagramPacket(buffer, buffer.length); while (true) { try { // 1. Reception d'un message socket.receive(data); // 2. Regarde si une autre banque replique un nouveau compte LamportMessages type = LamportMessages .fromCode(data.getData()[0]); if (type == LamportMessages.NEW_ACCOUNT) { // 2b. Si oui, on l'ajout a la banque int[] newAccountData = Toolbox.buildData(data.getData(), data.getLength(), 0); bank.handleOnCreate(newAccountData[0], newAccountData[1]); } else { // 3. Sinon on a un message lamport normal LamportState state = LamportState.fromByte(data.getData(), data.getLength()); acceptReceive(state, data); } } catch (IOException e) { e.printStackTrace(); } } }
68da157d-8c67-4cca-a2eb-b1844d4bc1d1
private void acceptReceive(LamportState state, DatagramPacket data) throws IOException { int remoteBankId = state.remoteBankId; // 1. Met a jour l'estampille // FIXME Synchronized localTimestamp = Math.max(localTimestamp, state.timestamp) + 1; // 2. Effectue les actions suivant le type de message recu switch (state.type) { case NEW_ACCOUNT: // Deja traite car pas un message lamport standard break; case REQUEST: // Mise a jour de la table locale this.state[remoteBankId].set(LamportMessages.REQUEST, state.timestamp); // Envoi du recu LamportState data2send = new LamportState(LamportMessages.RECEIPT, localTimestamp); send(remoteBankId, data2send.toByte(bank.getId())); break; case RELEASE: // Mise a jour de la table locale this.state[remoteBankId].set(LamportMessages.RELEASE, state.timestamp); // Recupe des donnees en plus dans le message de release if (state.type == LamportMessages.RELEASE && data.getLength() >= 9){ // Construction des donnees byte code = data.getData()[9]; // Code int[] releaseData = Toolbox.buildData(data.getData(), data.getLength() - 9, 9); // Donnee repliquee // Conversion en enum LamportUnlockMessage lum = LamportUnlockMessage.fromCode(code); // Mise a jour de la banque suivant les donnees recues switch (lum) { case DELETE_ACCOUNT: bank.handleOnDelete(releaseData[0]); break; case UPDATE_MONEY: bank.handleOnUpdate(releaseData[0], releaseData[1]); break; default: System.err .println("LamportRelease: non implementee"); break; } } break; case RECEIPT: // Met a jour si on avait pas de requete dans le tableau if (this.state[remoteBankId].type != LamportMessages.REQUEST) { this.state[remoteBankId].set(LamportMessages.RECEIPT, state.timestamp); } break; } // Indique si l'on peut avoir le mutex synchronized (this) { hasMutex = (this.state[bank.getId()].type == LamportMessages.REQUEST) && localAccesGranted(); if (DEBUG) { System.out.println("Lamport.acceptReceive()"); } if (hasMutex) { if (DEBUG) System.out .println("Notify() sur la banque " + bank.getId()); notify(); } } }
cb0363b6-a606-40fb-867e-0e2c34139b9d
public Teller(int bankId) throws UnknownHostException, SocketException { if (bankId < 0 || bankId > Config.banksAddresses.length - 1) throw new IllegalArgumentException( "No de banque invalide pour le guichetier !"); port = Config.banks2ClientPorts[bankId]; host = InetAddress.getByName(Config.banksAddresses[bankId]); socket = new DatagramSocket(); }
164651c9-9803-4401-9183-587c8cfa5963
private void sendPacket(byte[] tampon) throws IOException { DatagramPacket packet = new DatagramPacket(tampon, tampon.length, host, port); socket.send(packet); }
bb41ac39-e64e-4044-8181-4bfed371ec30
private DatagramPacket receivePacket() throws IOException { byte[] tampon = new byte[Config.bufferSize]; DatagramPacket packet = new DatagramPacket(tampon, tampon.length); //System.out.println("Attente de la reponse de la banque"); socket.receive(packet); return packet; }
e37597be-59fa-45fb-a226-dd30f5bbdaf4
public int addAccount(int money) { try { // Envoi de la requete sendPacket(Toolbox.buildMessage(Menu.ADD_ACCOUNT.getCode(), money)); // Reception de la reponse DatagramPacket p = receivePacket(); ErrorServerClient code = ErrorServerClient.fromCode(p.getData()[0]); // Si aucune erreur if (code == ErrorServerClient.OK) { // Renvoie le numero de compte int[] data = Toolbox.buildData(p); return data[0]; } else { return -1; } } catch (IOException e) { e.printStackTrace(); } return -1; }
b39faf47-3e1d-40da-8d06-c907858a86cb
public ErrorServerClient deleteAccount(int account) { try { // Envoi de la requete sendPacket(Toolbox.buildMessage(Menu.DELETE_ACCOUNT.getCode(), account)); // Reception de la reponse DatagramPacket p = receivePacket(); return ErrorServerClient.fromCode(p.getData()[0]); } catch (IOException e) { e.printStackTrace(); } return ErrorServerClient.AUTRE; }
26b1143d-99c5-44c4-9128-7bd3d256114a
public ErrorServerClient addMoney(int account, int money) { try { // Envoi de la requete sendPacket(Toolbox.buildMessage(Menu.ADD_MONEY.getCode(), account, money)); // Reception de la reponse DatagramPacket p = receivePacket(); return ErrorServerClient.fromCode(p.getData()[0]); } catch (IOException e) { e.printStackTrace(); } return ErrorServerClient.AUTRE; }
e450aa56-9697-4f95-bdec-87ea738f69b7
public ErrorServerClient takeMoney(int account, int money) { try { // Envoi de la requete sendPacket(Toolbox.buildMessage(Menu.TAKE_MONEY.getCode(), account, money)); // Reception de la reponse DatagramPacket p = receivePacket(); return ErrorServerClient.fromCode(p.getData()[0]); } catch (IOException e) { e.printStackTrace(); } return ErrorServerClient.AUTRE; }
de08ca61-c5cf-443b-97ad-d25eeb903970
public int getBalance(int account) { try { // Envoi de la requete sendPacket(Toolbox.buildMessage(Menu.GET_BALANCE.getCode(), account)); // Reception de la reponse DatagramPacket p = receivePacket(); ErrorServerClient code = ErrorServerClient.fromCode(p.getData()[0]); if (code == ErrorServerClient.OK) { return Toolbox.buildData(p)[0]; } } catch (IOException e) { e.printStackTrace(); } return -1; }
1253f4a9-85d7-429c-b174-3401b681fbb5
public byte getCode(){ return (byte)this.ordinal(); }
75a0004a-f979-47da-886e-eff95921b9e8
public static ErrorServerClient fromCode(byte code){ return ErrorServerClient.values()[(int)code]; }
d36c1b7d-dcd6-4f69-8a2c-1b56eb5383ea
Menu(String text) { this.text = text; }
bc180a75-030e-4ccc-b13e-7eebdcf03e9e
public String toString() { return text; }
ebe2c16b-d3e0-4652-99c7-355752f9f2f1
public byte getCode(){ return (byte)this.ordinal(); }
aedb3bb7-82f8-4da9-806c-64613f65f165
public static Menu fromCode(byte code){ return Menu.values()[(int)code]; }
36cf2ba9-289d-46c4-b300-8f1d1f5a7e35
StatsDType(String statType) { this.statType = statType; }
ff59589a-f52e-488f-a93e-2730b887e552
public String getShortString() { return statType; }
5349ee78-0b1c-4e26-bf58-71e063b3afd9
void increment(String key);
aaf18d77-c521-4e30-a3a3-59c478cc345f
void count(String key, int delta);
39a2d062-779d-46de-929c-3b30f12fedb2
void count(String key, Object delta, double rate);
a8247bdc-3f3b-4395-a4ba-2b7f20a6165a
void gauge(String key, double value);
545913df-5079-49eb-a234-c781a625463b
void gauge(String key, long value);
627a50b6-7293-4dcb-b001-840dac407b50
void time(String key, int timeInMs);
b726b0d5-a1e2-474a-bf01-699062c4f382
public StatsDMetric(String key, StatsDType type, Object value) { this(key, type, value, null); }
d7e1e0f5-4507-48ac-87ed-5956ee97cf4c
public StatsDMetric(String key, StatsDType type, Object value, Double rate) { this.key = key; this.type = type; this.value = value; this.rate = rate; }
bad19413-6378-4ed4-afdf-60119529a52e
public String getKey() { return key; }
28c3a878-7022-4493-a05f-f04dded960fa
public StatsDType getType() { return type; }
206ae9e1-b262-4684-a3ae-5df7b6e4d9ef
public Object getValue() { return value; }
ea2027da-13de-4fae-be25-7b85051c112f
public Double getRate() { return rate; }
a2ffe0be-2bda-457b-99c8-3d261b441f72
@Override public void increment(String key) { // noop }
2bbc7649-ade8-4df3-8e08-846c7e903f32
@Override public void count(String key, int delta) { // noop }
885b8b11-7c5a-4326-ac93-ed4e2f84dad7
@Override public void count(String key, Object delta, double rate) { // noop }
67d8a9bf-3678-4e31-a45b-ebe17cd4a577
@Override public void gauge(String key, double value) { // noop }
bb0090cb-3de2-4cec-8639-4ceadeb8b726
@Override public void gauge(String key, long value) { // noop }
20897125-9d8b-4287-843f-89015953edaa
@Override public void time(String key, int timeInMs) { // noop }
9f3aebcc-a61d-4460-be05-7f98ab49b5f3
public StatsDClientImpl(String host, int port) { this(host, port, Executors.newSingleThreadExecutor(new ThreadFactory() { private ThreadFactory delegate = Executors.defaultThreadFactory(); @Override public Thread newThread(Runnable r) { Thread thread = delegate.newThread(r); thread.setName("Statsd flusher"); return thread; } })); }
9db384c4-6693-43f6-b425-7d4e80842869
@Override public Thread newThread(Runnable r) { Thread thread = delegate.newThread(r); thread.setName("Statsd flusher"); return thread; }
8c59724b-6933-4406-9d6b-7602681098ee
public StatsDClientImpl(String hostname, int port, ExecutorService service) { try { channel = DatagramChannel.open(); channel.connect(new InetSocketAddress(hostname, port)); } catch( Exception e ) { throw new RuntimeException("Failed to start StatSD client", e); } service.submit(new Runnable() { @Override public void run() { DecimalFormat format = new DecimalFormat(RATE_FORMAT); ByteBuffer buffer = ByteBuffer.allocate(1400); while( true ) { try { StatsDMetric metric = queue.poll(); if( metric == null ) { if( buffer.position() > 0 ) { flush(buffer); } metric = queue.take(); } byte[] bytes = convert(format, metric).getBytes(UTF_8); if( buffer.remaining() < bytes.length ) { flush(buffer); } buffer.put(bytes); } catch( InterruptedException e ) { // nothing } } } private void flush(ByteBuffer buffer) { buffer.flip(); try { channel.write(buffer); } catch( IOException e ) { LOGGER.warn("Failed to send statsd packet", e); } buffer.clear(); } }); }
c7763b8b-d325-48c6-9bcf-6055cc44e734
@Override public void run() { DecimalFormat format = new DecimalFormat(RATE_FORMAT); ByteBuffer buffer = ByteBuffer.allocate(1400); while( true ) { try { StatsDMetric metric = queue.poll(); if( metric == null ) { if( buffer.position() > 0 ) { flush(buffer); } metric = queue.take(); } byte[] bytes = convert(format, metric).getBytes(UTF_8); if( buffer.remaining() < bytes.length ) { flush(buffer); } buffer.put(bytes); } catch( InterruptedException e ) { // nothing } } }
40e87198-770e-4e59-b919-f8724cfd3889
private void flush(ByteBuffer buffer) { buffer.flip(); try { channel.write(buffer); } catch( IOException e ) { LOGGER.warn("Failed to send statsd packet", e); } buffer.clear(); }
347f31ff-6238-4911-a710-bb8b8fc2a1a6
public static String convert(StatsDMetric metric) { return convert(new DecimalFormat(RATE_FORMAT), metric); }
2e85ab13-f6ef-4ce7-a8d1-a00d63cf124e
static String convert(DecimalFormat format, StatsDMetric metric) { String rateString = ""; Double rate = metric.getRate(); if( rate != null ) { rateString = format.format(rate); } return String.format(Locale.ENGLISH, "%s:%s|%s%s\n", metric.getKey(), metric.getValue(), metric.getType() .getShortString(), rateString); }
958df02d-b813-460f-b646-c9ab4503de4b
@Override public void increment(String key) { queue.add(new StatsDMetric(key, StatsDType.COUNTER, 1)); }
ab45bae8-368b-4899-a980-b3b6bd2807f1
@Override public void count(String key, int delta) { queue.add(new StatsDMetric(key, StatsDType.COUNTER, delta)); }
5ceaaf21-decf-4643-b5cb-ebc85432823a
@Override public void gauge(String key, double value) { queue.add(new StatsDMetric(key, StatsDType.GAUGE, value)); }
4a212dac-9ea0-4737-848b-799f9c307d75
@Override public void time(String key, int timeInMs) { queue.add(new StatsDMetric(key, StatsDType.TIMER, timeInMs)); }
c4668a70-e63e-474a-83de-e10e2d7e155d
@Override public void count(String key, Object delta, double rate) { queue.add(new StatsDMetric(key, StatsDType.COUNTER, delta, rate)); }
e8e9cbc3-6c1f-4c2d-b2e8-ca2b9be88ba4
@Override public void gauge(String key, long value) { queue.add(new StatsDMetric(key, StatsDType.GAUGE, value)); }
e3d5616e-a7a7-4a8d-b037-a7c32749ed6c
public ConvertTest(String testName) { super(testName); }
96e9d117-d2e3-4e86-adba-5c2768c31847
public static Test suite() { return new TestSuite(ConvertTest.class); }
3367bb64-6bde-4da0-8ad1-6941c616ebeb
public void testConversions() { assertEquals("test:1|c\n", StatsDClientImpl.convert(new StatsDMetric("test", StatsDType.COUNTER, 1))); assertEquals("test:2|c|@0.1\n", StatsDClientImpl.convert(new StatsDMetric("test", StatsDType.COUNTER, 2, 0.1))); assertEquals("test:2|c|@1.01\n", StatsDClientImpl.convert(new StatsDMetric("test", StatsDType.COUNTER, 2, 1.01))); assertEquals("test:2|g\n", StatsDClientImpl.convert(new StatsDMetric("test", StatsDType.GAUGE, 2))); assertEquals("test:3.0|g\n", StatsDClientImpl.convert(new StatsDMetric("test", StatsDType.GAUGE, 3.0))); assertEquals("test:123|ms\n", StatsDClientImpl.convert(new StatsDMetric("test", StatsDType.TIMER, 123))); }
72c1cecc-0025-48c9-82d2-0890930b6fce
public MySQLDatabase(FigAdmin instance) { plugin = instance; }
faf9b8aa-0a70-4072-9e35-52e6e883f9b2
public Connection getSQLConnection(String mysqlDatabase) { FileConfiguration Config = plugin.getConfig(); String mysqlUser = Config.getString("mysql-user", "root"); String mysqlPassword = Config.getString("mysql-password", "root"); try { return DriverManager.getConnection(mysqlDatabase + "?autoReconnect=true&user=" + mysqlUser + "&password=" + mysqlPassword); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "Unable to retreive connection", ex); } return null; }
33f648c9-7ad5-42f2-9583-2661621c5e09
public Connection getSQLConnection() { String mysqlDatabase = plugin.getConfig().getString("mysql-database", "jdbc:mysql://localhost:3306/minecraft"); return getSQLConnection(mysqlDatabase); }
8d481089-c804-4e57-8ede-4a2be4f87294
public boolean initialize(FigAdmin plugin) { this.plugin = plugin; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String table = plugin.getConfig().getString("mysql-table"); try { conn = getSQLConnection(); DatabaseMetaData dbm = conn.getMetaData(); // Table create if not it exists if (!dbm.getTables(null, null, table, null).next()) { getLogger().log(Level.INFO, "[FigAdmin] Creating table " + table + "."); ps = conn.prepareStatement("CREATE TABLE `" + table + "` ( \n" + " `name` varchar(32) NOT NULL, \n" + " `reason` text NOT NULL, \n " + " `admin` varchar(32) NOT NULL, \n" + " `time` bigint(20) NOT NULL, \n " + " `temptime` bigint(20) NOT NULL DEFAULT '0', \n" + " `type` int(11) NOT NULL DEFAULT '0', \n" + " `id` int(11) NOT NULL AUTO_INCREMENT, \n" + " `ip` varchar(16) DEFAULT NULL, \n" + " PRIMARY KEY (`id`) USING BTREE \n" + ") ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ROW_FORMAT=DYNAMIC;"); ps.execute(); if (!dbm.getTables(null, null, table, null).next()) throw new SQLException("Table " + table + " not found; tired to create and failed"); } // Clean up old temp bans ps = conn.prepareStatement("DELETE FROM " + table + " WHERE (type = 0 OR type = 1) AND (temptime > 0) AND (temptime < ?)"); ps.setLong(1, System.currentTimeMillis() / 1000); ps.execute(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); return false; } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); if (rs != null) rs.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } return true; }
eefe558b-2d86-42a9-ae76-1cf753491958
public String getAddress(String pName) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String mysqlTable = plugin.getConfig().getString("mysql-table"); try { conn = getSQLConnection(); ps = conn.prepareStatement("SELECT `ip` FROM `" + mysqlTable + "` WHERE name = ?"); ps.setString(1, pName); rs = ps.executeQuery(); while (rs.next()) { String ip = rs.getString("ip"); return ip; } } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); if (rs != null) rs.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } return null; }
22cb3a12-effb-4224-aafa-e30ea7259ba0
public boolean removeFromBanlist(String player) { String mysqlTable = plugin.getConfig().getString("mysql-table"); Connection conn = null; PreparedStatement ps = null; try { conn = getSQLConnection(); ps = conn.prepareStatement("DELETE FROM " + mysqlTable + " WHERE name = ? AND (type = 0 or type = 1) ORDER BY time DESC"); ps.setString(1, player); ps.executeUpdate(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); return false; } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } return true; }
4bfe3741-a456-4791-8ec7-499a7198148c
public void addPlayer(EditBan e) { String mysqlTable = plugin.getConfig().getString("mysql-table"); Connection conn = null; PreparedStatement ps = null; try { conn = getSQLConnection(); ps = conn.prepareStatement("INSERT INTO `" + mysqlTable + "` (name,reason,admin,temptime,type,time) VALUES(?,?,?,?,?,?)"); ps.setString(1, e.name); ps.setString(2, e.reason); ps.setString(3, e.admin); if (e.endTime < 1) { ps.setLong(4, 0); } else ps.setLong(4, e.endTime); ps.setInt(5, e.type); ps.setLong(6, System.currentTimeMillis() / 1000); ps.executeUpdate(); // Update banedit ID PreparedStatement getID = conn.prepareStatement("SELECT LAST_INSERT_ID()"); ResultSet rsID = getID.executeQuery(); rsID.next(); e.id = rsID.getInt(1); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } }
a3883c7b-bfa6-4038-8093-498a599923fb
public String getBanReason(String player) { Connection conn = getSQLConnection(); PreparedStatement ps = null; ResultSet rs = null; String mysqlTable = plugin.getConfig().getString("mysql-table"); try { ps = conn.prepareStatement("SELECT * FROM `" + mysqlTable + "` WHERE name = ? ORDER BY id DESC LIMIT 1"); ps.setString(1, player); rs = ps.executeQuery(); while (rs.next()) { String reason = rs.getString("reason"); return reason; } } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } return null; }
8861c5d8-ee55-4ece-89af-a1c446fe364c
public void updateAddress(String p, String ip) { Connection conn = null; PreparedStatement ps = null; String mysqlTable = plugin.getConfig().getString("mysql-table"); try { conn = getSQLConnection(); ps = conn.prepareStatement("UPDATE `" + mysqlTable + "` SET ip = ? WHERE name = ?"); ps.setString(1, ip); ps.setString(2, p); ps.executeUpdate(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } }
1e7753b8-3263-42e0-92e0-388ab2b811ba
public ArrayList<EditBan> listRecords(String name, boolean exact) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String mysqlTable = plugin.getConfig().getString("mysql-table"); try { conn = getSQLConnection(); ps = conn.prepareStatement("SELECT * FROM `" + mysqlTable + "` WHERE name " + ((exact) ? "= ?" : "LIKE ?") + " ORDER BY time DESC LIMIT 10"); if (exact) { ps.setString(1, name); } else { ps.setString(1, "'%" + name + "%'"); } rs = ps.executeQuery(); ArrayList<EditBan> bans = new ArrayList<EditBan>(); while (rs.next()) { bans.add(getEditBan(rs)); } return bans; } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); if (rs != null) rs.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } return null; }
1b697783-525b-4c3c-a3da-2639f59f5dac
protected EditBan loadFullRecord(String pName) { return loadFullRecord(pName, -1); }
f6617ebc-47a5-45df-a159-ab326fed49e9
protected EditBan loadFullRecord(int id) { return loadFullRecord(null, id); }
a05510ee-4f11-432b-905c-90e6e77d9e10
private EditBan loadFullRecord(String pName, int id) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String mysqlTable = plugin.getConfig().getString("mysql-table"); try { String statement = "SELECT * FROM " + mysqlTable + " WHERE name = ? ORDER BY time DESC LIMIT 1"; if (pName == null) { statement = "SELECT * FROM " + mysqlTable + " WHERE id = ?"; } conn = getSQLConnection(); ps = conn.prepareStatement(statement); if (pName == null) { ps.setInt(1, id); } else { ps.setString(1, pName); } rs = ps.executeQuery(); while (rs.next()) { return new EditBan(rs.getInt("id"), rs.getString("name"), rs.getString("reason"), rs.getString("admin"), rs.getLong("time"), rs.getLong("temptime"), rs.getInt("type"), rs .getString("ip")); } } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); if (rs != null) rs.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } return null; }
858eee0c-ecbd-4d7a-ae4d-cdb71ab9c35f
public boolean saveFullRecord(EditBan ban) { String mysqlTable = plugin.getConfig().getString("mysql-table"); Connection conn = null; PreparedStatement ps = null; boolean success = false; try { conn = getSQLConnection(); ps = conn.prepareStatement("UPDATE " + mysqlTable + " SET name = ?, reason = ?, admin = ?, time = ?, temptime = ?, type = ? WHERE id = ? LIMIT 1"); ps.setLong(5, ban.endTime); ps.setString(1, ban.name); ps.setString(2, ban.reason); ps.setString(3, ban.admin); ps.setLong(5, ban.time); ps.setLong(6, ban.type); ps.setInt(7, ban.id); success = ps.executeUpdate() > 0; } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } return success; }
8118ddcd-5b89-4a77-a356-a62bcdb754b6
@Override public ArrayList<EditBan> getBannedPlayers() { ArrayList<EditBan> list = new ArrayList<EditBan>(); Connection conn = getSQLConnection(); String mysqlTable = plugin.getConfig().getString("mysql-table"); if (conn == null) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Could not establish SQL connection. Disabling FigAdmin"); plugin.getServer().getPluginManager().disablePlugin(plugin); return list; } else { PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.prepareStatement("SELECT * FROM " + mysqlTable + " WHERE (type = 0 OR type = 1) AND (temptime > ? OR temptime = 0)"); ps.setLong(1, System.currentTimeMillis() / 1000); rs = ps.executeQuery(); while (rs.next()) { EditBan e = getEditBan(rs); list.add(e); } } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); } finally { try { if (ps != null) ps.close(); if (rs != null) rs.close(); if (conn != null) conn.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } try { conn.close(); FigAdmin.log.log(Level.INFO, "[FigAdmin] Initialized db connection"); } catch (SQLException e) { e.printStackTrace(); plugin.getServer().getPluginManager().disablePlugin(plugin); } } return list; }
8dbce9cd-8d8a-43ee-89ad-1abbc6c0abac
private EditBan getEditBan(ResultSet rs) throws SQLException { return new EditBan(rs.getInt("id"), rs.getString("name"), rs.getString("reason"), rs.getString("admin"), rs .getLong("time"), rs.getLong("temptime"), rs.getInt("type"), rs.getString("ip")); }
095f6e67-40e7-459a-b869-29c3f566a414
@Override protected boolean deleteFullRecord(int id) { String mysqlTable = plugin.getConfig().getString("mysql-table"); Connection conn = null; PreparedStatement ps = null; boolean success = false; try { conn = getSQLConnection(); ps = conn.prepareStatement("DELETE FROM " + mysqlTable + " WHERE id = ? ORDER BY time DESC"); ps.setInt(1, id); ps.executeUpdate(); success = ps.getUpdateCount() > 0; } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); return false; } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } return success; }
0990deab-648b-4355-8c6b-01258ff10ab3
protected String importFromKiwi(String table, String database) { if (database == null) { database = plugin.getConfig().getString("mysql-database"); } else { database = "jdbc:mysql://localhost:3306/" + database; } Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = getSQLConnection(database); if (conn == null || !conn.isValid(5)) { return "Can't connect to database `" + database + "`; does it exist?"; } DatabaseMetaData dbm = conn.getMetaData(); if (!dbm.getTables(null, null, table, null).next()) { return "Table `" + table + "` doesn't exit!"; } ps = conn.prepareStatement("SELECT * FROM `" + table + "`"); rs = ps.executeQuery(); while (rs.next()) { String name = rs.getString("name"); System.out.println("Added banned player: " + name); long temptime = 0; if (rs.getLong("temptime") > 0) { temptime = rs.getDate("temptime").getTime() / 1000; } EditBan e = new EditBan(0, name, rs.getString("reason"), rs.getString("admin"), rs.getLong("time") / 1000, temptime, EditBan.BAN, null); addPlayer(e); plugin.bannedPlayers.add(e); } return "Done!"; } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin][KiwiImport] Couldn't execute MySQL statement: ", ex); return "Error!"; } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); if (rs != null) rs.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } }
acb6fcfa-58f9-464a-9c91-48002e66ee92
@Override public int getWarnCount(String player) { int warns = 0; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String mysqlTable = plugin.getConfig().getString("mysql-table"); try { conn = getSQLConnection(); ps = conn.prepareStatement("SELECT * FROM `" + mysqlTable + "` WHERE name = ? AND type = 2"); ps.setString(1, player); rs = ps.executeQuery(); while (rs.next()) { warns++; } } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); if (rs != null) rs.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } return warns; }
dfe75a7a-a63e-4ffb-9630-ac4be1b2c450
@Override public int clearWarnings(String player) { String mysqlTable = plugin.getConfig().getString("mysql-table"); Connection conn = null; PreparedStatement ps = null; int warns = 0; try { conn = getSQLConnection(); ps = conn.prepareStatement("DELETE FROM " + mysqlTable + " WHERE name = ? AND type = 2"); ps.setString(1, player); ps.executeUpdate(); warns = ps.getUpdateCount(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Couldn't execute MySQL statement: ", ex); } finally { try { if (ps != null) ps.close(); if (conn != null) conn.close(); } catch (SQLException ex) { FigAdmin.log.log(Level.SEVERE, "[FigAdmin] Failed to close MySQL connection: ", ex); } } return warns; }
2e4e71d7-8afc-4c3b-9fc1-1f3b6c7ef793
EditCommand(FigAdmin plugin) { this.plugin = plugin; }
056aca49-7aa3-439c-bd7b-dbc5b12d9f5c
private static String banType(int num) { switch (num) { case 0: return "Ban "; case 1: return "IP-Ban"; case 2: return "Warn "; default: return "?"; } }
b406131c-61aa-4ee2-a08a-f5ed10a10845
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { try { if (!plugin.hasPermission(sender, "figadmin.editban")) { sender.sendMessage(plugin.formatMessage(plugin.getConfig().getString("messages.noPermission"))); return true; } if (args.length < 1) return false; if (args[0].equalsIgnoreCase("list")) { return list(sender, args); } if (args[0].equalsIgnoreCase("load")) { return load(sender, args); } if (args[0].equalsIgnoreCase("id")) { return id(sender, args); } if (args[0].equalsIgnoreCase("delete")) { return delete(sender, args); } if (args[0].equalsIgnoreCase("search")) { return search(sender, args); } if (args[0].equalsIgnoreCase("save")) { if (ban == null) { sender.sendMessage(ChatColor.RED + "You aren't editing a ban"); return true; } return save(sender, args); } if (args[0].equalsIgnoreCase("cancel")) { if (ban == null) { sender.sendMessage(ChatColor.RED + "You aren't editing a ban"); return true; } return cancel(sender, args); } if (args[0].equalsIgnoreCase("show") || args[0].equalsIgnoreCase("view")) { if (ban == null) { sender.sendMessage(ChatColor.RED + "You aren't editing a ban"); return true; } return view(sender, args); } if (args[0].equalsIgnoreCase("reason")) { if (ban == null) { sender.sendMessage(ChatColor.RED + "You aren't editing a ban"); return true; } return reason(sender, args); } if (args[0].equalsIgnoreCase("time")) { if (ban == null) { sender.sendMessage(ChatColor.RED + "You aren't editing a ban"); return true; } return time(sender, args); } } catch (Exception exc) { System.out.println("[FigAdmin] Error: EditCommand"); exc.printStackTrace(); } return false; }
c0b5603c-3123-4257-8959-06cdde5db64d
public static void showBanInfo(EditBan eb, CommandSender sender) { DateFormat shortTime = DateFormat.getDateTimeInstance(); sender.sendMessage(ChatColor.AQUA + banType(eb.type)); sender.sendMessage(ChatColor.GOLD + " | " + ChatColor.WHITE + eb.name + ChatColor.YELLOW + " was banned by " + ChatColor.WHITE + eb.admin + ChatColor.YELLOW); sender.sendMessage(ChatColor.GOLD + " | at " + shortTime.format((new Date(eb.time * 1000)))); if (eb.endTime > 0) sender.sendMessage(ChatColor.GOLD + " | " + ChatColor.YELLOW + "Will be unbanned at " + shortTime.format((new Date(eb.endTime * 1000)))); sender.sendMessage(ChatColor.GOLD + " | " + ChatColor.YELLOW + "Reason: " + ChatColor.GRAY + eb.reason); }
a2c1aa40-1fc2-4c90-9088-62bdda4c7c14
private boolean list(CommandSender sender, String[] args) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "Usage: list <player>"); return true; } if (!FigAdmin.validName(args[1])) { sender.sendMessage(plugin.formatMessage(plugin.getConfig().getString("messages.badPlayerName", "bad player name"))); return true; } List<EditBan> bans = plugin.db.listRecords(args[1], true); if (bans.isEmpty()) { sender.sendMessage(ChatColor.RED + "No records"); return true; } sender.sendMessage(ChatColor.GOLD + "Found " + bans.size() + " records for user " + bans.get(0).name + ":"); for (EditBan ban : bans) { sender.sendMessage(ChatColor.AQUA + banType(ban.type) + ChatColor.YELLOW + ban.id + ": " + ChatColor.GREEN + ban.reason + ChatColor.YELLOW + " by " + ban.admin); } return true; }
2cb757ca-aaa9-4490-9191-6c1e916307ea
private boolean search(CommandSender sender, String[] args) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "Usage: search <player>"); return true; } List<EditBan> bans = plugin.db.listRecords(args[1], false); if (bans.isEmpty()) { sender.sendMessage(ChatColor.RED + "No records"); return true; } sender.sendMessage(ChatColor.GOLD + "Found " + bans.size() + " records for keyword " + args[1] + ":"); for (EditBan ban : bans) { sender.sendMessage(ChatColor.AQUA + banType(ban.type) + ChatColor.YELLOW + ban.id + " " + ban.name + ": " + ChatColor.GREEN + ban.reason + ChatColor.YELLOW + " by " + ban.admin); } return true; }
67e2aaf0-ceb2-4784-8fd3-1c9fe688eb65
private boolean load(CommandSender sender, String[] args) { if (ban != null) { sender.sendMessage(ChatColor.RED + "Finish what you're doing first!"); return true; } if (args.length < 2) { sender.sendMessage(ChatColor.RED + "Usage: load <player>"); return true; } if (!FigAdmin.validName(args[1])) { sender.sendMessage(ChatColor.RED + plugin.formatMessage(plugin.getConfig().getString("messages.badPlayerName", "bad player name"))); return true; } EditBan eb = plugin.db.loadFullRecord(args[1]); if (eb == null) { sender.sendMessage(ChatColor.RED + "Unable to find the last ban/warn of this player"); return true; } ban = eb; sender.sendMessage(ChatColor.GREEN + "Editing the last ban/warn of player " + eb.name + ": "); showBanInfo(eb, sender); return true; }
561a111d-0380-49bf-825e-44efa5bd638d
private boolean id(CommandSender sender, String[] args) { if (ban != null) { sender.sendMessage(ChatColor.RED + "Finish what you're doing first!"); return true; } if (args.length < 2) { sender.sendMessage(ChatColor.RED + "Usage: load <ban id>"); return true; } int id; try { id = Integer.parseInt(args[1]); } catch (NumberFormatException exc) { sender.sendMessage(ChatColor.RED + "ID has to be a number!"); return true; } EditBan eb = plugin.db.loadFullRecord(id); if (eb == null) { sender.sendMessage(ChatColor.RED + "Unable to find a ban of this player"); return true; } ban = eb; sender.sendMessage(ChatColor.GREEN + "Editing the last ban/warn of player " + eb.name + ": "); showBanInfo(eb, sender); return true; }
db656a8f-c6a3-4be9-85f9-33ed8ac9c14b
private boolean save(CommandSender sender, String[] args) { if (plugin.db.saveFullRecord(ban)) { for (int i = 0; i < plugin.bannedPlayers.size(); i++) { EditBan eb = plugin.bannedPlayers.get(i); if (eb.name.equals(ban.name) && eb.type == ban.type) { plugin.bannedPlayers.set(i, eb); break; } } sender.sendMessage(ChatColor.GREEN + "Saved ban!"); } else { sender.sendMessage(ChatColor.RED + "Saving Failed!"); } ban = null; return true; }
8d5b4990-190c-4646-9dd1-51a3641a845c
private boolean view(CommandSender sender, String[] args) { showBanInfo(ban, sender); return true; }
4fa2051c-2810-413b-8bc1-24367a5f4262
private boolean reason(CommandSender sender, String[] args) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "Usage: reason <add/set/show> (text)"); return true; } if (args[1].equalsIgnoreCase("add")) { if (args.length < 3) { sender.sendMessage(ChatColor.RED + "Usage: reason add <text>"); return true; } ban.reason += " " + plugin.combineSplit(2, args, " "); ban.reason = plugin.formatMessage(ban.reason); return true; } boolean show = false; if (args[1].equalsIgnoreCase("set")) { if (args.length < 3) { sender.sendMessage(ChatColor.RED + "Usage: reason set <text>"); show = true; } ban.reason = plugin.combineSplit(2, args, " "); ban.reason = plugin.formatMessage(ban.reason); show = true; } if (show || args[1].equalsIgnoreCase("show")) { sender.sendMessage(ChatColor.YELLOW + "Reason: " + ChatColor.WHITE + ban.reason); return true; } return false; }
a2dc0f10-6af9-4a24-ac08-0e388507e9ad
private boolean time(CommandSender sender, String[] args) { if (args.length < 4) { sender.sendMessage(ChatColor.RED + "Usage: time <add/sub/set> <time> <sec/min/hour/day/week/month>"); return true; } long time = plugin.parseTimeSpec(args[2], args[3]); if (time == 0) { sender.sendMessage(ChatColor.RED + "Invalid time format"); return true; } boolean add = args[1].equalsIgnoreCase("add"), set = args[1].equalsIgnoreCase("set"), sub = args[1] .equalsIgnoreCase("sub"); if (add || set || sub) { if (ban.endTime == 0) { ban.endTime = ban.time; } if (add) { ban.endTime += time; } else if (set) { ban.endTime = ban.time + time; } else if (sub) { ban.endTime -= time; } Date date = new Date(); date.setTime(ban.endTime * 1000); sender.sendMessage(ChatColor.YELLOW + "New time: " + ChatColor.WHITE + date.toString()); return true; } return false; }
2e1ec0d1-bc4a-43cb-a38c-f6d5e6200297
private boolean delete(CommandSender sender, String[] args) { if (ban != null) { sender.sendMessage(ChatColor.RED + "Finish what you're doing first!"); return true; } if (args.length < 2) { sender.sendMessage(ChatColor.RED + "Usage: delete [id]"); return true; } int id; try { id = Integer.parseInt(args[1]); } catch (NumberFormatException exc) { sender.sendMessage(ChatColor.RED + "ID has to be a number!"); return true; } for (int i = 0; i < plugin.bannedPlayers.size(); i++) { if (plugin.bannedPlayers.get(i).id == id) { plugin.bannedPlayers.remove(i); break; } } boolean success = plugin.db.deleteFullRecord(id); if (success) sender.sendMessage(ChatColor.GREEN + "Deleted record " + id); else sender.sendMessage(ChatColor.RED + "Can't find record " + id); return success; }