View difference between Paste ID: 8G9q6Qyu and nugiu2EU
SHOW: | | - or go back to the newest paste.
1
Index: net.sf.l2j;Config.JAVA
2
===================================================================
3
--- net.sf.l2j;Config.JAVA (revision)
4
+++ net.sf.l2j;Config.JAVA (working copy)
5
6
+	/** Auto Save Data Base */
7
+	public static boolean ENABLE_BACKUP_BOOLEAN;
8
+	public static String NAME_DATA_BASE;
9
10
11
+	ENABLE_BACKUP_BOOLEAN = Boolean.parseBoolean(aCis.getProperty("AutoSaveDB", "True"));
12
+	NAME_DATA_BASE = aCis.getProperty("URL_DB", "aCis");
13
	
14
15
	
16
17
Index: Dev.AutoBackup;BackupDBSave.JAVA
18
===================================================================
19
--- Dev.AutoBackup;BackupDBSave.JAVA (revision)
20
+++ Dev.AutoBackup;BackupDBSave.JAVA (working copy)
21
22
+	package Dev.AutoBackup;
23
+	
24
+	import java.io.BufferedReader;
25
+	import java.io.File;
26
+	import java.io.FileInputStream;
27
+	import java.io.FileOutputStream;
28
+	import java.io.IOException;
29
+	import java.io.InputStreamReader;
30
+	import java.net.URL;
31
+	import java.sql.Connection;
32
+	import java.sql.PreparedStatement;
33
+	import java.sql.ResultSet;
34
+	import java.text.DateFormat;
35
+	import java.text.SimpleDateFormat;
36
+	import java.util.Date;
37
+	import java.util.zip.ZipEntry;
38
+	import java.util.zip.ZipOutputStream;
39
+	
40
+	import net.sf.l2j.commons.concurrent.ThreadPool;
41
+	
42
+	import net.sf.l2j.Config;
43
+	import net.sf.l2j.L2DatabaseFactory;
44
+	import net.sf.l2j.util.Mysql;
45
+	
46
+	
47
+	/**
48
+	 * @author COMBATE
49
+	 * 
50
+	 * note to RESTORE
51
+	 * Unzip the file
52
+	 * Then go to database via navicat and run Execute SQL File
53
+	 * Then declick the option "Run multiple queries in each execution" to avoid conflict with locks of tables 
54
+	 */
55
+	public class BackupDBSave
56
+	{
57
+		private String database_name = Config.NAME_DATA_BASE;
58
+		private boolean DEBUG_SYSTEM = false;
59
+		private long initializeAfterTime = 1000 * 60 * 60 * 1; // Start in 2 hour
60
+		private long checkEveryTime = 1000 * 60 * 60 * 1; // Every 6 hours
61
+		
62
+		protected BackupDBSave()
63
+		{
64
+			ThreadPool.scheduleAtFixedRate(() -> BackupDBToSql(), initializeAfterTime, checkEveryTime);
65
+			
66
+			System.out.println("Database Backup Manager: Loaded");
67
+		}
68
+	
69
+		public void BackupDBToSql()
70
+		{
71
+			String pathOfMysql = "\"";
72
+			
73
+			Connection con = null;
74
+			PreparedStatement statement = null;
75
+			ResultSet rs = null;
76
+			
77
+			try
78
+			{
79
+				con = L2DatabaseFactory.getInstance().getConnection();
80
+				statement = con.prepareStatement("SELECT @@basedir");
81
+				rs = statement.executeQuery();
82
+				
83
+				while (rs.next())
84
+				{
85
+					pathOfMysql += rs.getString(1);
86
+				}
87
+			}
88
+			catch (Exception e)
89
+			{
90
+				e.printStackTrace();
91
+			}
92
+			finally
93
+			{
94
+				Mysql.closeQuietly(con, statement, rs);
95
+			}
96
+			
97
+			if (pathOfMysql.isEmpty())
98
+			{
99
+				System.out.println("Error on backup database. Empty path of mysql.");
100
+				return;
101
+			}
102
+			
103
+			// Give the specific path (pathOfMysql out = C:\Program Files\MySQL\MySQL Server 5.7\)
104
+			pathOfMysql += "bin\\mysqldump" + "\"";
105
+			
106
+			if(DEBUG_SYSTEM) System.out.println("Path of mysql: " + pathOfMysql);
107
+			
108
+			// Initialize code for backup
109
+			try
110
+			{
111
+				// Section for path of system
112
+				URL applicationRootPathURL = getClass().getProtectionDomain().getCodeSource().getLocation();
113
+				File applicationRootPath = new File(applicationRootPathURL.getPath());
114
+				File myFile = new File(applicationRootPath.getParent());
115
+				File lastMyFile = new File(myFile.getParent());
116
+	
117
+				String dbUser = Config.DATABASE_LOGIN;
118
+				String dbPass = Config.DATABASE_PASSWORD;
119
+				
120
+				String commandOfMysqlDump = " " + database_name + " --single-transaction -u" + dbUser + " -p" + dbPass + " --skip-create-options --skip-comments --disable-keys > ";
121
+				
122
+				/* NOTE: Creating Path Constraints for folder saving */
123
+				/* NOTE: Here the backup folder is created for saving inside it */
124
+				String folderPath = "backup";
125
+				
126
+				/* NOTE: Creating Folder if it does not exist */
127
+				File f1 = new File(folderPath);
128
+				f1.mkdir();
129
+				
130
+				/* NOTE: Creating Path Constraints for backup saving */
131
+				/* NOTE: Here the backup is saved in a folder called backup with the name backup.sql */
132
+				String pathUntilDirectory = (lastMyFile.getAbsolutePath() + "\\backup\\").replaceAll("%20", " ");
133
+				String savePath = ("\""+pathUntilDirectory + "backup.sql\"").replaceAll("%20", " ");
134
+	
135
+				/* NOTE: Used to create a cmd command */
136
+				String commandToExecute = "cmd /c "+ pathOfMysql + commandOfMysqlDump + savePath;
137
+				
138
+				if (DEBUG_SYSTEM)
139
+				{
140
+					System.out.println("Save path of sql file: " + savePath);
141
+					System.out.println("Command To Execute: " + commandToExecute);
142
+				}
143
+				
144
+				/* NOTE: Executing the command here */
145
+				Process runtimeProcess = Runtime.getRuntime().exec(new String[] {"cmd", "/c", commandToExecute });
146
+				
147
+				if (DEBUG_SYSTEM)
148
+				{
149
+					BufferedReader stdInput = new BufferedReader(new InputStreamReader(runtimeProcess.getInputStream()));
150
+					BufferedReader stdError = new BufferedReader(new InputStreamReader(runtimeProcess.getErrorStream()));
151
+					
152
+					// read the output from the command
153
+					System.out.println("Here is the standard output of the command:\n");
154
+					String s = null;
155
+					while ((s = stdInput.readLine()) != null) {
156
+						System.out.println(s);
157
+					}
158
+					
159
+					// read any errors from the attempted command
160
+					System.out.println("Here is the standard error of the command (if any):\n");
161
+					while ((s = stdError.readLine()) != null) {
162
+						System.out.println(s);
163
+					}
164
+				}
165
+				
166
+				int processComplete = runtimeProcess.waitFor();
167
+				
168
+				/* NOTE: processComplete=0 if correctly executed, will contain other values if not */
169
+				if (processComplete == 0)
170
+				{
171
+					System.out.println("Backup to SQL Complete");
172
+					
173
+					// Zip the sql file
174
+					zipAFile(pathUntilDirectory);
175
+					
176
+					// Delete the backup.sql file
177
+					deleteAFile(savePath.replaceAll("\"", ""));
178
+				}
179
+				else
180
+				{
181
+					System.out.println("Backup to SQL Failure");
182
+				}
183
+			}
184
+			catch (IOException | InterruptedException ex)
185
+			{
186
+				System.out.println("Error at Backuprestore" + ex.getMessage());
187
+			}
188
+		}
189
+		
190
+		@SuppressWarnings("resource")
191
+		private static void zipAFile(String pathToSave)
192
+		{
193
+			byte[] buffer = new byte[1024];
194
+			
195
+			try
196
+			{
197
+				DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
198
+	            Date date = new Date();
199
+				
200
+				FileOutputStream fos = new FileOutputStream(pathToSave + "Backup_"+dateFormat.format(date)+".zip");
201
+				ZipOutputStream zos = new ZipOutputStream(fos);
202
+				ZipEntry ze = new ZipEntry("backup.sql");
203
+				zos.putNextEntry(ze);
204
+				FileInputStream in = new FileInputStream(pathToSave + "\\backup.sql");
205
+				
206
+				int len;
207
+				while ((len = in.read(buffer)) > 0)
208
+				{
209
+					zos.write(buffer, 0, len);
210
+				}
211
+				
212
+				in.close();
213
+				zos.closeEntry();
214
+				
215
+				// remember close it
216
+				zos.close();
217
+				
218
+				System.out.println("Done the zip of backup.");
219
+				
220
+			}
221
+			catch (IOException ex)
222
+			{
223
+				ex.printStackTrace();
224
+			}
225
+			
226
+		}
227
+		
228
+		private static void deleteAFile(String path) {
229
+			try{
230
+	    		File file = new File(path);
231
+	    		System.out.println(file.delete() ? (file.getName() + " is deleted!") : ("Delete operation is failed."));
232
+	    		
233
+	    	}catch(Exception e){
234
+	
235
+	    		e.printStackTrace();
236
+	
237
+	    	}
238
+		}
239
+	
240
+		public static BackupDBSave getInstance()
241
+		{
242
+			return SingletonHolder._instance;
243
+		}
244
+		
245
+		private static class SingletonHolder
246
+		{
247
+			protected static final BackupDBSave _instance = new BackupDBSave();
248
+		}
249
+	}
250
+		
251
252
Index: Dev.AutoBackup;Mysql.JAVA
253
===================================================================
254
--- Dev.AutoBackup;Mysql.JAVA (revision)
255
+++ Dev.AutoBackup;Mysql.JAVA (working copy)
256
257
+	package Dev.AutoBackup;
258
+	
259
+	
260
+	import java.sql.Connection;
261
+	import java.sql.PreparedStatement;
262
+	import java.sql.ResultSet;
263
+	import java.sql.SQLException;
264
+	import java.sql.Statement;
265
+	import java.util.logging.Logger;
266
+	
267
+	import net.sf.l2j.L2DatabaseFactory;
268
+	
269
+	/**
270
+	 * @author COMBATE
271
+	 *
272
+	 */
273
+	public abstract class Mysql
274
+	{
275
+		private static final Logger _log = Logger.getLogger(Mysql.class.getName());
276
+	
277
+		/**
278
+		 * Performs a simple sql queries where unnecessary control parameters <BR>
279
+		 * NOTE: In this method, the parameters passed are not valid for SQL-injection!
280
+		 * @param db 
281
+		 * @param query 
282
+		 * @param vars 
283
+		 * @return 
284
+		 */
285
+		public static boolean setEx(L2DatabaseFactory db, String query, Object... vars)
286
+		{
287
+			Connection con = null;
288
+			Statement statement = null;
289
+			PreparedStatement pstatement = null;
290
+			boolean successed = true;
291
+			
292
+			try
293
+			{
294
+				if(db == null)
295
+					db = L2DatabaseFactory.getInstance();
296
+	
297
+				con = db.getConnection();
298
+				if(vars.length == 0)
299
+				{
300
+					statement = con.createStatement();
301
+					statement.executeUpdate(query);
302
+					statement.close();
303
+				}
304
+				else
305
+				{
306
+					pstatement = con.prepareStatement(query);
307
+					setVars(pstatement, vars);
308
+					pstatement.executeUpdate();
309
+					pstatement.close();
310
+				}
311
+				con.close();
312
+			}
313
+			catch(Exception e)
314
+			{
315
+				_log.warning("Could not execute update '" + query + "': " + e);
316
+				e.printStackTrace();
317
+				successed = false;
318
+			}
319
+			finally
320
+			{
321
+				closeQuietly(con, pstatement);
322
+				closeQuietly(statement);
323
+			}
324
+			return successed;
325
+		}
326
+	
327
+		public static void setVars(PreparedStatement statement, Object... vars) throws SQLException
328
+		{
329
+			Number n;
330
+			long long_val;
331
+			double double_val;
332
+			for(int i = 0; i < vars.length; i++)
333
+				if(vars[i] instanceof Number)
334
+				{
335
+					n = (Number) vars[i];
336
+					long_val = n.longValue();
337
+					double_val = n.doubleValue();
338
+					if(long_val == double_val)
339
+						statement.setLong(i + 1, long_val);
340
+					else
341
+						statement.setDouble(i + 1, double_val);
342
+				}
343
+				else if(vars[i] instanceof String)
344
+					statement.setString(i + 1, (String) vars[i]);
345
+		}
346
+	
347
+		public static boolean set(String query, Object... vars)
348
+		{
349
+			return setEx(null, query, vars);
350
+		}
351
+	
352
+		public static boolean set(String query)
353
+		{
354
+			return setEx(null, query);
355
+		}
356
+		
357
+		public static void closeQuietly(Connection conn) 
358
+		{
359
+			try {
360
+				close(conn);
361
+			} catch (SQLException e) { // NOPMD
362
+				// quiet
363
+			}
364
+		}
365
+	
366
+		public static void closeQuietly(Connection conn, Statement stmt, ResultSet rs) {
367
+	
368
+	        try {
369
+	            closeQuietly(rs);
370
+	        } finally {
371
+	            try {
372
+	                closeQuietly(stmt);
373
+	            } finally {
374
+	                closeQuietly(conn);
375
+	            }
376
+	        }
377
+	    }
378
+		
379
+		public static void closeQuietly(Connection conn, Statement stmt) 
380
+	    {
381
+	    	try {
382
+	    		closeQuietly(stmt);
383
+	    	} finally {
384
+	    		closeQuietly(conn);
385
+	    	}
386
+	    }
387
+	
388
+	    public static void closeQuietly(ResultSet rs) {
389
+	        try {
390
+	            close(rs);
391
+	        } catch (SQLException e) { // NOPMD
392
+	            // quiet
393
+	        }
394
+	    }
395
+	
396
+	    public static void closeQuietly(Statement stmt) {
397
+	        try {
398
+	            close(stmt);
399
+	        } catch (SQLException e) { // NOPMD
400
+	            // quiet
401
+	        }
402
+	    }
403
+	
404
+	    public static void close(Connection conn) throws SQLException {
405
+	        if (conn != null) {
406
+	            conn.close();
407
+	        }
408
+	    }
409
+	
410
+	    public static void close(ResultSet rs) throws SQLException {
411
+	        if (rs != null) {
412
+	            rs.close();
413
+	        }
414
+	    }
415
+	
416
+	    public static void close(Statement stmt) throws SQLException {
417
+	        if (stmt != null) {
418
+	            stmt.close();
419
+	        }
420
+	    }
421
+	}
422
+	
423
424
Index: net.sf.l2j.gameserver;GameServer.JAVA
425
===================================================================
426
--- net.sf.l2j.gameserver;GameServer.JAVA (revision)
427
+++ net.sf.l2j.gameserver;GameServer.JAVA (working copy)
428
429
+	import Dev.AutoBackup.BackupDBSave;
430
431
+	StringUtil.printSection("DataBase Auto Save");
432
+	if (Config.ENABLE_BACKUP_BOOLEAN) {
433
+		BackupDBSave.getInstance();
434
+	    LOGGER.info("[DataBase Auto Save]: Enabled");
435
+	}else
436
+	{
437
+		LOGGER.info("[DataBase Auto Save]: Desatived");
438
+	}
439
440
Index: gameserver.config.aCis.aCis.properties
441
===================================================================
442
--- gameserver.config.aCis.aCis.properties (revision)
443
+++ gameserver.config.aCis.aCis.properties (working copy)
444
445
# Enable Auto Save DataBase
446
AutoSaveDB = True
447
448
#Name DataBase
449
#Ex: l2jdb
450
URL_DB = aCis