Skip to content

Instantly share code, notes, and snippets.

@FMCalisto
Forked from pedroreissantos/DbaseClean.java
Created February 24, 2016 20:37
Show Gist options
  • Select an option

  • Save FMCalisto/71ce61e7bac37ed90996 to your computer and use it in GitHub Desktop.

Select an option

Save FMCalisto/71ce61e7bac37ed90996 to your computer and use it in GitHub Desktop.
Exemplos de introdução aos componentes do projeto (Engenharia de Software, IST, 2016)
/*
* DbaseClean
* Drop a database, if exists, and create a new empty one.
* Collect database info from a resource file.
*
* When using embeded in an application must be called outside a transaction
* (@Atomic) or connection to the same database server!
*
* javac DbaseClean.java
* java -cp mysql-connector-java-5.1.38.jar:. DbaseClean
*
* Maven (do not use in the fenix-framework):
* <dependency>
* <groupId>mysql</groupId>
* <artifactId>mysql-connector-java</artifactId>
* <version>5.1.38</version>
* </dependency>
*/
import java.io.*;
import java.sql.*;
import java.util.Scanner;
public class DbaseClean {
static final String driver = "com.mysql.jdbc.Driver";
static final String url = "jdbc:mysql://localhost/";
private String dbase, user, passwd; // dbase params from resource file
// resource file in current-dir ou src/main/resources maven-dir
private static String res = "fenix-framework-jvstm-ojb.properties";
private Connection conn = null;
public DbaseClean() { getDbase(res); }
public DbaseClean(String resource) { getDbase(res = resource); }
public DbaseClean(String db, String user, String pw) {
dbase = db;
this.user = user;
passwd = pw;
}
public void connect() throws SQLException {
conn = DriverManager.getConnection(url, user, passwd);
}
public void disconnect() throws SQLException {
if (conn != null) conn.close();
conn = null;
}
public String name() { return dbase; }
public String user() { return user; }
protected String passwd() { return passwd; }
public void name(String s) { dbase = s; }
public void user(String s) { user = s; }
public void passwd(String s) { passwd = s; }
public static void main(String[] args) {
try {
DbaseClean db;
if (args.length == 3) db = new DbaseClean(args[0], args[1], args[2]);
else {
if (args.length > 3) {
System.err.println("DbaseClean [dbase [user [passwd]]]");
return;
}
db = new DbaseClean();
if (args.length > 0) db.name(args[0]);
if (args.length > 1) db.user(args[1]);
if (args.length > 2) db.passwd(args[2]);
}
db.cleanup();
System.out.println("Database created successfully...");
} catch(Exception e) { e.printStackTrace(); }
}
public void cleanup() throws Exception {
Class.forName(driver);
System.err.println(user()+"@"+url+user()); // debug
connect();
System.err.println("Connected..."); // debug
try { sql("DROP DATABASE " + name());
} catch (SQLException e) { System.err.println(e); }
sql("CREATE DATABASE " + name());
disconnect();
}
public void sql(String com) throws SQLException {
Statement stmt = conn.createStatement();
stmt.executeUpdate(com);
stmt.close();
}
/* read database information from resource file */
private void getDbase(String fileName) {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (line.length() == 0) continue;
if (line.charAt(0) == '#') continue;
String[] attr = line.split("=");
if (attr[0].equals("dbUsername")) user = attr[1].trim();
if (attr[0].equals("dbPassword")) passwd = attr[1].trim();
if (attr[0].equals("dbAlias")) {
int i = attr[1].trim().lastIndexOf('/');
int j = attr[1].trim().lastIndexOf('?');
dbase = attr[1].trim().substring(i+1,j);
}
}
scanner.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
import java.io.*;
import java.util.*;
abstract class Command {
private String name, help;
Command(String n) { name = n; help = "<no help>"; }
Command(String n, String h) { name = n; help = h; }
abstract void execute(String[] args);
public String name() { return name; }
public String help() { return help; }
/* package */ void help(String h) { help = h; }
}
class Quit extends Command {
Quit() { super("quit", "exit the command interpreter"); }
void execute(String[] args) { System.exit(0); }
}
class Help extends Command {
Shell shell;
Help(Shell sh) { super("help", "this command help"); shell = sh; }
void execute(String[] args) {
if (args.length == 0)
for (Command c: shell.coms) System.out.println(c.name());
else {
for (String s: args)
for (Command c: shell.coms)
if (c.name().equals(s))
System.out.println(c.help());
}
}
}
class Print extends Command {
Print() { super("print"); }
void execute(String[] args) {
System.out.println("#"+args.length);
for (String s: args)
System.out.println(s);
}
}
class Shell {
List<Command> coms = new ArrayList<Command>();
public static void main(String[] args) throws Exception {
Shell sh = new Shell();
sh.add(new Quit());
sh.add(new Help(sh));
sh.add(new Print());
sh.add(new Command("exec", "execute a command") {
void execute(String[] args) {
try { Exec.main(args);
} catch (Exception e) { throw new RuntimeException(""+e); }
}
} );
sh.add(new Command("excep", "throw an exception") {
void execute(String[] args) {
throw new RuntimeException("teste!");
}
} );
sh.add(new Command("sum", "sum a list of integers") {
void execute(String[] args) {
int sum = 0;
for (String s: args) sum += Integer.parseInt(s);
System.out.println("sum="+sum);
}
} );
sh.execute();
}
public void add(Command c) { coms.add(c); }
public void execute() throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str, prompt = System.getenv().get("PS1");
if (prompt == null) prompt = "$ ";
System.out.println("myDrive shell");
System.out.print(prompt);
while ((str = in.readLine()) != null) {
String[] arg = str.split(" ");
boolean found = false;
for (Command c: coms)
if (arg[0].equals(c.name())) {
try {
c.execute(Arrays.copyOfRange(arg, 1, arg.length));
} catch (RuntimeException e) {
System.err.println(arg[0]+": "+e);
}
found = true;
}
if (!found && arg[0].length() > 0) System.err.println(arg[0]+": command not found.");
System.out.print(prompt);
}
}
private static boolean wildcard(String text, String pattern) {
String[] cards = pattern.split("\\*");
for (String card : cards) {
int idx = text.indexOf(card);
if(idx == -1) return false; // Card not detected in the text.
text = text.substring(idx + card.length());
}
return true;
}
}
/*
* javac -cp log4j-api-2.5.jar\;. Log4j2.java
* java -cp log4j-core-2.5.jar\;log4j-api-2.5.jar\;. Log4j2
* Use log4j2.xml in CLASSPATH or set property log4j.configurationFile:
* java -Dlog4j.configurationFile=File:configuration.xml
* or
* System.setProperties("log4j.configurationFile", "File:configuration.xml);
*
* <dependencies>
* <dependency>
* <groupId>org.apache.logging.log4j</groupId>
* <artifactId>log4j-api</artifactId>
* <version>2.0-rc1</version>
* </dependency>
* <dependency>
* <groupId>org.apache.logging.log4j</groupId>
* <artifactId>log4j-core</artifactId>
* <version>2.0-rc1</version>
* </dependency>
* </dependencies>
*/
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4j2 {
public static void main( String[] args ) {
Logger log = LogManager.getRootLogger();
log.trace("Configuration File Defined To Be :: "+System.getProperty("log4j.configurationFile"));
log.trace("Trace Message!");
log.debug("Debug Message!");
log.info("Info Message!");
log.warn("Warn Message!");
log.error("Error Message!");
log.fatal("Fatal Message!");
}
}
/* log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="Console">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="trace">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
*/
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.math.BigInteger;
import java.util.Random;
public class sha1 {
public static void main(String[] args) {
for (String s: args)
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(s.getBytes("UTF-8")); // Change this to "UTF-16" if needed
byte[] digest = md.digest();
System.out.println(s+": "+
String.format("%040x", new java.math.BigInteger(1, digest)));
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { System.err.println(e); }
}
}
/*
* XML input/output
*
* javac -cp jdom2-2.0.6.jar:. XmlRead.java
* java -cp jdom2-2.0.6.jar:. XmlRead users.xml
*/
import java.io.File;
import java.io.FileWriter;
import java.io.PrintStream;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Attribute;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;
import org.jdom2.output.Format;
// http://www.jdom.org/docs/apidocs/org/jdom2/Element.html
public class XmlRead {
public static void main(String[] args) {
//String[] names = { "abc", "def", "ghi", "jkl", "mno" };
new XmlRead().input(args[0]);
//output(args.length > 1 ? args[1] : null, names);
output(args.length > 1 ? args[1] : null, new String[] { "abc", "def", "ghi", "jkl", "mno" });
}
public void input(String filename) {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(filename).getFile());
try {
Document document = (Document) new SAXBuilder().build(file);
Element rootNode = document.getRootElement();
for (Element node: rootNode.getChildren("user"))
System.out.println("Name : " + node.getAttributeValue("id") + " " + node.getChildText("username"));
} catch (JDOMException | IOException e) { e.printStackTrace(); }
}
public static void output(String filename, String[] names) {
try {
Document doc = new Document(new Element("users"));
int id = 0;
for (String s : names) {
Element staff = new Element("user");
staff.setAttribute(new Attribute("id", "" + ++id));
staff.addContent(new Element("username").setText(s));
doc.getRootElement().addContent(staff);
}
XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
if (filename != null)
xmlOutput.output(doc, new FileWriter(filename));
else
xmlOutput.output(doc, new PrintStream(System.out));
} catch (IOException io) { System.err.println(io); }
}
}
/* users.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="7">
<username>Abc</username>
</user>
<user id="0">
<username>dEf</username>
</user>
<user id="9">
<username>ghI</username>
</user>
<user id="6">
<username>JkL</username>
</user>
<user id="8">
<username>mNo</username>
</user>
</users>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment