code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
var Videobox = {
init: function (options) {
// init default options
this.options = Object.extend({
resizeDuration: 400, // Duration of height and width resizing (ms)
initialWidth: 250, // Initial width of the box (px)
initialHeight: 250, // Initial height of the box (px)
defaultWidth: 425, // Default width of the box (px)
defaultHeight: 350, // Default height of the box (px)
animateCaption: true, // Enable/Disable caption animation
flvplayer: 'swf/flvplayer.swf'
}, options || {});
this.anchors = [];
$A($$('a')).each(function(el){
if(el.rel && el.href && el.rel.test('^vidbox', 'i')) {
el.addEvent('click', function (e) {
e = new Event(e);
e.stop();
this.click(el);
}.bind(this));
this.anchors.push(el);
}
}, this);
this.overlay = new Element('div').setProperty('id', 'lbOverlay').injectInside(document.body);
this.center = new Element('div').setProperty('id', 'lbCenter').setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px', marginLeft: '-'+(this.options.initialWidth/2)+'px', display: 'none'}).injectInside(document.body);
this.bottomContainer = new Element('div').setProperty('id', 'lbBottomContainer').setStyle('display', 'none').injectInside(document.body);
this.bottom = new Element('div').setProperty('id', 'lbBottom').injectInside(this.bottomContainer);
new Element('a').setProperties({id: 'lbCloseLink', href: '#'}).injectInside(this.bottom).onclick = this.overlay.onclick = this.close.bind(this);
this.caption = new Element('div').setProperty('id', 'lbCaption').injectInside(this.bottom);
this.number = new Element('div').setProperty('id', 'lbNumber').injectInside(this.bottom);
new Element('div').setStyle('clear', 'both').injectInside(this.bottom);
var nextEffect = this.nextEffect.bind(this);
this.fx = {
overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
center: this.center.effects({duration: 500, transition: Fx.Transitions.sineInOut, onComplete: nextEffect}),
bottom: this.bottom.effect('margin-top', {duration: 400})
};
},
click: function(link) {
return this.open (link.href, link.title, link.rel);
},
open: function(sLinkHref, sLinkTitle, sLinkRel) {
this.href = sLinkHref;
this.title = sLinkTitle;
this.rel = sLinkRel;
this.position();
this.setup();
this.video(this.href);
this.top = Window.getScrollTop() + (Window.getHeight() / 15);
this.center.setStyles({top: this.top+'px', display: ''});
this.fx.overlay.start(0.8);
this.step = 1;
this.center.setStyle('background','#fff url(loading.gif) no-repeat center');
this.caption.innerHTML = this.title;
this.fx.center.start({'height': [this.options.contentsHeight]});
},
setup: function(){
var aDim = this.rel.match(/[0-9]+/g);
this.options.contentsWidth = (aDim && (aDim[0] > 0)) ? aDim[0] : this.options.defaultWidth;
this.options.contentsHeight = (aDim && (aDim[1] > 0)) ? aDim[1] : this.options.defaultHeight;
},
position: function(){
this.overlay.setStyles({'top': window.getScrollTop()+'px', 'height': window.getHeight()+'px'});
},
video: function(sLinkHref){
if (sLinkHref.match(/youtube\.com\/watch/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('=');
this.videoID = videoId[1];
this.so = new SWFObject("http://www.youtube.com/v/"+this.videoID, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/metacafe\.com\/watch/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('/');
this.videoID = videoId[4];
this.so = new SWFObject("http://www.metacafe.com/fplayer/"+this.videoID+"/.swf", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/google\.com\/videoplay/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('=');
this.videoID = videoId[1];
this.so = new SWFObject("http://video.google.com/googleplayer.swf?docId="+this.videoID+"&hl=en", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/ifilm\.com\/video/i)) {
this.flash = true;
var hRef = sLinkHref;
var videoId = hRef.split('video/');
this.videoID = videoId[1];
this.so = new SWFObject("http://www.ifilm.com/efp", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0", "#000");
this.so.addVariable("flvbaseclip", this.videoID+"&");
this.so.addParam("wmode", "transparent");
}
else if (sLinkHref.match(/\.mov/i)) {
this.flash = false;
if (navigator.plugins && navigator.plugins.length) {
this.other ='<object id="qtboxMovie" type="video/quicktime" codebase="http://www.apple.com/qtactivex/qtplugin.cab" data="'+sLinkHref+'" width="'+this.options.contentsWidth+'" height="'+this.options.contentsHeight+'"><param name="src" value="'+sLinkHref+'" /><param name="scale" value="aspect" /><param name="controller" value="true" /><param name="autoplay" value="true" /><param name="bgcolor" value="#000000" /><param name="enablejavascript" value="true" /></object>';
} else {
this.other = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="'+this.options.contentsWidth+'" height="'+this.options.contentsHeight+'" id="qtboxMovie"><param name="src" value="'+sLinkHref+'" /><param name="scale" value="aspect" /><param name="controller" value="true" /><param name="autoplay" value="true" /><param name="bgcolor" value="#000000" /><param name="enablejavascript" value="true" /></object>';
}
}
else if (sLinkHref.match(/\.wmv/i) || sLinkHref.match(/\.asx/i)) {
this.flash = false;
this.other = '<object NAME="Player" WIDTH="'+this.options.contentsWidth+'" HEIGHT="'+this.options.contentsHeight+'" align="left" hspace="0" type="application/x-oleobject" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"><param NAME="URL" VALUE="'+sLinkHref+'"><param><param NAME="AUTOSTART" VALUE="false"></param><param name="showControls" value="true"></param><embed WIDTH="'+this.options.contentsWidth+'" HEIGHT="'+this.options.contentsHeight+'" align="left" hspace="0" SRC="'+sLinkHref+'" TYPE="application/x-oleobject" AUTOSTART="false"></embed></object>'
}
else if (sLinkHref.match(/\.flv/i)) {
this.flash = true;
this.so = new SWFObject(this.options.flvplayer+"?file="+sLinkHref, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0", "#000");
}
else {
this.flash = true;
this.videoID = sLinkHref;
this.so = new SWFObject(this.videoID, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
}
},
nextEffect: function(){
switch (this.step++){
case 1:
this.fx.center.start({'width': [this.options.contentsWidth], 'marginLeft': [this.options.contentsWidth/-2]});
break;
this.step++;
case 2:
this.center.setStyle('background','#fff');
this.flash ? this.so.write(this.center) : this.center.setHTML(this.other) ;
this.bottomContainer.setStyles({top: (this.top + this.center.clientHeight)+'px', height: '0px', marginLeft: this.center.style.marginLeft, width: this.options.contentsWidth+'px',display: ''});
if (this.options.animateCaption){
this.fx.bottom.set(-this.bottom.offsetHeight);
this.bottomContainer.style.height = '';
this.fx.bottom.start(0);
break;
}
this.bottomContainer.style.height = '';
this.step++;
}
},
close: function(){
this.fx.overlay.start(0);
this.center.style.display = this.bottomContainer.style.display = 'none';
this.center.innerHTML = '';
return false;
}
};
window.addEvent('domready', Videobox.init.bind(Videobox)); | 111113ddd | videobox.js | JavaScript | gpl3 | 8,074 |
//** Created: March 19th, 08'
//** Aug 16th, 08'- Updated to v 1.4:
//1) Adds ability to set speed/duration of panel animation (in milliseconds)
//2) Adds persistence support, so the last viewed panel is recalled when viewer returns within same browser session
//3) Adds ability to specify whether panels should stop at the very last and first panel, or wrap around and start all over again
//4) Adds option to specify two navigational image links positioned to the left and right of the Carousel Viewer to move the panels back and forth
//** Aug 27th, 08'- Nav buttons (if enabled) also repositions themselves now if window is resized
var stepcarousel={
ajaxloadingmsg: '<div style="margin: 1em; font-weight: bold"><img src="ajaxloadr.gif" style="vertical-align: middle" /> Fetching Content. Please wait...</div>', //customize HTML to show while fetching Ajax content
defaultbuttonsfade: 0.4, //Fade degree for disabled nav buttons (0=completely transparent, 1=completely opaque)
configholder: {},
getCSSValue:function(val){ //Returns either 0 (if val contains 'auto') or val as an integer
return (val=="auto")? 0 : parseInt(val)
},
getremotepanels:function($, config){ //function to fetch external page containing the panel DIVs
config.$belt.html(this.ajaxloadingmsg)
$.ajax({
url: config.contenttype[1], //path to external content
async: true,
error:function(ajaxrequest){
config.$belt.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
},
success:function(content){
config.$belt.html(content)
config.$panels=config.$gallery.find('.'+config.panelclass)
stepcarousel.alignpanels($, config)
}
})
},
getoffset:function(what, offsettype){
return (what.offsetParent)? what[offsettype]+this.getoffset(what.offsetParent, offsettype) : what[offsettype]
},
getCookie:function(Name){
var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return null
},
setCookie:function(name, value){
document.cookie = name+"="+value
},
fadebuttons:function(config, currentpanel){
config.$leftnavbutton.fadeTo('fast', currentpanel==0? this.defaultbuttonsfade : 1)
config.$rightnavbutton.fadeTo('fast', currentpanel==config.lastvisiblepanel? this.defaultbuttonsfade : 1)
},
addnavbuttons:function(config, currentpanel){
config.$leftnavbutton=$('<img src="'+config.defaultbuttons.leftnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Back '+config.defaultbuttons.moveby+' panels'}).appendTo('body')
config.$rightnavbutton=$('<img src="'+config.defaultbuttons.rightnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Forward '+config.defaultbuttons.moveby+' panels'}).appendTo('body')
config.$leftnavbutton.bind('click', function(){ //assign nav button event handlers
stepcarousel.stepBy(config.galleryid, -config.defaultbuttons.moveby)
})
config.$rightnavbutton.bind('click', function(){ //assign nav button event handlers
stepcarousel.stepBy(config.galleryid, config.defaultbuttons.moveby)
})
if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
this.fadebuttons(config, currentpanel)
}
},
alignpanels:function($, config){
var paneloffset=0
config.paneloffsets=[paneloffset] //array to store upper left offset of each panel (1st element=0)
config.panelwidths=[] //array to store widths of each panel
config.$panels.each(function(index){ //loop through panels
var $currentpanel=$(this)
$currentpanel.css({float: 'none', position: 'absolute', left: paneloffset+'px'}) //position panel
$currentpanel.bind('click', function(e){return config.onpanelclick(e.target)}) //bind onpanelclick() to onclick event
paneloffset+=stepcarousel.getCSSValue($currentpanel.css('marginRight')) + parseInt($currentpanel.get(0).offsetWidth || $currentpanel.css('width')) //calculate next panel offset
config.paneloffsets.push(paneloffset) //remember this offset
config.panelwidths.push(paneloffset-config.paneloffsets[config.paneloffsets.length-2]) //remember panel width
})
config.paneloffsets.pop() //delete last offset (redundant)
var addpanelwidths=0
var lastpanelindex=config.$panels.length-1
config.lastvisiblepanel=lastpanelindex
for (var i=config.$panels.length-1; i>=0; i--){
addpanelwidths+=(i==lastpanelindex? config.panelwidths[lastpanelindex] : config.paneloffsets[i+1]-config.paneloffsets[i])
if (config.gallerywidth>addpanelwidths){
config.lastvisiblepanel=i //calculate index of panel that when in 1st position reveals the very last panel all at once based on gallery width
}
}
config.$belt.css({width: paneloffset+'px'}) //Set Belt DIV to total panels' widths
config.currentpanel=(config.panelbehavior.persist)? parseInt(this.getCookie(window[config.galleryid+"persist"])) : 0 //determine 1st panel to show by default
config.currentpanel=(typeof config.currentpanel=="number" && config.currentpanel<config.$panels.length)? config.currentpanel : 0
if (config.currentpanel!=0){
var endpoint=config.paneloffsets[config.currentpanel]+(config.currentpanel==0? 0 : config.beltoffset)
config.$belt.css({left: -endpoint+'px'})
}
if (config.defaultbuttons.enable==true){ //if enable default back/forth nav buttons
this.addnavbuttons(config, config.currentpanel)
$(window).bind("load, resize", function(){ //refresh position of nav buttons when page loads/resizes, in case offsets weren't available document.oncontentload
config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
config.$leftnavbutton.css({left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px'})
config.$rightnavbutton.css({left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px'})
})
}
this.statusreport(config.galleryid)
config.oninit()
config.onslideaction(this)
},
stepTo:function(galleryid, pindex){ /*User entered pindex starts at 1 for intuitiveness. Internally pindex still starts at 0 */
var config=stepcarousel.configholder[galleryid]
if (typeof config=="undefined"){
alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
return
}
var pindex=Math.min(pindex-1, config.paneloffsets.length-1)
var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset)
if (config.panelbehavior.wraparound==false && config.defaultbuttons.enable==true){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
this.fadebuttons(config, pindex)
}
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
config.currentpanel=pindex
this.statusreport(galleryid)
},
stepBy:function(galleryid, steps){
var config=stepcarousel.configholder[galleryid]
if (typeof config=="undefined"){
alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
return
}
var direction=(steps>0)? 'forward' : 'back' //If "steps" is negative, that means backwards
var pindex=config.currentpanel+steps //index of panel to stop at
if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
pindex=(direction=="back" && pindex<=0)? 0 : (direction=="forward")? Math.min(pindex, config.lastvisiblepanel) : pindex
if (config.defaultbuttons.enable==true){ //if default nav buttons are enabled, fade them in and out depending on if at start or end of carousel
stepcarousel.fadebuttons(config, pindex)
}
}
else{ //else, for normal stepBy behavior
pindex=(pindex>config.paneloffsets.length-1 || pindex<0 && pindex-steps>0)? 0 : (pindex<0)? config.paneloffsets.length+steps : pindex //take into account end or starting panel and step direction
}
var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset) //left distance for Belt DIV to travel to
if (pindex==0 && direction=='forward' || config.currentpanel==0 && direction=='back' && config.panelbehavior.wraparound==true){ //decide whether to apply "push pull" effect
config.$belt.animate({left: -config.paneloffsets[config.currentpanel]-(direction=='forward'? 100 : -30)+'px'}, 'normal', function(){
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
})
}
else
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
config.currentpanel=pindex
this.statusreport(galleryid)
},
statusreport:function(galleryid){
var config=stepcarousel.configholder[galleryid]
var startpoint=config.currentpanel //index of first visible panel
var visiblewidth=0
for (var endpoint=startpoint; endpoint<config.paneloffsets.length; endpoint++){ //index (endpoint) of last visible panel
visiblewidth+=config.panelwidths[endpoint]
if (visiblewidth>config.gallerywidth){
break
}
}
startpoint+=1 //format startpoint for user friendiness
endpoint=(endpoint+1==startpoint)? startpoint : endpoint //If only one image visible on the screen and partially hidden, set endpoint to startpoint
var valuearray=[startpoint, endpoint, config.panelwidths.length]
for (var i=0; i<config.statusvars.length; i++){
window[config.statusvars[i]]=valuearray[i] //Define variable (with user specified name) and set to one of the status values
config.$statusobjs[i].text(valuearray[i]+" ") //Populate element on page with ID="user specified name" with one of the status values
}
},
setup:function(config){
//Disable Step Gallery scrollbars ASAP dynamically (enabled for sake of users with JS disabled)
document.write('<style type="text/css">\n#'+config.galleryid+'{overflow: hidden;}\n</style>')
jQuery(document).ready(function($){
config.$gallery=$('#'+config.galleryid)
config.gallerywidth=config.$gallery.width()
config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
config.$belt=config.$gallery.find('.'+config.beltclass) //Find Belt DIV that contains all the panels
config.$panels=config.$gallery.find('.'+config.panelclass) //Find Panel DIVs that each contain a slide
config.onpanelclick=(typeof config.onpanelclick=="undefined")? function(target){} : config.onpanelclick //attach custom "onpanelclick" event handler
config.onslideaction=(typeof config.onslide=="undefined")? function(){} : function(beltobj){$(beltobj).stop(); config.onslide()} //attach custom "onslide" event handler
config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
config.beltoffset=stepcarousel.getCSSValue(config.$belt.css('marginLeft')) //Find length of Belt DIV's left margin
config.statusvars=config.statusvars || [] //get variable names that will hold "start", "end", and "total" slides info
config.$statusobjs=[$('#'+config.statusvars[0]), $('#'+config.statusvars[1]), $('#'+config.statusvars[2])]
config.currentpanel=0
stepcarousel.configholder[config.galleryid]=config //store config parameter as a variable
if (config.contenttype[0]=="ajax" && typeof config.contenttype[1]!="undefined") //fetch ajax content?
stepcarousel.getremotepanels($, config)
else
stepcarousel.alignpanels($, config) //align panels and initialize gallery
}) //end document.ready
jQuery(window).bind('unload', function(){ //clean up
if (config.panelbehavior.persist){
stepcarousel.setCookie(window[config.galleryid+"persist"], config.currentpanel)
}
jQuery.each(config, function(ai, oi){
oi=null
})
config=null
})
}
}
| 0slider | slider.js | JavaScript | mpl11 | 12,667 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Demo {
public static void main(String args[]) {
Queue q = new Queue();
new Publisher(q);
new Consumer(q);
}
}
| 0812005-java | trunk/Java/java-project-2008/src/GiaoTiepThread/Demo.java | Java | oos | 301 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Queue {
int exchangeValue;
boolean busy = false;
synchronized int get() {
if (!busy) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(
"Get: InterruptedException");
}
}
System.out.println("Get: " + exchangeValue);
busy=false;
notify();
return exchangeValue;
}
synchronized void put(int exchangeValue) {
if (busy) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(
"Put: InterruptedException");
}
}
this.exchangeValue = exchangeValue;
busy = true;
System.out.println("Put: " + exchangeValue);
notify();
}
}
| 0812005-java | trunk/Java/java-project-2008/src/GiaoTiepThread/Queue.java | Java | oos | 1,013 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Publisher implements Runnable {
Queue q;
Publisher(Queue q) {
this.q = q;
new Thread(this, "Publisher").start();
}
public void run() {
for (int i = 0; i < 5; i++) {
q.put(i);
}
}
} | 0812005-java | trunk/Java/java-project-2008/src/GiaoTiepThread/Publisher.java | Java | oos | 407 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Consumer implements Runnable {
Queue q;
Consumer(Queue q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
for (int i = 0; i < 5; i++) {
q.get();
}
}
} | 0812005-java | trunk/Java/java-project-2008/src/GiaoTiepThread/Consumer.java | Java | oos | 403 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author TanAnh
*/
public class Demo {
public static void main(String args[]) throws InterruptedException{
Parentheses p3=new Parentheses();
MyThread name1=new MyThread(p3, "Bob");
MyThread name2=new MyThread(p3, "Mary");
MyThread name3=new MyThread(p3, "Anh");
MyThread name4=new MyThread(p3, "Luong");
name1.t.join();
name2.t.join();
name3.t.join();
name4.t.join();
System.out.println("Interupted");
}
}
| 0812005-java | trunk/Java/java-project-2008/src/Demo.java | Java | oos | 633 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author TanAnh
*/
public class MyThread implements Runnable {
String s1;
Parentheses p1;
Thread t;
public MyThread(Parentheses p2, String s2){
p1=p2;
s1=s2;
t=new Thread(this);
t.start();
}
@Override
public void run() {
synchronized(p1){
p1.display(s1);
}
}
}
| 0812005-java | trunk/Java/java-project-2008/src/MyThread.java | Java | oos | 492 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.xml.sax.SAXException;
/**
*
* @author PC
*/
public class _MainFrm extends javax.swing.JFrame {
/**
* Creates new form _MainFrm
*/
public _MainFrm() {
initComponents();
}
/**
* 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.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane2.setViewportView(jTextArea1);
jButton1.setText("Execute");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("jButton2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26))
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jButton1)
.addGap(32, 32, 32)
.addComponent(jButton2)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap(59, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
// TODO add your handling code here:
String query = jTextArea1.getText();
String_Utilities.QUERY res = String_Utilities.getQuery(query);
switch (res) {
case INSERT:
String_Utilities.insert_method(query);
break;
case UPDATE:
String_Utilities.update_method(query);
break;
case CREATE:
Table table=new Table();
new XuLyChuoi().TaoBang(query, table);
new Create().CreateTable(table);
}
} catch (ParserConfigurationException ex) {
Logger.getLogger(_MainFrm.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(_MainFrm.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(_MainFrm.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerConfigurationException ex) {
Logger.getLogger(_MainFrm.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(_MainFrm.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus 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 {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(_MainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(_MainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(_MainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(_MainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new _MainFrm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration//GEN-END:variables
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/_MainFrm.java | Java | oos | 8,167 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* @author TanAnh
*/
public class String_Utilities {
private static String getPara(String query) {
int from = query.indexOf('(');
int to = query.indexOf(')');
return query.substring(from + 1, to).trim();
}
private static String getParavalues(String query) {
query = query.toLowerCase();
int from = query.indexOf("values") + "values".length();
int to = query.length() - 1;
return query.substring(from + 1, to).trim();
}
private static List<Col> getListCol(String Para, String ParaValues) {
List<Col> res = new LinkedList<Col>();
String[] lisPara = Para.split(",");
String[] lisParaValues = ParaValues.split(",");
for (int i = 0; i < lisPara.length; i++) {
Col c = new Col();
if (lisParaValues[i].contains("'")) {
c.Type = "string";
} else {
c.Type = "int";
}
c.Ten = lisPara[i];
c.Value = lisParaValues[i];
res.add(c);
}
return res;
}
private static String getTableName_update(String query) {
int from = "update".length() + 1;
int to = query.indexOf("set");
String res = query.substring(from, to);
return res.trim();
}
private static String getPara_update(String query) {
int from = query.indexOf("set") + "set".length();
int to = query.indexOf("where");
String res = query.substring(from, to);
return res.trim();
}
private static String get_Where(String query) {
int from = query.indexOf("where") + "where".length();
int to = query.length();
String res = query.substring(from, to);
return res.trim();
}
private static void do_update(String Para, String s_Where, String TableName) {
String[] where = s_Where.split("=");
String[] paras = Para.split(",");
try {
File directory = new File("");
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml"));
javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath();
String expresstion = "//Table[@Ten='" + TableName + "']";
Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE);
expresstion = "//Record[Col=" + where[1] + "]";
Node node_rec = get_record_update(where, doc);
Node node_col;
for (String string : paras) {
String[] s_val = string.split("=");
// expresstion = "//Col[@Ten='" + s_val[0].trim() + "']";
//// String ss="HoTen";
//// expresstion = "//Col[@Ten='" + ss + "']";
////
// node_col = (Node) xpath.evaluate(expresstion, node_rec, XPathConstants.NODE);
//
// // System.err.println(node_col.getNodeValue());
// node_col.setTextContent(s_val[1]);
//
NodeList list_col = node_rec.getChildNodes();
int n = list_col.getLength();
for (int i = 0; i < n; i++) {
String tam = null;
if (list_col.item(i).getNodeName() == "Col") {
tam = list_col.item(i).getAttributes().getNamedItem("Ten").getTextContent();
}
if (tam.contains(s_val[0].trim())) {
list_col.item(i).setTextContent(s_val[1]);
}
}
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (TransformerException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (XPathExpressionException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static Node get_record_update(String[] where, Document doc) {
Node res = null;
String tagname = where[0].trim();
NodeList nodelist = doc.getElementsByTagName("Col");
for (int i = 0; i < nodelist.getLength(); i++) {
String tam = nodelist.item(i).getTextContent().trim();
if (tam.contains(where[1])) {
res = nodelist.item(i);
break;
}
}
return res.getParentNode();
}
public enum QUERY {
SELECT,
INSERT,
UPDATE,
DELETE,
CREATE
}
public static QUERY getQuery(String s) {
QUERY res = null;
int kq = 0;
String sub = s.substring(0, "delete".length()).toUpperCase();
if (sub.compareToIgnoreCase(QUERY.DELETE.toString()) == 0) {
res = QUERY.DELETE;
}
if (sub.compareToIgnoreCase(QUERY.UPDATE.toString()) == 0) {
res = QUERY.UPDATE;
}
if (sub.compareToIgnoreCase(QUERY.INSERT.toString()) == 0) {
res = QUERY.INSERT;
}
if (sub.compareToIgnoreCase(QUERY.SELECT.toString()) == 0) {
res = QUERY.SELECT;
}
if (sub.compareToIgnoreCase(QUERY.CREATE.toString()) == 0) {
res = QUERY.CREATE;
}
return res;
}
public static void main(String args[]) throws TransformerConfigurationException, TransformerException {
String query = "update HOCSINH set HoTen='Tuan Kiet', DTB=8.9 where MaHS=6";
QUERY res = getQuery(query);
switch (res) {
case INSERT:
insert_method(query);
break;
case UPDATE:
update_method(query);
break;
}
}
public static void update_method(String query) {
String tableName = getTableName_update(query);
String Para = getPara_update(query);
String s_Where = get_Where(query);
do_update(Para, s_Where, tableName);
}
public static void insert_method(String query) throws TransformerConfigurationException, TransformerException {
String tableName = getTableName(query);
String Para = getPara(query);
String ParaValues = getParavalues(query);
List<Col> list_col = getListCol(Para, ParaValues);
Record rc=new Record();
rc.add_rec_to_table(list_col, tableName);
System.err.println(getQuery(query));
}
private static String getTableName(String query) {
int from = query.indexOf("into") + "into".length();
int to = query.indexOf('(');
return query.substring(from, to).trim();
}
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/String_Utilities.java | Java | oos | 8,598 |
package XML;
import java.util.ArrayList;
import java.util.List;
public class Table {
public String TenBang;
public List<Record> ListRecord=new ArrayList<Record>();
public String TenKhoaChinh;
public String KieuKhoaChinh;
public Table(String TenBang,List<Record> ListRecord,String TenKhoaChinh, String KieuKhoaChinh)
{
this.TenBang=TenBang;
this.ListRecord=ListRecord;
this.TenKhoaChinh=TenKhoaChinh;
this.KieuKhoaChinh=KieuKhoaChinh;
}
public Table()
{
}
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/Table.java | Java | oos | 576 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author PC
*/
public class Condition {
public String TenBang;
public String[] Bien;
public String[] GiaTri;
public String[] DauSoSanh;
public String[] DauNoi;
public Condition()
{
}
public Condition(String TenBang,String[] Bien,String[] GiaTri,String[] DauSoSanh,String[] DauNoi)
{
this.TenBang=TenBang;
this.Bien=Bien;
this.GiaTri=GiaTri;
this.DauSoSanh=DauSoSanh;
this.DauNoi=DauNoi;
}
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/Condition.java | Java | oos | 649 |
package XML;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.xml.sax.SAXException;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author PC
*/
public class Form extends javax.swing.JFrame {
/**
* Creates new form Form
*/
public Form() {
initComponents();
}
/**
* 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.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
jScrollPane3 = new javax.swing.JScrollPane();
jTextArea3 = new javax.swing.JTextArea();
jScrollPane4 = new javax.swing.JScrollPane();
jTextArea4 = new javax.swing.JTextArea();
jButton2 = new javax.swing.JButton();
jScrollPane5 = new javax.swing.JScrollPane();
jTextArea5 = new javax.swing.JTextArea();
jScrollPane6 = new javax.swing.JScrollPane();
jTextArea6 = new javax.swing.JTextArea();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton1.setText("OK");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea2.setColumns(20);
jTextArea2.setRows(5);
jScrollPane2.setViewportView(jTextArea2);
jTextArea3.setColumns(20);
jTextArea3.setRows(5);
jScrollPane3.setViewportView(jTextArea3);
jTextArea4.setColumns(20);
jTextArea4.setRows(5);
jScrollPane4.setViewportView(jTextArea4);
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jTextArea5.setColumns(20);
jTextArea5.setRows(5);
jScrollPane5.setViewportView(jTextArea5);
jTextArea6.setColumns(20);
jTextArea6.setRows(5);
jScrollPane6.setViewportView(jTextArea6);
jButton3.setText("OK");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE)
.addComponent(jScrollPane4))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
.addComponent(jScrollPane6)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton3)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
.addComponent(jScrollPane3)
.addComponent(jScrollPane5))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)
.addComponent(jScrollPane4)
.addComponent(jScrollPane6))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String th="";
Table dl=new Table();
XuLyChuoi xl=new XuLyChuoi();
xl.TaoBang(jTextArea1.getText(), dl);
for(int i=0;i<dl.ListRecord.get(0).ListCol.size();i++)
{
th+=dl.ListRecord.get(0).ListCol.get(i).Ten+"\t"+dl.ListRecord.get(0).ListCol.get(i).Type+"\n";
}
th+=dl.TenKhoaChinh;
jTextArea2.setText(dl.TenBang+"\n\n"+th);
Create cr=new Create();
try {
cr.CreateTable(dl);
} catch (ParserConfigurationException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerConfigurationException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
Condition ct=new Condition();
XuLyChuoi xl=new XuLyChuoi();
xl.XoaDong(jTextArea3.getText(),ct);
String th=ct.TenBang+"\n";
for(int i=0;i<ct.Bien.length;i++)
{
th+=ct.Bien[i]+"\t"+ct.DauSoSanh[i]+"\t"+ct.GiaTri[i]+"\n";
}
for(int i=0;i<ct.DauNoi.length;i++)
{
th+=ct.DauNoi[i]+"\n";
}
jTextArea4.setText(th);
Delete dl=new Delete();
dl.DeleteRecord(ct);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
Attributes tt=new Attributes();
Condition ct=new Condition();
Condition dk=new Condition();
XuLyChuoi xl=new XuLyChuoi();
xl.ChonDong(jTextArea5.getText(),tt);
ct=tt.DieuKien1;
dk=tt.DieuKien2;
String th=new String();
if(ct!=null)
{
th = ct.TenBang + "\n";
for (int i = 0; i < ct.Bien.length; i++) {
th += ct.Bien[i] + "\t" + ct.DauSoSanh[i] + "\t" + ct.GiaTri[i] + "\n";
}
for (int i = 0; i < ct.DauNoi.length; i++) {
th += ct.DauNoi[i] + "\n";
}
}
if(dk!=null)
{
th = dk.TenBang + "\n";
for (int i = 0; i < dk.Bien.length; i++) {
th += dk.Bien[i] + "\t" + dk.DauSoSanh[i] + "\t" + dk.GiaTri[i] + "\n";
}
for (int i = 0; i < dk.DauNoi.length; i++) {
th += dk.DauNoi[i] + "\n";
}
}
jTextArea6.setText(th);
Select sl=new Select();
sl.SelectRecord(tt,null);
}//GEN-LAST:event_jButton3ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus 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 {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Form().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JTextArea jTextArea3;
private javax.swing.JTextArea jTextArea4;
private javax.swing.JTextArea jTextArea5;
private javax.swing.JTextArea jTextArea6;
// End of variables declaration//GEN-END:variables
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/Form.java | Java | oos | 11,912 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.Serializable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
*
* @author PC
*/
class Col implements Serializable{
public String Ten;
public String Type;
public String Value;
public Col()
{
}
void append_to_record(Node rec, Document doc) {
Element col = doc.createElement("Col");
col.setAttribute("Ten", this.Ten);
col.setAttribute("Type", this.Type);
col.setTextContent(this.Value);
rec.appendChild(col);
System.out.println("added a record");
}
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/Col.java | Java | oos | 810 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
*
* @author PC
*/
public class Record implements Serializable{
public List<Col> ListCol=new ArrayList<Col>();
public Record()
{
}
public static void add_rec_to_table(List<Col> list_col, String TableName) throws TransformerConfigurationException, TransformerException {
try {
File directory = new File("");
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml"));
javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath();
String expresstion = "//Table[@Ten='" + TableName + "']";
Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE);
Element e_rec = doc.createElement("Record");
node_tab.appendChild(e_rec);
for (Col col : list_col) {
col.append_to_record(e_rec, doc);
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (XPathExpressionException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/Record.java | Java | oos | 3,143 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author PC
*/
public class Attributes
{
public String Bang1;
public String Bang2;
public String[] ThuocTinh1;
public String[] ThuocTinh2;
public Condition DieuKien1;
public Condition DieuKien2;
public String BienNoi1;
public String BienNoi2;
public boolean SoSanh;
public Attributes()
{
}
public Attributes(String Bang1, String Bang2, String[] ThuocTinh1, String[] ThuocTinh2, Condition DieuKien1, Condition DieuKien2, String BienNoi1, String BienNoi2, boolean SoSanh)
{
this.Bang1=Bang1;
this.Bang2=Bang2;
this.ThuocTinh1=ThuocTinh1;
this.ThuocTinh2=ThuocTinh2;
this.DieuKien1=DieuKien1;
this.DieuKien2=DieuKien2;
this.BienNoi1=BienNoi1;
this.BienNoi2=BienNoi2;
this.SoSanh=SoSanh;
}
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/Attributes.java | Java | oos | 1,051 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
*
* @author PC
*/
public class Create {
public void CreateTable(Table dl) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException {
File directory = new File("");
String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(filepath);
Element database=doc.getDocumentElement();
Element table=doc.createElement("Table");
table.setAttribute("Ten", dl.TenBang);
//table.setAttribute("pk", dl.TenKhoaChinh);
Element record =doc.createElement("Record");
Element[] col=new Element[dl.ListRecord.get(0).ListCol.size()];
for (int i = 0; i < dl.ListRecord.get(0).ListCol.size(); i++)
{
col[i]=doc.createElement("Col");
col[i].setAttribute("Ten", dl.ListRecord.get(0).ListCol.get(i).Ten);
col[i].setAttribute("Type", dl.ListRecord.get(0).ListCol.get(i).Type);
/*
if(dl.ListRecord.get(0).ListCol.get(i).Ten.compareTo(dl.TenKhoaChinh)==0)
col[i].setAttribute("PK", "true");
else
col[i].setAttribute("PK", "false");
*/
record.appendChild(col[i]);
}
table.appendChild(record);
database.appendChild(table);
TransformerFactory tff = TransformerFactory.newInstance();
Transformer transformer = tff.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource xmlSource = new DOMSource(doc);
StreamResult outputTarget = new StreamResult(filepath);
transformer.transform(xmlSource, outputTarget);
}
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/Create.java | Java | oos | 2,565 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author PC
*/
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Delete {
public void DeleteRecord(Condition ct) {
try {
File directory = new File("");
String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(filepath);
XPathFactory xfactory = XPathFactory.newInstance();
javax.xml.xpath.XPath xpath = xfactory.newXPath();
String reg="//Table[@Ten='"+ct.TenBang+"']/Record[Col[";
for (int i = 0; i < ct.Bien.length - 1; i++) {
reg += "@Ten='" + ct.Bien[i] + "' and ." + ct.DauSoSanh[i] + "'" + ct.GiaTri[i] + "' " + ct.DauNoi[i] + " ";
}
reg += "@Ten='" + ct.Bien[ct.Bien.length - 1] + "' and ." + ct.DauSoSanh[ct.Bien.length - 1] + "'" + ct.GiaTri[ct.Bien.length - 1] + "']]";
System.out.println(reg);
XPathExpression expr = xpath.compile(reg);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
Node item=nodes.item(i);
item.getParentNode().removeChild(item);
}
TransformerFactory tff = TransformerFactory.newInstance();
Transformer transformer = tff.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource xmlSource = new DOMSource(doc);
StreamResult outputTarget = new StreamResult(filepath);
transformer.transform(xmlSource, outputTarget);
} catch (Exception ex) {
}
}
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/Delete.java | Java | oos | 2,664 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author PC
*/
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Select {
public void SelectRecord(Attributes tt, Table tb) {
try {
File directory = new File("");
String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(filepath);
XPathFactory xfactory = XPathFactory.newInstance();
javax.xml.xpath.XPath xpath = xfactory.newXPath();
String reg1 = new String();
String reg2 = new String();
if (tt.DieuKien1 != null) {
reg1 = "//Table[@Ten='" + tt.DieuKien1.TenBang + "']/Record[Col[";
for (int i = 0; i < tt.DieuKien1.Bien.length - 1; i++) {
reg1 += "@Ten='" + tt.DieuKien1.Bien[i] + "' and ." + tt.DieuKien1.DauSoSanh[i] + "'" + tt.DieuKien1.GiaTri[i] + "' " + tt.DieuKien1.DauNoi[i] + " ";
}
reg1 += "@Ten='" + tt.DieuKien1.Bien[tt.DieuKien1.Bien.length - 1] + "' and ." + tt.DieuKien1.DauSoSanh[tt.DieuKien1.Bien.length - 1] + "'" + tt.DieuKien1.GiaTri[tt.DieuKien1.Bien.length - 1] + "']]";
}
if (tt.DieuKien2 != null) {
reg2 = "//Table[@Ten='" + tt.DieuKien2.TenBang + "']/Record[Col[";
for (int i = 0; i < tt.DieuKien2.Bien.length - 1; i++) {
reg2 += "@Ten='" + tt.DieuKien2.Bien[i] + "' and ." + tt.DieuKien2.DauSoSanh[i] + "'" + tt.DieuKien2.GiaTri[i] + "' " + tt.DieuKien2.DauNoi[i] + " ";
}
reg2 += "@Ten='" + tt.DieuKien2.Bien[tt.DieuKien2.Bien.length - 1] + "' and ." + tt.DieuKien2.DauSoSanh[tt.DieuKien2.Bien.length - 1] + "'" + tt.DieuKien2.GiaTri[tt.DieuKien2.Bien.length - 1] + "']]";
}
System.out.println(reg1);
System.out.println(reg2);
String rx = new String();
String rx1 = new String();
String rx2 = new String();
if (tt.Bang2 == null && tt.DieuKien2 == null) {
if (tt.DieuKien1 == null)//Khong where
{
rx = "//Table[@Ten='" + tt.Bang1 + "']/Record";
XPathExpression expr = xpath.compile(rx);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
NodeList nl = nodes.item(i).getChildNodes();
for (int j = 0; j < nl.getLength(); j++)//chon ra Col
{
Node it = nl.item(j);
if (it.getNodeType() == Node.ELEMENT_NODE) {
for (int k = 0; k < tt.ThuocTinh1.length; k++) {
if (it.getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[k]) == 0) {
System.out.println(nl.item(j).getTextContent());
}
}
}
}
}
} else//Co where khong long khong ket
{
rx = "//Table[@Ten='" + tt.DieuKien1.TenBang + "']/Record[Col[";
for (int i = 0; i < tt.DieuKien1.Bien.length - 1; i++) {
rx += "@Ten='" + tt.DieuKien1.Bien[i] + "' and ." + tt.DieuKien1.DauSoSanh[i] + "'" + tt.DieuKien1.GiaTri[i] + "' " + tt.DieuKien1.DauNoi[i] + " ";
}
rx += "@Ten='" + tt.DieuKien1.Bien[tt.DieuKien1.Bien.length - 1] + "' and ." + tt.DieuKien1.DauSoSanh[tt.DieuKien1.Bien.length - 1] + "'" + tt.DieuKien1.GiaTri[tt.DieuKien1.Bien.length - 1] + "']]";
XPathExpression expr = xpath.compile(rx);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
NodeList nl = nodes.item(i).getChildNodes();
for (int j = 0; j < nl.getLength(); j++)//chon ra Col
{
Node it = nl.item(j);
if (it.getNodeType() == Node.ELEMENT_NODE) {
for (int k = 0; k < tt.ThuocTinh1.length; k++) {
if (it.getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[k]) == 0) {
System.out.println(nl.item(j).getTextContent());
}
}
}
}
}
}
} else//tt.Bang2!=null || tt.DieuKien2!=null
{
if (tt.DieuKien1 == null) {
if (tt.DieuKien2 == null)//Ket khong long
{
rx1 = "//Table[@Ten='" + tt.Bang1 + "']/Record/Col[@Ten='" + tt.BienNoi1 + "']";
rx2 = "//Table[@Ten='" + tt.Bang2 + "']/Record/Col[@Ten='" + tt.BienNoi2 + "']";
XPathExpression expr1 = xpath.compile(rx1);
Object result1 = expr1.evaluate(doc, XPathConstants.NODESET);
NodeList nodes1 = (NodeList) result1;
XPathExpression expr2 = xpath.compile(rx2);
Object result2 = expr2.evaluate(doc, XPathConstants.NODESET);
NodeList nodes2 = (NodeList) result2;
for (int i = 0; i < nodes1.getLength(); i++)
{
Node i1 = nodes1.item(i);
for (int j = 0; j < nodes2.getLength(); j++)
{
Node i2 = nodes2.item(j);
if (i1.getTextContent().compareTo(i2.getTextContent()) == 0)
{
NodeList pr1 = i1.getParentNode().getChildNodes();
for (int l = 0; l < pr1.getLength(); l++)
{
if(pr1.item(l).getNodeType()==Node.ELEMENT_NODE)
{
for (int m = 0; m < tt.ThuocTinh1.length; m++)
{
if(pr1.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[m])==0)
System.out.println(pr1.item(l).getTextContent());
}
}
}
NodeList pr2 = i2.getParentNode().getChildNodes();
for (int l = 0; l < pr2.getLength(); l++)
{
if(pr2.item(l).getNodeType()==Node.ELEMENT_NODE)
{
for (int m = 0; m < tt.ThuocTinh2.length; m++)
{
if(pr2.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh2[m])==0)
System.out.println(pr2.item(l).getTextContent());
}
}
}
}
}
}
} else {
if (tt.Bang2 != null)//Long khong ket
{
//Chon Col
rx1="//Table[@Ten='" + tt.Bang1 + "']/Record/Col[@Ten='"+tt.BienNoi1+"']";
XPathExpression expr1 = xpath.compile(rx1);
Object result1 = expr1.evaluate(doc, XPathConstants.NODESET);
NodeList nodes1 = (NodeList) result1;
//Chon Record
rx2 = "//Table[@Ten='" + tt.DieuKien2.TenBang + "']/Record[Col[";
for (int i = 0; i < tt.DieuKien2.Bien.length - 1; i++) {
rx2 += "@Ten='" + tt.DieuKien2.Bien[i] + "' and ." + tt.DieuKien2.DauSoSanh[i] + "'" + tt.DieuKien2.GiaTri[i] + "' " + tt.DieuKien2.DauNoi[i] + " ";
}
rx2 += "@Ten='" + tt.DieuKien2.Bien[tt.DieuKien2.Bien.length - 1] + "' and ." + tt.DieuKien2.DauSoSanh[tt.DieuKien2.Bien.length - 1] + "'" + tt.DieuKien2.GiaTri[tt.DieuKien2.Bien.length - 1] + "']]";
XPathExpression expr2 = xpath.compile(rx2);
Object result2 = expr2.evaluate(doc, XPathConstants.NODESET);
NodeList nodes2 = (NodeList) result2;
for (int i = 0; i < nodes2.getLength(); i++)
{
NodeList nl2 = nodes2.item(i).getChildNodes();
for (int j = 0; j < nl2.getLength(); j++)//chon ra Col
{
Node it2 = nl2.item(j);
if (it2.getNodeType() == Node.ELEMENT_NODE)
{
if (it2.getAttributes().item(0).getNodeValue().compareTo(tt.BienNoi2) == 0)
{
if(tt.SoSanh==true)//in
{
for (int k = 0; k < nodes1.getLength(); k++)
{
if(nodes1.item(k).getTextContent().equals(it2.getTextContent()))
{
NodeList pr1 = nodes1.item(k).getParentNode().getChildNodes();
for (int l = 0; l < pr1.getLength(); l++)
{
if(pr1.item(l).getNodeType()==Node.ELEMENT_NODE)
{
for (int m = 0; m < tt.ThuocTinh1.length; m++)
{
if(pr1.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[m])==0)
System.out.println(pr1.item(l).getTextContent());
}
}
}
}
}
}
else//not in
{
for (int k = 0; k < nodes1.getLength(); k++)
{
if(!nodes1.item(k).getTextContent().equals(it2.getTextContent()))
{
NodeList pr1 = nodes1.item(k).getParentNode().getChildNodes();
for (int l = 0; l < pr1.getLength(); l++)
{
if(pr1.item(l).getNodeType()==Node.ELEMENT_NODE)
{
for (int m = 0; m < tt.ThuocTinh1.length; m++)
{
if(pr1.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[m])==0)
System.out.println(pr1.item(l).getTextContent());
}
}
}
}
}
}
}
}
}
}
}
}
}
}
} catch (Exception ex) {
}
}
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/Select.java | Java | oos | 14,947 |
package XML;
/*
* To change this template, choose Tools | Templates and open the template in
* the editor.
*/
/**
*
* @author PC
*/
import java.lang.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class XuLyChuoi {
public String XoaMoiKhoangTrang(String chuoi) {
return chuoi.replaceAll("\\s", "");
}
public void TaoBang(String chuoi, Table dl) {
String[] h = chuoi.split("\\(");
String c1 = XoaMoiKhoangTrang(h[0]);
String ct = c1.substring(0, 11);
ct = ct.toLowerCase();
if (ct.contains("createtable")) {
dl.TenBang = c1.substring(11, c1.length());
}
String c2 = XoaMoiKhoangTrang(h[1]);
Record rc=new Record();
if (c2.contains("primarykey"))
{
c2 = c2.substring(0, c2.length() - 1);
String[] tt = c2.split(",");
for (int i = 0; i < tt.length - 1; i++)
{
if (tt[i].contains("int")) {
Col temp=new Col();
temp.Type = "int";
temp.Ten = tt[i].substring(0, tt[i].length() - 3);
temp.Value=new String();
rc.ListCol.add(temp);
}
if (tt[i].contains("varchar"))
{
Col temp=new Col();
temp.Type = "string";
temp.Ten = tt[i].substring(0, tt[i].length() - 7);
temp.Value=new String();
rc.ListCol.add(temp);
}
}
h[2] = XoaMoiKhoangTrang(h[2]);
dl.TenKhoaChinh = h[2].substring(0, h[2].length() - 2);
} else {
c2 = c2.substring(0, c2.length() - 1);
String[] tt = c2.split(",");
for (int i = 0; i < tt.length; i++) {
if (tt[i].contains("int")) {
Col temp=new Col();
temp.Type = "int";
temp.Ten = tt[i].substring(0, tt[i].length() - 3);
temp.Value=new String();
rc.ListCol.add(temp);
}
if (tt[i].contains("varchar")) {
Col temp=new Col();
temp.Type = "string";
temp.Ten = tt[i].substring(0, tt[i].length() - 7);
temp.Value=new String();
rc.ListCol.add(temp);
}
}
dl.TenKhoaChinh = null;
}
dl.ListRecord.add(rc);
}
public void XoaDong(String chuoi, Condition ct) {
String regex = null;
if (chuoi.contains("where")) {
regex = "where";
}
if (chuoi.contains("WHERE")) {
regex = "WHERE";
}
String[] h = chuoi.split(regex);
h[0] = XoaMoiKhoangTrang(h[0]);
ct.TenBang = h[0].substring(10);
char[] s = h[1].toCharArray();
List<String> d = new ArrayList<String>();
List<String> n = new ArrayList<String>();
for (int i = 0; i < s.length; i++) {
if (s[i] == '<' || s[i] == '=' || s[i] == '>') {
d.add(Character.toString(s[i]));
}
}
for (int i = 0; i < s.length - 4; i++) {
if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) {
n.add("and");
}
if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) {
n.add("or");
}
}
String tokens[] = null;
String splitPattern = "<|>|=|AND|OR|and|or";
Pattern p = Pattern.compile(splitPattern);
tokens = p.split(h[1].trim());
ct.Bien = new String[tokens.length / 2];
ct.GiaTri = new String[tokens.length / 2];
ct.DauNoi = new String[(tokens.length / 2) - 1];
for (int i = 0; i < tokens.length / 2; i++) {
ct.Bien[i] = tokens[2 * i].trim();
if (tokens[2 * i + 1].trim().contains("'")) {
ct.GiaTri[i] = tokens[2 * i + 1].trim().replaceAll("'", " ").trim();
} else {
ct.GiaTri[i] = tokens[2 * i + 1].trim();
}
}
ct.DauNoi = n.toArray(new String[0]);
ct.DauSoSanh = d.toArray(new String[0]);
}
public void ChonDong(String chuoi, Attributes tt) {
chuoi = chuoi.trim();
chuoi = chuoi.replaceAll("\n", " ");
chuoi = chuoi.replaceAll("\t", " ");
System.out.println(chuoi);
String tokens[] = null;
String splitPattern = "select |SELECT | FROM | from ";
if (!(chuoi.contains(" WHERE ") || chuoi.contains(" where "))) {
Pattern p = Pattern.compile(splitPattern);
tokens = p.split(chuoi);
tokens[1] = XoaMoiKhoangTrang(tokens[1]);
String c[] = tokens[1].split(",");
tt.Bang1 = tokens[2].trim();
tt.Bang2 = null;
tt.ThuocTinh1 = new String[c.length];
for (int i = 0; i < c.length; i++) {
tt.ThuocTinh1[i] = c[i];
}
} else {
splitPattern += "| WHERE | where ";
Pattern p = Pattern.compile(splitPattern);
tokens = p.split(chuoi);
if (tokens[2].contains(",")) //co 2 bang
{
tokens[2] = XoaMoiKhoangTrang(tokens[2]);
tt.Bang1 = tokens[2].substring(0, tokens[2].indexOf(",")).trim();
tt.Bang2 = tokens[2].substring(tokens[2].indexOf(",") + 1, tokens[2].length()).trim();
String[] at = tokens[1].split(",");
List<String> tt1 = new ArrayList<String>();
List<String> tt2 = new ArrayList<String>();
for (int i = 0; i < at.length; i++) {
if (at[i].contains(tt.Bang1)) {
tt1.add(at[i].substring(tt.Bang1.length() + 1));
}
if (at[i].contains(tt.Bang2)) {
tt2.add(at[i].substring(tt.Bang2.length() + 1));
}
}
tt.ThuocTinh1 = tt1.toArray(new String[0]);
tt.ThuocTinh2 = tt2.toArray(new String[0]);
System.out.println(tt.Bang1);
for (int i = 0; i < tt.ThuocTinh1.length; i++) {
System.out.println(tt.ThuocTinh1[i]);
}
System.out.println("\n" + tt.Bang2);
for (int i = 0; i < tt.ThuocTinh2.length; i++) {
System.out.println(tt.ThuocTinh2[i]);
}
String[] bn = tokens[3].split("=");
for (int i = 0; i < bn.length; i++) {
if (bn[i].contains(tt.Bang1)) {
tt.BienNoi1 = bn[i].substring(tt.Bang1.length() + 1);
}
if (bn[i].contains(tt.Bang2)) {
tt.BienNoi2 = bn[i].substring(tt.Bang2.length() + 1);
}
}
tt.SoSanh = true;
System.out.println(tt.BienNoi1);
System.out.println(tt.BienNoi2);
} else //Khong co 2 bang
{
tokens[1] = XoaMoiKhoangTrang(tokens[1]);
String c[] = tokens[1].split(",");
tt.Bang1 = tokens[2].trim();
tt.ThuocTinh1 = new String[c.length];
for (int i = 0; i < c.length; i++) {
tt.ThuocTinh1[i] = c[i];
}
if (tokens.length == 4) //Khong long nhau
{
tt.Bang2 = null;
for (int i = 0; i < tokens.length; i++) {
System.out.println(tokens[i]);
}
tt.DieuKien1=new Condition();
tt.DieuKien1.TenBang=tt.Bang1;
char[] s = tokens[3].toCharArray();
List<String> d = new ArrayList<String>();
List<String> n = new ArrayList<String>();
for (int i = 0; i < s.length; i++) {
if (s[i] == '<' || s[i] == '=' || s[i] == '>') {
d.add(Character.toString(s[i]));
}
}
for (int i = 0; i < s.length - 4; i++) {
if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) {
n.add("and");
}
if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) {
n.add("or");
}
}
String tks[] = null;
String sp = "<|>|=|AND|OR|and|or";
Pattern pt = Pattern.compile(sp);
tks = pt.split(tokens[3].trim());
tt.DieuKien1.Bien = new String[tks.length / 2];
tt.DieuKien1.GiaTri = new String[tks.length / 2];
tt.DieuKien1.DauNoi = new String[(tks.length / 2) - 1];
for (int i = 0; i < tks.length / 2; i++) {
tt.DieuKien1.Bien[i] = tks[2 * i].trim();
if (tks[2 * i + 1].trim().contains("'"))
{
tt.DieuKien1.GiaTri[i]=tks[2 * i + 1].trim().replaceAll("'", " ").trim();
} else {
tt.DieuKien1.GiaTri[i] = tks[2 * i + 1].trim();
}
}
tt.DieuKien1.DauNoi = n.toArray(new String[0]);
tt.DieuKien1.DauSoSanh = d.toArray(new String[0]);
} else //Long Nhau
{
tt.Bang2 = tokens[5].trim();
tt.BienNoi2 = tokens[4].trim();
System.out.println(tt.Bang2);
System.out.println(tt.BienNoi2);
for (int i = 0; i < tokens.length; i++) {
System.out.println(tokens[i]);
}
tokens[6]=tokens[6].trim().substring(0,tokens[6].length()-1);
tt.DieuKien2=new Condition();
tt.DieuKien2.TenBang=tt.Bang2;
char[] s = tokens[6].toCharArray();
List<String> d = new ArrayList<String>();
List<String> n = new ArrayList<String>();
for (int i = 0; i < s.length; i++) {
if (s[i] == '<' || s[i] == '=' || s[i] == '>') {
d.add(Character.toString(s[i]));
}
}
for (int i = 0; i < s.length - 4; i++) {
if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) {
n.add("and");
}
if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) {
n.add("or");
}
}
String tks[] = null;
String sp = "<|>|=|AND|OR|and|or";
Pattern pt = Pattern.compile(sp);
tks = pt.split(tokens[6].trim());
tt.DieuKien2.Bien = new String[tks.length / 2];
tt.DieuKien2.GiaTri = new String[tks.length / 2];
tt.DieuKien2.DauNoi = new String[(tks.length / 2) - 1];
for (int i = 0; i < tks.length / 2; i++) {
tt.DieuKien2.Bien[i] = tks[2 * i].trim();
if (tks[2 * i + 1].trim().contains("'"))
{
tt.DieuKien2.GiaTri[i] = tks[2 * i + 1].trim().replaceAll("'", " ").trim();
} else {
tt.DieuKien2.GiaTri[i] = tks[2 * i + 1].trim();
}
}
tt.DieuKien2.DauNoi = n.toArray(new String[0]);
tt.DieuKien2.DauSoSanh = d.toArray(new String[0]);
tokens[3]=tokens[3].trim();
tt.BienNoi1=tokens[3].substring(0,tokens[3].indexOf(" "));
if(tokens[3].contains(" not ") || tokens[3].contains(" NOT "))
tt.SoSanh=false;
else
tt.SoSanh=true;
}
}
}
}
}
| 0812005-java | trunk/Java/java-project-2008/src/XML/XuLyChuoi.java | Java | oos | 13,377 |
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author TanAnh
*/
public class Parentheses {
void display(String s) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Parentheses.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(s);
}
}
| 0812005-java | trunk/Java/java-project-2008/src/Parentheses.java | Java | oos | 480 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Demo {
public static void main(String args[]) {
Queue q = new Queue();
new Publisher(q);
new Consumer(q);
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/GiaoTiepThread/Demo.java | Java | oos | 301 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Queue {
int exchangeValue;
boolean busy = false;
synchronized int get() {
if (!busy) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(
"Get: InterruptedException");
}
}
System.out.println("Get: " + exchangeValue);
busy=false;
notify();
return exchangeValue;
}
synchronized void put(int exchangeValue) {
if (busy) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(
"Put: InterruptedException");
}
}
this.exchangeValue = exchangeValue;
busy = true;
System.out.println("Put: " + exchangeValue);
notify();
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/GiaoTiepThread/Queue.java | Java | oos | 1,013 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Publisher implements Runnable {
Queue q;
Publisher(Queue q) {
this.q = q;
new Thread(this, "Publisher").start();
}
public void run() {
for (int i = 0; i < 5; i++) {
q.put(i);
}
}
} | 0812005-java | trunk/Java/java-project-2008/DoAn/src/GiaoTiepThread/Publisher.java | Java | oos | 407 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Consumer implements Runnable {
Queue q;
Consumer(Queue q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
for (int i = 0; i < 5; i++) {
q.get();
}
}
} | 0812005-java | trunk/Java/java-project-2008/DoAn/src/GiaoTiepThread/Consumer.java | Java | oos | 403 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author TanAnh
*/
public class Demo {
public static void main(String args[]) throws InterruptedException{
Parentheses p3=new Parentheses();
MyThread name1=new MyThread(p3, "Bob");
MyThread name2=new MyThread(p3, "Mary");
MyThread name3=new MyThread(p3, "Anh");
MyThread name4=new MyThread(p3, "Luong");
name1.t.join();
name2.t.join();
name3.t.join();
name4.t.join();
System.out.println("Interupted");
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/Demo.java | Java | oos | 660 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author TanAnh
*/
public class MyThread implements Runnable {
String s1;
Parentheses p1;
Thread t;
public MyThread(Parentheses p2, String s2){
p1=p2;
s1=s2;
t=new Thread(this);
t.start();
}
@Override
public void run() {
synchronized(p1){
p1.display(s1);
}
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/MyThread.java | Java | oos | 492 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* @author TanAnh
*/
public class String_Utilities {
private static String getPara(String query) {
int from = query.indexOf('(');
int to = query.indexOf(')');
return query.substring(from + 1, to).trim();
}
private static String getParavalues(String query) {
query = query.toLowerCase();
int from = query.indexOf("values") + "values".length();
int to = query.length() - 1;
return query.substring(from + 1, to).trim();
}
private static List<Col> getListCol(String Para, String ParaValues) {
List<Col> res = new LinkedList<Col>();
String[] lisPara = Para.split(",");
String[] lisParaValues = ParaValues.split(",");
for (int i = 0; i < lisPara.length; i++) {
Col c = new Col();
if (lisParaValues[i].contains("'")) {
c.Type = "String";
} else {
c.Type = "int";
}
c.Ten = lisPara[i];
c.Value = lisParaValues[i];
res.add(c);
}
return res;
}
private static void add_rec_to_table(List<Col> list_col, String TableName) throws TransformerConfigurationException, TransformerException {
try {
String filePath = "c:\\Database.xml";
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(filePath));
javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath();
String expresstion = "//Table[@Ten='" + TableName + "']";
Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE);
Element e_rec = doc.createElement("Record");
node_tab.appendChild(e_rec);
for (Col col : list_col) {
col.append_to_record(e_rec, doc);
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filePath));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (XPathExpressionException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static String getTableName_update(String query) {
int from = "update".length() + 1;
int to = query.indexOf("set");
String res = query.substring(from, to);
return res.trim();
}
private static String getPara_update(String query) {
int from = query.indexOf("set") + "set".length();
int to = query.indexOf("where");
String res = query.substring(from, to);
return res.trim();
}
private static String get_Where(String query) {
int from = query.indexOf("where") + "where".length();
int to = query.length();
String res = query.substring(from, to);
return res.trim();
}
private static void do_update(String Para, String s_Where, String TableName) {
String[] where = s_Where.split("=");
String[] paras = Para.split(",");
try {
String filePath = "c:\\Database.xml";
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(filePath));
javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath();
String expresstion = "//Table[@Ten='" + TableName + "']";
Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE);
expresstion = "//Record[Col=" + where[1] + "]";
Node node_rec = get_record_update(where, doc);
Node node_col;
for (String string : paras) {
String[] s_val = string.split("=");
// expresstion = "//Col[@Ten='" + s_val[0].trim() + "']";
//// String ss="HoTen";
//// expresstion = "//Col[@Ten='" + ss + "']";
////
// node_col = (Node) xpath.evaluate(expresstion, node_rec, XPathConstants.NODE);
//
// // System.err.println(node_col.getNodeValue());
// node_col.setTextContent(s_val[1]);
//
NodeList list_col = node_rec.getChildNodes();
int n = list_col.getLength();
for (int i = 0; i < n; i++) {
String tam = null;
if (list_col.item(i).getNodeName() == "Col") {
tam = list_col.item(i).getAttributes().getNamedItem("Ten").getTextContent();
}
if (tam.contains(s_val[0].trim())) {
list_col.item(i).setTextContent(s_val[1]);
}
}
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filePath));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (TransformerException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (XPathExpressionException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static Node get_record_update(String[] where, Document doc) {
Node res = null;
String tagname = where[0].trim();
NodeList nodelist = doc.getElementsByTagName("Col");
for (int i = 0; i < nodelist.getLength(); i++) {
String tam = nodelist.item(i).getTextContent().trim();
if (tam.contains(where[1])) {
res = nodelist.item(i);
break;
}
}
return res.getParentNode();
}
static class Col {
public String Ten;
public String Type;
public String Value;
public Col() {
}
void append_to_record(Node rec, Document doc) {
Element col = doc.createElement("Col");
col.setAttribute("Ten", this.Ten);
col.setAttribute("Type", this.Type);
col.setTextContent(this.Value);
rec.appendChild(col);
System.out.println("added a record");
}
}
public enum QUERY {
SELECT,
INSERT,
UPDATE,
DELETE,
CREATE
}
public static QUERY getQuery(String s) {
QUERY res = null;
int kq = 0;
String sub = s.substring(0, "delete".length()).toUpperCase();
if (sub.compareToIgnoreCase(QUERY.DELETE.toString()) == 0) {
res = QUERY.DELETE;
}
if (sub.compareToIgnoreCase(QUERY.UPDATE.toString()) == 0) {
res = QUERY.UPDATE;
}
if (sub.compareToIgnoreCase(QUERY.INSERT.toString()) == 0) {
res = QUERY.INSERT;
}
if (sub.compareToIgnoreCase(QUERY.SELECT.toString()) == 0) {
res = QUERY.SELECT;
}
if (sub.compareToIgnoreCase(QUERY.CREATE.toString()) == 0) {
res = QUERY.CREATE;
}
return res;
}
public static void main(String args[]) throws TransformerConfigurationException, TransformerException {
String query = "update QLHS set HoTen='Tuan Kiet', DTB=8.9 where MaHS=6";
QUERY res = getQuery(query);
switch (res) {
case INSERT:
insert_method(query);
break;
case UPDATE:
update_method(query);
break;
}
}
private static void update_method(String query) {
String tableName = getTableName_update(query);
String Para = getPara_update(query);
String s_Where = get_Where(query);
do_update(Para, s_Where, tableName);
}
static void insert_method(String query) throws TransformerConfigurationException, TransformerException {
String tableName = getTableName(query);
String Para = getPara(query);
String ParaValues = getParavalues(query);
List<Col> list_col = getListCol(Para, ParaValues);
add_rec_to_table(list_col, tableName);
System.err.println(getQuery(query));
}
private static String getTableName(String query) {
int from = query.indexOf("into") + "into".length();
int to = query.indexOf('(');
return query.substring(from, to).trim();
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/XML/String_Utilities.java | Java | oos | 10,812 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author TanAnh
*/
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class NewClass {
public static void main(String argv[]) {
try {
File fXmlFile = new File("c:\\test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("-----------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("First Name : " + getTagValue("firstname", eElement));
System.out.println("Last Name : " + getTagValue("lastname", eElement));
System.out.println("Nick Name : " + getTagValue("nickname", eElement));
System.out.println("Salary : " + getTagValue("salary", eElement));
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/XML/NewClass.java | Java | oos | 1,964 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
/**
*
* @author TanAnh
*/
public class XPath {
public static void main(String args[]) {
String a;
try {
String filePath = "C:\\test.xml";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new File(filePath));
javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/company/staff";
Node widgetNode = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
NodeList listnod = widgetNode.getChildNodes();
for (int i = 0; i < listnod.getLength(); i++) {
a = listnod.item(i).getTextContent();
System.out.print("-" + a);
}
System.out.println();
System.out.println("----------------");
expression = "nickname";
Node newnode = (Node) xpath.evaluate(expression, widgetNode, XPathConstants.NODE);
System.err.println(newnode.getTextContent());
} catch (XPathExpressionException ex) {
} catch (SAXException ex) {
} catch (IOException ex) {
} catch (ParserConfigurationException ex) {
}
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/XML/XPath.java | Java | oos | 1,647 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.File;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
/**
*
* @author TanAnh
*/
public class WriteXMLFile {
public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
// Document doc = docBuilder.newDocument();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
// nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
// salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\test.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/XML/WriteXMLFile.java | Java | oos | 2,748 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import org.w3c.dom.NamedNodeMap;
public class ModifyXMLFile {
public static void main(String argv[]) {
try {
String filePath = "C:\\test.xml";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new File(filePath));
// Get the root element
Node company = doc.getFirstChild();
// Get the staff element , it may not working if tag has spaces, or
// whatever weird characters in front...it's better to use
// getElementsByTagName() to get it directly.
// Node staff = company.getFirstChild();
// Get the staff element by tag name directly
Node staff = doc.getElementsByTagName("staff").item(0);
// update staff attribute
NamedNodeMap attr = staff.getAttributes();
Node nodeAttr = attr.getNamedItem("id");
nodeAttr.setTextContent("2");
// append a new node to staff
Element age = doc.createElement("age");
age.appendChild(doc.createTextNode("28"));
staff.appendChild(age);
// loop the staff child node
NodeList list = staff.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
// get the salary element, and update the value
if ("salary".equals(node.getNodeName())) {
node.setTextContent("2000000");
}
//remove firstname
if ("firstname".equals(node.getNodeName())) {
staff.removeChild(node);
}
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filePath));
transformer.transform(source, result);
System.out.println("Done");
} catch (Exception pce) {
System.err.println("ERR"+pce.getMessage());
}
}
} | 0812005-java | trunk/Java/java-project-2008/DoAn/src/XML/ModifyXMLFile.java | Java | oos | 2,782 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author TanAnh
*/
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String args[]) {
try {
Socket s = new Socket("localhost", 2002);
OutputStream os = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
HocSinh to = new HocSinh(1, "Nguyen Tan Anh");
oos.writeObject(to);
oos.close();
os.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/SimpleClient.java | Java | oos | 677 |
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author TanAnh
*/
public class Parentheses {
void display(String s) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Parentheses.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(s);
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/Parentheses.java | Java | oos | 480 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TestSocket;
import java.io.*;
import java.net.*;
/**
*
* @author TanAnh
*/
public class SimpleServer {
public static void main(String args[]) {
int port = 2002;
try {
ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
InputStream is = s.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
HocSinh to = (HocSinh) ois.readObject();
if (to != null) {
System.out.println(to.id);
System.out.println(to.value);
}
is.close();
s.close();
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/TestSocket/SimpleServer.java | Java | oos | 863 |
package TestSocket;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.Serializable;
/**
*
* @author TanAnh
*/
class HocSinh implements Serializable {
int value;
String id;
public HocSinh(int v, String s) {
this.value = v;
this.id = s;
}
}
| 0812005-java | trunk/Java/java-project-2008/DoAn/src/TestSocket/HocSinh.java | Java | oos | 344 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Demo {
public static void main(String args[]) {
Queue q = new Queue();
new Publisher(q);
new Consumer(q);
}
}
| 0812005-java | trunk/Java/src/GiaoTiepThread/Demo.java | Java | oos | 301 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Queue {
int exchangeValue;
boolean busy = false;
synchronized int get() {
if (!busy) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(
"Get: InterruptedException");
}
}
System.out.println("Get: " + exchangeValue);
busy=false;
notify();
return exchangeValue;
}
synchronized void put(int exchangeValue) {
if (busy) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(
"Put: InterruptedException");
}
}
this.exchangeValue = exchangeValue;
busy = true;
System.out.println("Put: " + exchangeValue);
notify();
}
}
| 0812005-java | trunk/Java/src/GiaoTiepThread/Queue.java | Java | oos | 1,013 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Publisher implements Runnable {
Queue q;
Publisher(Queue q) {
this.q = q;
new Thread(this, "Publisher").start();
}
public void run() {
for (int i = 0; i < 5; i++) {
q.put(i);
}
}
} | 0812005-java | trunk/Java/src/GiaoTiepThread/Publisher.java | Java | oos | 407 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GiaoTiepThread;
/**
*
* @author TanAnh
*/
class Consumer implements Runnable {
Queue q;
Consumer(Queue q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
for (int i = 0; i < 5; i++) {
q.get();
}
}
} | 0812005-java | trunk/Java/src/GiaoTiepThread/Consumer.java | Java | oos | 403 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author TanAnh
*/
public class Demo {
public static void main(String args[]) throws InterruptedException{
Parentheses p3=new Parentheses();
MyThread name1=new MyThread(p3, "Bob");
MyThread name2=new MyThread(p3, "Mary");
MyThread name3=new MyThread(p3, "Anh");
MyThread name4=new MyThread(p3, "Luong");
name1.t.join();
name2.t.join();
name3.t.join();
name4.t.join();
System.out.println("Interupted");
}
}
| 0812005-java | trunk/Java/src/Demo.java | Java | oos | 633 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author TanAnh
*/
public class MyThread implements Runnable {
String s1;
Parentheses p1;
Thread t;
public MyThread(Parentheses p2, String s2){
p1=p2;
s1=s2;
t=new Thread(this);
t.start();
}
@Override
public void run() {
synchronized(p1){
p1.display(s1);
}
}
}
| 0812005-java | trunk/Java/src/MyThread.java | Java | oos | 492 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* @author TanAnh
*/
public class String_Utilities {
private static String getPara(String query) {
int from = query.indexOf('(');
int to = query.indexOf(')');
return query.substring(from + 1, to).trim();
}
private static String getParavalues(String query) {
query = query.toLowerCase();
int from = query.indexOf("values") + "values".length();
int to = query.length() - 1;
return query.substring(from + 1, to).trim();
}
private static List<Col> getListCol(String Para, String ParaValues) {
List<Col> res = new LinkedList<Col>();
String[] lisPara = Para.split(",");
String[] lisParaValues = ParaValues.split(",");
for (int i = 0; i < lisPara.length; i++) {
Col c = new Col();
if (lisParaValues[i].contains("'")) {
c.Type = "String";
} else {
c.Type = "int";
}
c.Ten = lisPara[i];
c.Value = lisParaValues[i];
res.add(c);
}
return res;
}
private static void add_rec_to_table(List<Col> list_col, String TableName) throws TransformerConfigurationException, TransformerException {
try {
File directory = new File("");
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml"));
javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath();
String expresstion = "//Table[@Ten='" + TableName + "']";
Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE);
Element e_rec = doc.createElement("Record");
node_tab.appendChild(e_rec);
for (Col col : list_col) {
col.append_to_record(e_rec, doc);
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (XPathExpressionException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static String getTableName_update(String query) {
int from = "update".length() + 1;
int to = query.indexOf("set");
String res = query.substring(from, to);
return res.trim();
}
private static String getPara_update(String query) {
int from = query.indexOf("set") + "set".length();
int to = query.indexOf("where");
String res = query.substring(from, to);
return res.trim();
}
private static String get_Where(String query) {
int from = query.indexOf("where") + "where".length();
int to = query.length();
String res = query.substring(from, to);
return res.trim();
}
private static void do_update(String Para, String s_Where, String TableName) {
String[] where = s_Where.split("=");
String[] paras = Para.split(",");
try {
File directory = new File("");
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml"));
javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath();
String expresstion = "//Table[@Ten='" + TableName + "']";
Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE);
expresstion = "//Record[Col=" + where[1] + "]";
Node node_rec = get_record_update(where, doc);
Node node_col;
for (String string : paras) {
String[] s_val = string.split("=");
// expresstion = "//Col[@Ten='" + s_val[0].trim() + "']";
//// String ss="HoTen";
//// expresstion = "//Col[@Ten='" + ss + "']";
////
// node_col = (Node) xpath.evaluate(expresstion, node_rec, XPathConstants.NODE);
//
// // System.err.println(node_col.getNodeValue());
// node_col.setTextContent(s_val[1]);
//
NodeList list_col = node_rec.getChildNodes();
int n = list_col.getLength();
for (int i = 0; i < n; i++) {
String tam = null;
if (list_col.item(i).getNodeName() == "Col") {
tam = list_col.item(i).getAttributes().getNamedItem("Ten").getTextContent();
}
if (tam.contains(s_val[0].trim())) {
list_col.item(i).setTextContent(s_val[1]);
}
}
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (TransformerException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (XPathExpressionException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static Node get_record_update(String[] where, Document doc) {
Node res = null;
String tagname = where[0].trim();
NodeList nodelist = doc.getElementsByTagName("Col");
for (int i = 0; i < nodelist.getLength(); i++) {
String tam = nodelist.item(i).getTextContent().trim();
if (tam.contains(where[1])) {
res = nodelist.item(i);
break;
}
}
return res.getParentNode();
}
static class Col {
public String Ten;
public String Type;
public String Value;
public Col() {
}
void append_to_record(Node rec, Document doc) {
Element col = doc.createElement("Col");
col.setAttribute("Ten", this.Ten);
col.setAttribute("Type", this.Type);
col.setTextContent(this.Value);
rec.appendChild(col);
System.out.println("added a record");
}
}
public enum QUERY {
SELECT,
INSERT,
UPDATE,
DELETE,
CREATE
}
public static QUERY getQuery(String s) {
QUERY res = null;
int kq = 0;
String sub = s.substring(0, "delete".length()).toUpperCase();
if (sub.compareToIgnoreCase(QUERY.DELETE.toString()) == 0) {
res = QUERY.DELETE;
}
if (sub.compareToIgnoreCase(QUERY.UPDATE.toString()) == 0) {
res = QUERY.UPDATE;
}
if (sub.compareToIgnoreCase(QUERY.INSERT.toString()) == 0) {
res = QUERY.INSERT;
}
if (sub.compareToIgnoreCase(QUERY.SELECT.toString()) == 0) {
res = QUERY.SELECT;
}
if (sub.compareToIgnoreCase(QUERY.CREATE.toString()) == 0) {
res = QUERY.CREATE;
}
return res;
}
public static void main(String args[]) throws TransformerConfigurationException, TransformerException {
String query = "update HOCSINH set HoTen='Tuan Kiet', DTB=8.9 where MaHS=6";
QUERY res = getQuery(query);
switch (res) {
case INSERT:
insert_method(query);
break;
case UPDATE:
update_method(query);
break;
}
}
private static void update_method(String query) {
String tableName = getTableName_update(query);
String Para = getPara_update(query);
String s_Where = get_Where(query);
do_update(Para, s_Where, tableName);
}
static void insert_method(String query) throws TransformerConfigurationException, TransformerException {
String tableName = getTableName(query);
String Para = getPara(query);
String ParaValues = getParavalues(query);
List<Col> list_col = getListCol(Para, ParaValues);
add_rec_to_table(list_col, tableName);
System.err.println(getQuery(query));
}
private static String getTableName(String query) {
int from = query.indexOf("into") + "into".length();
int to = query.indexOf('(');
return query.substring(from, to).trim();
}
}
| 0812005-java | trunk/Java/src/XML/String_Utilities.java | Java | oos | 10,993 |
package XML;
public class Table {
public String TenBang;
public String[] Kieu;
public String[] TenBien;
public String TenKhoaChinh;
public String KieuKhoaChinh;
public String[] GiaTri;
public Table(String TenBang, String[] Kieu, String[] TenBien, String TenKhoaChinh, String KieuKhoaChinh, String[] GiaTri)
{
this.TenBang=TenBang;
this.Kieu=Kieu;
this.TenBien=TenBien;
this.TenKhoaChinh=TenKhoaChinh;
this.KieuKhoaChinh=KieuKhoaChinh;
this.GiaTri=GiaTri;
}
public Table()
{
}
}
| 0812005-java | trunk/Java/src/XML/Table.java | Java | oos | 594 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.util.List;
/**
*
* @author PC
*/
public class Records{
public List<Record> records;
public Records()
{
}
public Records(List<Record> records)
{
this.records=records;
}
}
| 0812005-java | trunk/Java/src/XML/Records.java | Java | oos | 380 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author PC
*/
public class Condition {
public String TenBang;
public String[] Bien;
public String[] GiaTri;
public String[] DauSoSanh;
public String[] DauNoi;
public Condition()
{
}
public Condition(String TenBang,String[] Bien,String[] GiaTri,String[] DauSoSanh,String[] DauNoi)
{
this.TenBang=TenBang;
this.Bien=Bien;
this.GiaTri=GiaTri;
this.DauSoSanh=DauSoSanh;
this.DauNoi=DauNoi;
}
}
| 0812005-java | trunk/Java/src/XML/Condition.java | Java | oos | 649 |
package XML;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.xml.sax.SAXException;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author PC
*/
public class Form extends javax.swing.JFrame {
/**
* Creates new form Form
*/
public Form() {
initComponents();
}
/**
* 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.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
jScrollPane3 = new javax.swing.JScrollPane();
jTextArea3 = new javax.swing.JTextArea();
jScrollPane4 = new javax.swing.JScrollPane();
jTextArea4 = new javax.swing.JTextArea();
jButton2 = new javax.swing.JButton();
jScrollPane5 = new javax.swing.JScrollPane();
jTextArea5 = new javax.swing.JTextArea();
jScrollPane6 = new javax.swing.JScrollPane();
jTextArea6 = new javax.swing.JTextArea();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton1.setText("OK");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea2.setColumns(20);
jTextArea2.setRows(5);
jScrollPane2.setViewportView(jTextArea2);
jTextArea3.setColumns(20);
jTextArea3.setRows(5);
jScrollPane3.setViewportView(jTextArea3);
jTextArea4.setColumns(20);
jTextArea4.setRows(5);
jScrollPane4.setViewportView(jTextArea4);
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jTextArea5.setColumns(20);
jTextArea5.setRows(5);
jScrollPane5.setViewportView(jTextArea5);
jTextArea6.setColumns(20);
jTextArea6.setRows(5);
jScrollPane6.setViewportView(jTextArea6);
jButton3.setText("OK");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE)
.addComponent(jScrollPane4))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
.addComponent(jScrollPane6)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton3)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
.addComponent(jScrollPane3)
.addComponent(jScrollPane5))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)
.addComponent(jScrollPane4)
.addComponent(jScrollPane6))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String th="";
Table dl=new Table();
XuLyChuoi xl=new XuLyChuoi();
xl.TaoBang(jTextArea1.getText(), dl);
for(int i=0;i<dl.Kieu.length;i++)
{
th+=dl.TenBien[i]+"\t"+dl.Kieu[i]+"\n";
}
th+=dl.TenKhoaChinh;
jTextArea2.setText(dl.TenBang+"\n\n"+th);
Create cr=new Create();
try {
cr.CreateTable(dl);
} catch (ParserConfigurationException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerConfigurationException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
Condition ct=new Condition();
XuLyChuoi xl=new XuLyChuoi();
xl.XoaDong(jTextArea3.getText(),ct);
String th=ct.TenBang+"\n";
for(int i=0;i<ct.Bien.length;i++)
{
th+=ct.Bien[i]+"\t"+ct.DauSoSanh[i]+"\t"+ct.GiaTri[i]+"\n";
}
for(int i=0;i<ct.DauNoi.length;i++)
{
th+=ct.DauNoi[i]+"\n";
}
jTextArea4.setText(th);
Delete dl=new Delete();
dl.DeleteRecord(ct);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
Records rs=new Records();
Attributes tt=new Attributes();
Condition ct=new Condition();
Condition dk=new Condition();
XuLyChuoi xl=new XuLyChuoi();
xl.ChonDong(jTextArea5.getText(),tt);
ct=tt.DieuKien1;
dk=tt.DieuKien2;
String th=new String();
if(ct!=null)
{
th = ct.TenBang + "\n";
for (int i = 0; i < ct.Bien.length; i++) {
th += ct.Bien[i] + "\t" + ct.DauSoSanh[i] + "\t" + ct.GiaTri[i] + "\n";
}
for (int i = 0; i < ct.DauNoi.length; i++) {
th += ct.DauNoi[i] + "\n";
}
}
if(dk!=null)
{
th = dk.TenBang + "\n";
for (int i = 0; i < dk.Bien.length; i++) {
th += dk.Bien[i] + "\t" + dk.DauSoSanh[i] + "\t" + dk.GiaTri[i] + "\n";
}
for (int i = 0; i < dk.DauNoi.length; i++) {
th += dk.DauNoi[i] + "\n";
}
}
jTextArea6.setText(th);
Select sl=new Select();
sl.SelectRecord(tt,rs);
}//GEN-LAST:event_jButton3ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus 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 {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Form().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JTextArea jTextArea3;
private javax.swing.JTextArea jTextArea4;
private javax.swing.JTextArea jTextArea5;
private javax.swing.JTextArea jTextArea6;
// End of variables declaration//GEN-END:variables
}
| 0812005-java | trunk/Java/src/XML/Form.java | Java | oos | 11,858 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.util.List;
/**
*
* @author PC
*/
public class Record {
public List<String> record;
public Record()
{
}
public Record(List<String> record)
{
this.record=record;
}
}
| 0812005-java | trunk/Java/src/XML/Record.java | Java | oos | 370 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author PC
*/
public class Temp {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Delete dl=new Delete();
Condition ct=new Condition();
ct.TenBang="HOCSINH";
ct.Bien=new String[4];
ct.GiaTri=new String[4];
ct.DauSoSanh=new String[4];
ct.DauNoi=new String[3];
ct.Bien[0]="dtb";
ct.GiaTri[0]="0";
ct.DauSoSanh[0]=">";
ct.Bien[1]="dtb";
ct.GiaTri[1]="5";
ct.DauSoSanh[1]="<";
ct.Bien[2]="dtb";
ct.GiaTri[2]="7";
ct.DauSoSanh[2]=">";
ct.Bien[3]="dtb";
ct.GiaTri[3]="10";
ct.DauSoSanh[3]="<";
ct.DauNoi[0]="and";
ct.DauNoi[1]="or";
ct.DauNoi[2]="and";
dl.DeleteRecord(ct);
}
}
| 0812005-java | trunk/Java/src/XML/Temp.java | Java | oos | 986 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author TanAnh
*/
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class NewClass {
public static void main(String argv[]) {
try {
File fXmlFile = new File("c:\\test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("-----------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("First Name : " + getTagValue("firstname", eElement));
System.out.println("Last Name : " + getTagValue("lastname", eElement));
System.out.println("Nick Name : " + getTagValue("nickname", eElement));
System.out.println("Salary : " + getTagValue("salary", eElement));
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}
| 0812005-java | trunk/Java/src/XML/NewClass.java | Java | oos | 1,964 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author PC
*/
public class Attributes
{
public String Bang1;
public String Bang2;
public String[] ThuocTinh1;
public String[] ThuocTinh2;
public Condition DieuKien1;
public Condition DieuKien2;
public String BienNoi1;
public String BienNoi2;
public boolean SoSanh;
public Attributes()
{
}
public Attributes(String Bang1, String Bang2, String[] ThuocTinh1, String[] ThuocTinh2, Condition DieuKien1, Condition DieuKien2, String BienNoi1, String BienNoi2, boolean SoSanh)
{
this.Bang1=Bang1;
this.Bang2=Bang2;
this.ThuocTinh1=ThuocTinh1;
this.ThuocTinh2=ThuocTinh2;
this.DieuKien1=DieuKien1;
this.DieuKien2=DieuKien2;
this.BienNoi1=BienNoi1;
this.BienNoi2=BienNoi2;
this.SoSanh=SoSanh;
}
}
| 0812005-java | trunk/Java/src/XML/Attributes.java | Java | oos | 1,051 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
/**
*
* @author PC
*/
public class Create {
public void CreateTable(Table dl) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException {
File directory = new File("");
String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(filepath);
Element database=doc.getDocumentElement();
Element table=doc.createElement("Table");
table.setAttribute("Ten", dl.TenBang);
//table.setAttribute("pk", dl.TenKhoaChinh);
Element record =doc.createElement("Record");
Element[] col=new Element[dl.TenBien.length];
for (int i = 0; i < dl.TenBien.length; i++) {
col[i] = doc.createElement("Col");
col[i].setAttribute("Ten", dl.TenBien[i]);
col[i].setAttribute("Type", dl.Kieu[i]);
record.appendChild(col[i]);
}
table.appendChild(record);
database.appendChild(table);
TransformerFactory tff = TransformerFactory.newInstance();
Transformer transformer = tff.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource xmlSource = new DOMSource(doc);
StreamResult outputTarget = new StreamResult(filepath);
transformer.transform(xmlSource, outputTarget);
}
}
| 0812005-java | trunk/Java/src/XML/Create.java | Java | oos | 2,171 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author PC
*/
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Delete {
public void DeleteRecord(Condition ct) {
try {
File directory = new File("");
String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(filepath);
XPathFactory xfactory = XPathFactory.newInstance();
javax.xml.xpath.XPath xpath = xfactory.newXPath();
String reg="//Table[@Ten='"+ct.TenBang+"']/Record[Col[";
for (int i = 0; i < ct.Bien.length - 1; i++) {
reg += "@Ten='" + ct.Bien[i] + "' and ." + ct.DauSoSanh[i] + "'" + ct.GiaTri[i] + "' " + ct.DauNoi[i] + " ";
}
reg += "@Ten='" + ct.Bien[ct.Bien.length - 1] + "' and ." + ct.DauSoSanh[ct.Bien.length - 1] + "'" + ct.GiaTri[ct.Bien.length - 1] + "']]";
System.out.println(reg);
XPathExpression expr = xpath.compile(reg);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
Node item=nodes.item(i);
item.getParentNode().removeChild(item);
}
TransformerFactory tff = TransformerFactory.newInstance();
Transformer transformer = tff.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource xmlSource = new DOMSource(doc);
StreamResult outputTarget = new StreamResult(filepath);
transformer.transform(xmlSource, outputTarget);
} catch (Exception ex) {
}
}
}
| 0812005-java | trunk/Java/src/XML/Delete.java | Java | oos | 2,632 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
/**
*
* @author TanAnh
*/
public class XPath {
public static void main(String args[]) {
String a;
try {
String filePath = "C:\\file.xml";
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(filePath));
javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/company/staff";
Node widgetNode = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
NodeList listnod = widgetNode.getChildNodes();
for (int i = 0; i < listnod.getLength(); i++) {
a = listnod.item(i).getTextContent();
System.out.print("-" + a);
}
System.out.println();
System.out.println("----------------");
expression = "nickname";
Node newnode = (Node) xpath.evaluate(expression, widgetNode, XPathConstants.NODE);
System.err.println(newnode.getTextContent());
} catch (XPathExpressionException ex) {
Logger.getLogger(XPath.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(XPath.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(XPath.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(XPath.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| 0812005-java | trunk/Java/src/XML/XPath.java | Java | oos | 2,046 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author PC
*/
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Select {
public void SelectRecord(Attributes tt, Records rs) {
try {
rs = new Records();
File directory = new File("");
String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(filepath);
XPathFactory xfactory = XPathFactory.newInstance();
javax.xml.xpath.XPath xpath = xfactory.newXPath();
String reg1 = new String();
String reg2 = new String();
if (tt.DieuKien1 != null) {
reg1 = "//Table[@Ten='" + tt.DieuKien1.TenBang + "']/Record[Col[";
for (int i = 0; i < tt.DieuKien1.Bien.length - 1; i++) {
reg1 += "@Ten='" + tt.DieuKien1.Bien[i] + "' and ." + tt.DieuKien1.DauSoSanh[i] + "'" + tt.DieuKien1.GiaTri[i] + "' " + tt.DieuKien1.DauNoi[i] + " ";
}
reg1 += "@Ten='" + tt.DieuKien1.Bien[tt.DieuKien1.Bien.length - 1] + "' and ." + tt.DieuKien1.DauSoSanh[tt.DieuKien1.Bien.length - 1] + "'" + tt.DieuKien1.GiaTri[tt.DieuKien1.Bien.length - 1] + "']]";
}
if (tt.DieuKien2 != null) {
reg2 = "//Table[@Ten='" + tt.DieuKien2.TenBang + "']/Record[Col[";
for (int i = 0; i < tt.DieuKien2.Bien.length - 1; i++) {
reg2 += "@Ten='" + tt.DieuKien2.Bien[i] + "' and ." + tt.DieuKien2.DauSoSanh[i] + "'" + tt.DieuKien2.GiaTri[i] + "' " + tt.DieuKien2.DauNoi[i] + " ";
}
reg2 += "@Ten='" + tt.DieuKien2.Bien[tt.DieuKien2.Bien.length - 1] + "' and ." + tt.DieuKien2.DauSoSanh[tt.DieuKien2.Bien.length - 1] + "'" + tt.DieuKien2.GiaTri[tt.DieuKien2.Bien.length - 1] + "']]";
}
System.out.println(reg1);
System.out.println(reg2);
String rx = new String();
String rx1 = new String();
String rx2 = new String();
if (tt.Bang2 == null && tt.DieuKien2 == null) {
if (tt.DieuKien1 == null)//Khong where
{
rx = "//Table[@Ten='" + tt.Bang1 + "']/Record";
XPathExpression expr = xpath.compile(rx);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
NodeList nl = nodes.item(i).getChildNodes();
for (int j = 0; j < nl.getLength(); j++)//chon ra Col
{
Node it = nl.item(j);
if (it.getNodeType() == Node.ELEMENT_NODE) {
for (int k = 0; k < tt.ThuocTinh1.length; k++) {
if (it.getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[k]) == 0) {
System.out.println(nl.item(j).getTextContent());
}
}
}
}
}
} else//Co where khong long khong ket
{
rx = "//Table[@Ten='" + tt.DieuKien1.TenBang + "']/Record[Col[";
for (int i = 0; i < tt.DieuKien1.Bien.length - 1; i++) {
rx += "@Ten='" + tt.DieuKien1.Bien[i] + "' and ." + tt.DieuKien1.DauSoSanh[i] + "'" + tt.DieuKien1.GiaTri[i] + "' " + tt.DieuKien1.DauNoi[i] + " ";
}
rx += "@Ten='" + tt.DieuKien1.Bien[tt.DieuKien1.Bien.length - 1] + "' and ." + tt.DieuKien1.DauSoSanh[tt.DieuKien1.Bien.length - 1] + "'" + tt.DieuKien1.GiaTri[tt.DieuKien1.Bien.length - 1] + "']]";
XPathExpression expr = xpath.compile(rx);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
NodeList nl = nodes.item(i).getChildNodes();
for (int j = 0; j < nl.getLength(); j++)//chon ra Col
{
Node it = nl.item(j);
if (it.getNodeType() == Node.ELEMENT_NODE) {
for (int k = 0; k < tt.ThuocTinh1.length; k++) {
if (it.getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[k]) == 0) {
System.out.println(nl.item(j).getTextContent());
}
}
}
}
}
}
} else//tt.Bang2!=null || tt.DieuKien2!=null
{
if (tt.DieuKien1 == null) {
if (tt.DieuKien2 == null)//Ket khong long
{
rx1 = "//Table[@Ten='" + tt.Bang1 + "']/Record/Col[@Ten='" + tt.BienNoi1 + "']";
rx2 = "//Table[@Ten='" + tt.Bang2 + "']/Record/Col[@Ten='" + tt.BienNoi2 + "']";
XPathExpression expr1 = xpath.compile(rx1);
Object result1 = expr1.evaluate(doc, XPathConstants.NODESET);
NodeList nodes1 = (NodeList) result1;
XPathExpression expr2 = xpath.compile(rx2);
Object result2 = expr2.evaluate(doc, XPathConstants.NODESET);
NodeList nodes2 = (NodeList) result2;
List<String> giao = new ArrayList<String>();
for (int i = 0; i < nodes1.getLength(); i++)
{
Node i1 = nodes1.item(i);
for (int j = 0; j < nodes2.getLength(); j++)
{
Node i2 = nodes2.item(j);
if (i1.getTextContent().compareTo(i2.getTextContent()) == 0)
{
NodeList pr1 = i1.getParentNode().getChildNodes();
for (int l = 0; l < pr1.getLength(); l++)
{
if(pr1.item(l).getNodeType()==Node.ELEMENT_NODE)
{
for (int m = 0; m < tt.ThuocTinh1.length; m++)
{
if(pr1.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[m])==0)
System.out.println(pr1.item(l).getTextContent());
}
}
}
NodeList pr2 = i2.getParentNode().getChildNodes();
for (int l = 0; l < pr2.getLength(); l++)
{
if(pr2.item(l).getNodeType()==Node.ELEMENT_NODE)
{
for (int m = 0; m < tt.ThuocTinh2.length; m++)
{
if(pr2.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh2[m])==0)
System.out.println(pr2.item(l).getTextContent());
}
}
}
}
}
}
} else {
if (tt.Bang2 != null)//Long khong ket
{
//Chon Col
rx1="//Table[@Ten='" + tt.Bang1 + "']/Record/Col[@Ten='"+tt.BienNoi1+"']";
XPathExpression expr1 = xpath.compile(rx1);
Object result1 = expr1.evaluate(doc, XPathConstants.NODESET);
NodeList nodes1 = (NodeList) result1;
//Chon Record
rx2 = "//Table[@Ten='" + tt.DieuKien2.TenBang + "']/Record[Col[";
for (int i = 0; i < tt.DieuKien2.Bien.length - 1; i++) {
rx2 += "@Ten='" + tt.DieuKien2.Bien[i] + "' and ." + tt.DieuKien2.DauSoSanh[i] + "'" + tt.DieuKien2.GiaTri[i] + "' " + tt.DieuKien2.DauNoi[i] + " ";
}
rx2 += "@Ten='" + tt.DieuKien2.Bien[tt.DieuKien2.Bien.length - 1] + "' and ." + tt.DieuKien2.DauSoSanh[tt.DieuKien2.Bien.length - 1] + "'" + tt.DieuKien2.GiaTri[tt.DieuKien2.Bien.length - 1] + "']]";
XPathExpression expr2 = xpath.compile(rx2);
Object result2 = expr2.evaluate(doc, XPathConstants.NODESET);
NodeList nodes2 = (NodeList) result2;
for (int i = 0; i < nodes2.getLength(); i++)
{
NodeList nl2 = nodes2.item(i).getChildNodes();
for (int j = 0; j < nl2.getLength(); j++)//chon ra Col
{
Node it2 = nl2.item(j);
if (it2.getNodeType() == Node.ELEMENT_NODE)
{
if (it2.getAttributes().item(0).getNodeValue().compareTo(tt.BienNoi2) == 0)
{
System.out.println(nl2.item(j).getTextContent());
}
}
}
}
}
}
}
}
} catch (Exception ex) {
}
}
}
| 0812005-java | trunk/Java/src/XML/Select.java | Java | oos | 11,527 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
import java.io.File;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
/**
*
* @author TanAnh
*/
public class WriteXMLFile {
public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
// nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
// salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\file.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
| 0812005-java | trunk/Java/src/XML/WriteXMLFile.java | Java | oos | 2,680 |
package XML;
/*
* To change this template, choose Tools | Templates and open the template in
* the editor.
*/
/**
*
* @author PC
*/
import java.lang.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class XuLyChuoi {
public String XoaMoiKhoangTrang(String chuoi) {
return chuoi.replaceAll("\\s", "");
}
public void TaoBang(String chuoi, Table dl) {
String[] h = chuoi.split("\\(");
String c1 = XoaMoiKhoangTrang(h[0]);
String ct = c1.substring(0, 11);
ct = ct.toLowerCase();
if (ct.contains("createtable")) {
dl.TenBang = c1.substring(11, c1.length());
}
String c2 = XoaMoiKhoangTrang(h[1]);
if (c2.contains("primarykey")) {
c2 = c2.substring(0, c2.length() - 1);
String[] tt = c2.split(",");
dl.Kieu = new String[tt.length - 1];
dl.TenBien = new String[tt.length - 1];
for (int i = 0; i < tt.length - 1; i++) {
if (tt[i].contains("int")) {
dl.Kieu[i] = "int";
dl.TenBien[i] = tt[i].substring(0, tt[i].length() - 3);
}
if (tt[i].contains("varchar")) {
dl.Kieu[i] = "string";
dl.TenBien[i] = tt[i].substring(0, tt[i].length() - 7);
}
}
h[2] = XoaMoiKhoangTrang(h[2]);
dl.TenKhoaChinh = h[2].substring(0, h[2].length() - 2);
} else {
c2 = c2.substring(0, c2.length() - 1);
String[] tt = c2.split(",");
dl.Kieu = new String[tt.length];
dl.TenBien = new String[tt.length];
for (int i = 0; i < tt.length; i++) {
if (tt[i].contains("int")) {
dl.Kieu[i] = "int";
dl.TenBien[i] = tt[i].substring(0, tt[i].length() - 3);
}
if (tt[i].contains("varchar")) {
dl.Kieu[i] = "string";
dl.TenBien[i] = tt[i].substring(0, tt[i].length() - 7);
}
}
dl.TenKhoaChinh = null;
}
}
public void XoaDong(String chuoi, Condition ct) {
String regex = null;
if (chuoi.contains("where")) {
regex = "where";
}
if (chuoi.contains("WHERE")) {
regex = "WHERE";
}
String[] h = chuoi.split(regex);
h[0] = XoaMoiKhoangTrang(h[0]);
ct.TenBang = h[0].substring(10);
char[] s = h[1].toCharArray();
List<String> d = new ArrayList<String>();
List<String> n = new ArrayList<String>();
for (int i = 0; i < s.length; i++) {
if (s[i] == '<' || s[i] == '=' || s[i] == '>') {
d.add(Character.toString(s[i]));
}
}
for (int i = 0; i < s.length - 4; i++) {
if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) {
n.add("and");
}
if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) {
n.add("or");
}
}
String tokens[] = null;
String splitPattern = "<|>|=|AND|OR|and|or";
Pattern p = Pattern.compile(splitPattern);
tokens = p.split(h[1].trim());
ct.Bien = new String[tokens.length / 2];
ct.GiaTri = new String[tokens.length / 2];
ct.DauNoi = new String[(tokens.length / 2) - 1];
for (int i = 0; i < tokens.length / 2; i++) {
ct.Bien[i] = tokens[2 * i].trim();
if (tokens[2 * i + 1].trim().contains("'")) {
ct.GiaTri[i] = tokens[2 * i + 1].trim().replaceAll("'", " ").trim();
} else {
ct.GiaTri[i] = tokens[2 * i + 1].trim();
}
}
ct.DauNoi = n.toArray(new String[0]);
ct.DauSoSanh = d.toArray(new String[0]);
}
public void ChonDong(String chuoi, Attributes tt) {
chuoi = chuoi.trim();
chuoi = chuoi.replaceAll("\n", " ");
chuoi = chuoi.replaceAll("\t", " ");
System.out.println(chuoi);
String tokens[] = null;
String splitPattern = "select |SELECT | FROM | from ";
if (!(chuoi.contains(" WHERE ") || chuoi.contains(" where "))) {
Pattern p = Pattern.compile(splitPattern);
tokens = p.split(chuoi);
tokens[1] = XoaMoiKhoangTrang(tokens[1]);
String c[] = tokens[1].split(",");
tt.Bang1 = tokens[2].trim();
tt.Bang2 = null;
tt.ThuocTinh1 = new String[c.length];
for (int i = 0; i < c.length; i++) {
tt.ThuocTinh1[i] = c[i];
}
} else {
splitPattern += "| WHERE | where ";
Pattern p = Pattern.compile(splitPattern);
tokens = p.split(chuoi);
if (tokens[2].contains(",")) //co 2 bang
{
tokens[2] = XoaMoiKhoangTrang(tokens[2]);
tt.Bang1 = tokens[2].substring(0, tokens[2].indexOf(",")).trim();
tt.Bang2 = tokens[2].substring(tokens[2].indexOf(",") + 1, tokens[2].length()).trim();
String[] at = tokens[1].split(",");
List<String> tt1 = new ArrayList<String>();
List<String> tt2 = new ArrayList<String>();
for (int i = 0; i < at.length; i++) {
if (at[i].contains(tt.Bang1)) {
tt1.add(at[i].substring(tt.Bang1.length() + 1));
}
if (at[i].contains(tt.Bang2)) {
tt2.add(at[i].substring(tt.Bang2.length() + 1));
}
}
tt.ThuocTinh1 = tt1.toArray(new String[0]);
tt.ThuocTinh2 = tt2.toArray(new String[0]);
System.out.println(tt.Bang1);
for (int i = 0; i < tt.ThuocTinh1.length; i++) {
System.out.println(tt.ThuocTinh1[i]);
}
System.out.println("\n" + tt.Bang2);
for (int i = 0; i < tt.ThuocTinh2.length; i++) {
System.out.println(tt.ThuocTinh2[i]);
}
String[] bn = tokens[3].split("=");
for (int i = 0; i < bn.length; i++) {
if (bn[i].contains(tt.Bang1)) {
tt.BienNoi1 = bn[i].substring(tt.Bang1.length() + 1);
}
if (bn[i].contains(tt.Bang2)) {
tt.BienNoi2 = bn[i].substring(tt.Bang2.length() + 1);
}
}
tt.SoSanh = true;
System.out.println(tt.BienNoi1);
System.out.println(tt.BienNoi2);
} else //Khong co 2 bang
{
tokens[1] = XoaMoiKhoangTrang(tokens[1]);
String c[] = tokens[1].split(",");
tt.Bang1 = tokens[2].trim();
tt.ThuocTinh1 = new String[c.length];
for (int i = 0; i < c.length; i++) {
tt.ThuocTinh1[i] = c[i];
}
if (tokens.length == 4) //Khong long nhau
{
tt.Bang2 = null;
for (int i = 0; i < tokens.length; i++) {
System.out.println(tokens[i]);
}
tt.DieuKien1=new Condition();
tt.DieuKien1.TenBang=tt.Bang1;
char[] s = tokens[3].toCharArray();
List<String> d = new ArrayList<String>();
List<String> n = new ArrayList<String>();
for (int i = 0; i < s.length; i++) {
if (s[i] == '<' || s[i] == '=' || s[i] == '>') {
d.add(Character.toString(s[i]));
}
}
for (int i = 0; i < s.length - 4; i++) {
if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) {
n.add("and");
}
if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) {
n.add("or");
}
}
String tks[] = null;
String sp = "<|>|=|AND|OR|and|or";
Pattern pt = Pattern.compile(sp);
tks = pt.split(tokens[3].trim());
tt.DieuKien1.Bien = new String[tks.length / 2];
tt.DieuKien1.GiaTri = new String[tks.length / 2];
tt.DieuKien1.DauNoi = new String[(tks.length / 2) - 1];
for (int i = 0; i < tks.length / 2; i++) {
tt.DieuKien1.Bien[i] = tks[2 * i].trim();
if (tks[2 * i + 1].trim().contains("'"))
{
tt.DieuKien1.GiaTri[i]=tks[2 * i + 1].trim().replaceAll("'", " ").trim();
} else {
tt.DieuKien1.GiaTri[i] = tks[2 * i + 1].trim();
}
}
tt.DieuKien1.DauNoi = n.toArray(new String[0]);
tt.DieuKien1.DauSoSanh = d.toArray(new String[0]);
} else //Long Nhau
{
tt.Bang2 = tokens[5].trim();
tt.BienNoi2 = tokens[4].trim();
System.out.println(tt.Bang2);
System.out.println(tt.BienNoi2);
for (int i = 0; i < tokens.length; i++) {
System.out.println(tokens[i]);
}
tokens[6]=tokens[6].trim().substring(0,tokens[6].length()-1);
tt.DieuKien2=new Condition();
tt.DieuKien2.TenBang=tt.Bang2;
char[] s = tokens[6].toCharArray();
List<String> d = new ArrayList<String>();
List<String> n = new ArrayList<String>();
for (int i = 0; i < s.length; i++) {
if (s[i] == '<' || s[i] == '=' || s[i] == '>') {
d.add(Character.toString(s[i]));
}
}
for (int i = 0; i < s.length - 4; i++) {
if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) {
n.add("and");
}
if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) {
n.add("or");
}
}
String tks[] = null;
String sp = "<|>|=|AND|OR|and|or";
Pattern pt = Pattern.compile(sp);
tks = pt.split(tokens[6].trim());
tt.DieuKien2.Bien = new String[tks.length / 2];
tt.DieuKien2.GiaTri = new String[tks.length / 2];
tt.DieuKien2.DauNoi = new String[(tks.length / 2) - 1];
for (int i = 0; i < tks.length / 2; i++) {
tt.DieuKien2.Bien[i] = tks[2 * i].trim();
if (tks[2 * i + 1].trim().contains("'"))
{
tt.DieuKien2.GiaTri[i] = tks[2 * i + 1].trim().replaceAll("'", " ").trim();
} else {
tt.DieuKien2.GiaTri[i] = tks[2 * i + 1].trim();
}
}
tt.DieuKien2.DauNoi = n.toArray(new String[0]);
tt.DieuKien2.DauSoSanh = d.toArray(new String[0]);
tokens[3]=tokens[3].trim();
tt.BienNoi1=tokens[3].substring(0,tokens[3].indexOf(" "));
if(tokens[3].contains(" not ") || tokens[3].contains(" NOT "))
tt.SoSanh=false;
else
tt.SoSanh=true;
}
}
}
}
}
| 0812005-java | trunk/Java/src/XML/XuLyChuoi.java | Java | oos | 12,960 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package XML;
/**
*
* @author TanAnh
*/
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ModifyXMLFile {
public static void main(String argv[]) {
try {
String filepath = "c:\\file.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
// Get the root element
Node company = doc.getFirstChild();
// Get the staff element , it may not working if tag has spaces, or
// whatever weird characters in front...it's better to use
// getElementsByTagName() to get it directly.
// Node staff = company.getFirstChild();
// Get the staff element by tag name directly
Node staff = doc.getElementsByTagName("staff").item(0);
// update staff attribute
NamedNodeMap attr = staff.getAttributes();
Node nodeAttr = attr.getNamedItem("id");
nodeAttr.setTextContent("3");
// append a new node to staff
Element age = doc.createElement("age");
age.appendChild(doc.createTextNode("28"));
staff.appendChild(age);
// loop the staff child node
NodeList list = staff.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
// get the salary element, and update the value
if ("salary".equals(node.getNodeName())) {
node.setTextContent("2000000");
}
//remove firstname
if ("firstname".equals(node.getNodeName())) {
staff.removeChild(node);
}
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done");
} catch (ParserConfigurationException pce) {
} catch (TransformerException tfe) {
} catch (IOException ioe) {
} catch (SAXException sae) {
}
}
}
| 0812005-java | trunk/Java/src/XML/ModifyXMLFile.java | Java | oos | 3,121 |
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author TanAnh
*/
public class Parentheses {
void display(String s) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Parentheses.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(s);
}
}
| 0812005-java | trunk/Java/src/Parentheses.java | Java | oos | 480 |
using System.Collections.Generic;
using System.Windows.Forms;
using EnglishLearning.DataLayer;
using EnglishLearning.Entities;
namespace EnglishLearning.BusinessLayer
{
internal class WordBLL
{
private WordDAL dal = new WordDAL();
public static Dictionary<string, List<string>> GetDictionary()
{
return WordDAL.GetDictionary();
}
public bool Add(Words w)
{
return dal.Add(w);
}
public bool Edit(string oldWord, Words w)
{
return dal.Edit(oldWord, w);
}
public bool Remove(string word)
{
return dal.Remove(word);
}
public int[] CountWord()
{
return dal.CountWord();
}
public Words GetRandomWord()
{
return dal.GetRandomWord();
}
public void About()
{
string aboutMe = "NGUYỄN DUY HÙNG\t\n\t\n"
+ "DoB: 11/07/1993\t\n"
+ "Mobile: 01675 965 568\t\n\t\n"
+ "Yahoo: duyhung.1no2\t\n"
+ "Email: duyhung.1no2@gmail.com\t\n";
MessageBox.Show(aboutMe, "Thanks for using my software!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public void Copyright()
{
System.Diagnostics.Process.Start("http://365webz.com");
}
public void HelpMe()
{
System.Diagnostics.Process.Start("English learning - User Guide.chm");
}
}
} | 01301-english-learning | trunk/EnglishLearning/BusinessLogicLayer/WordBLL.cs | C# | oos | 1,609 |
using EnglishLearning.DataLayer;
using EnglishLearning.Entities;
namespace EnglishLearning.BusinessLayer
{
internal class ConfigBLL
{
private ConfigDAL dal = new ConfigDAL();
public static Config GetConfig()
{
return ConfigDAL.GetConfig();
}
public bool UpdateConfig(Config c)
{
return dal.UpdateConfig(c);
}
public void FirstRun()
{
dal.FirstRun();
}
}
} | 01301-english-learning | trunk/EnglishLearning/BusinessLogicLayer/ConfigBLL.cs | C# | oos | 514 |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EnglishLearning")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("EnglishLearning")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2b3626e5-9b35-4625-ac3c-7cc43d71ae3c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 01301-english-learning | trunk/EnglishLearning/Properties/AssemblyInfo.cs | C# | oos | 1,413 |
using System;
using System.Drawing;
using System.Windows.Forms;
namespace EnglishLearning
{
public partial class SplashScreen : Form
{
public SplashScreen()
{
InitializeComponent();
}
private void SplashScreen_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
SolidBrush sb = new SolidBrush(Color.FromArgb(75, 255, 255, 255));
Pen p = new Pen(Color.FromArgb(150, 255, 255, 255));
//g.FillRectangle(sb, 0, 0, this.Width, this.Height);
//g.DrawRectangle(p, 0, 0, this.Width - 1, this.Height - 1);
g.DrawImage(Image.FromFile("images//SplashScreen.png"), new Rectangle(0, 0, 520, 295));
}
protected override void OnPaintBackground(PaintEventArgs e)
{
}
private void SplashScreen_Load(object sender, EventArgs e)
{
// Show Option
int sreenWidth = Screen.PrimaryScreen.Bounds.Width;
int screenHeight = Screen.PrimaryScreen.Bounds.Height;
Point p = new Point(((sreenWidth / 2) - (this.Width / 2)), (((screenHeight / 2) - ((this.Height) / 2))));
this.Location = p;
// Timer
Timer timer = new Timer();
timer.Interval = 3000;
timer.Tick += new EventHandler(timer_Tick);
timer.Enabled = true;
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
this.Dispose();
}
}
} | 01301-english-learning | trunk/EnglishLearning/PresentationLayer/SplashScreen.cs | C# | oos | 1,609 |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using EnglishLearning.BusinessLayer;
using EnglishLearning.Entities;
using EnglishLearning.PresentationLayer;
using EnglishLearning.Utilities;
namespace EnglishLearning
{
public partial class MainForm : Form
{
#region Declare Varables
Dictionary<string, List<string>> dic;
GlobalKeyboardHook keyHook;
WordBLL bll = new WordBLL();
ConfigBLL configBll = new ConfigBLL();
Config config;
InfoForm infoForm;
RandomWordForm randomWordForm;
QuickTranslateForm quickForm;
public static Color mainColor, overColor, downColor;
SolidBrush sb;
Graphics g;
int numberShowBalloonTip = 0;
string imageLink = "";
string currentMode = "";
string clipBoard;
#endregion
#region Form Load
public MainForm()
{
InitializeComponent();
}
private void mainForm_Load(object sender, EventArgs e)
{
clipBoard = Clipboard.GetText();
// First run program -- create folder and database
if (!File.Exists(Directory.GetCurrentDirectory() + "\\WordsStore.db"))
{
configBll.FirstRun();
}
// Key Hook
keyHook = new GlobalKeyboardHook();
keyHook.KeyUp += new KeyEventHandler(keyHook_KeyUp);
keyHook.HookedKeys.Add(Keys.LControlKey);
keyHook.HookedKeys.Add(Keys.RControlKey);
keyHook.HookedKeys.Add(Keys.Control);
keyHook.HookedKeys.Add(Keys.M);
keyHook.HookedKeys.Add(Keys.F7);
keyHook.HookedKeys.Add(Keys.F8);
keyHook.HookedKeys.Add(Keys.C);
keyHook.hook();
// Load Dictionary
dic = WordBLL.GetDictionary();
LoadDicToListView(dic);
// Load Configuration
config = ConfigBLL.GetConfig();
// Get main color
mainColor = Color.FromArgb(config.ColorR, config.ColorG, config.ColorB);
downColor = Color.FromArgb(((int)(((byte)(mainColor.R)))), ((int)(((byte)(mainColor.G - 50)))), ((int)(((byte)(mainColor.B)))));
overColor = Color.FromArgb(((int)(((byte)(mainColor.R)))), ((int)(((byte)(mainColor.G - 30)))), ((int)(((byte)(mainColor.B)))));
PaintButton();
// Load Word from SQLite database to List View
LoadDicToListView(dic);
// Show Info Form
infoForm = new InfoForm();
ShowInfoForm();
// Show Random Word Form
randomWordForm = new RandomWordForm();
ShowRandomWordForm();
// Translate Form
quickForm = new QuickTranslateForm();
quickForm.ShowInTaskbar = false;
}
void keyHook_KeyUp(object sender, KeyEventArgs e)
{
// Show / Hide Main Form
if (e.KeyCode == Keys.F7)
{
if (this.ShowInTaskbar == false)
{
this.Show();
this.TopMost = true;
this.TopMost = false;
this.txtSearch.Focus();
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = true;
}
else
{
this.Hide();
this.ShowInTaskbar = false;
}
}
if (e.KeyCode == Keys.F8)
{
if (quickForm.ShowInTaskbar == false)
{
quickForm.Show();
quickForm.ShowInTaskbar = true;
}
else
{
quickForm.Hide();
quickForm.ShowInTaskbar = false;
}
}
}
#endregion
#region Form Paint
private void mainForm_Paint(object sender, PaintEventArgs e)
{
g = e.Graphics;
sb = new SolidBrush(mainColor);
// TOP PAINT
// Background
g.FillRectangle(sb, 0, 0, this.Width, 50);
// Glass
LinearGradientBrush lgb = new LinearGradientBrush(new Point(0, 0), new Point(0, 25), Color.FromArgb(100, 255, 255, 255), Color.Transparent);
g.FillRectangle(lgb, 0, 0, this.Width, 25);
// Logo
Image logo = Image.FromFile("images//logo.png");
g.DrawImage(logo, new Rectangle(15, 5, 165, 40));
// BOTTOM PAINT
g.FillRectangle(sb, 0, this.Height - 57, this.Width, 30);
// TEXT BOX SEARCH
g.DrawRectangle(Pens.Gray, txtSearch.Location.X - 1, txtSearch.Location.Y - 1, txtSearch.Width + picSearch.Width + 1, txtSearch.Height + 1);
// Draw Line middle Word & Meaning text box
Graphics g2 = translatePanel.CreateGraphics();
g2.DrawLine(Pens.DarkGray, new Point(txtWord.Location.X, txtWord.Location.Y + txtWord.Height), new Point(txtWord.Location.X + txtWord.Width - 1, txtWord.Location.Y + txtWord.Height));
//g.DrawLine(Pens.Black, new Point())
}
private void translatePanel_Paint(object sender, PaintEventArgs e)
{
g = e.Graphics;
sb = new SolidBrush(mainColor);
g.FillRectangle(sb, wordImage.Location.X, wordImage.Location.Y + 175, wordImage.Width, 30);
g.FillRectangle(sb, 0, translatePanel.Height - 30, translatePanel.Width, 30);
//g.FillRectangle(Brushes.Black, 25,25, pictureBox1.Width, 125);
}
void PaintButton()
{
foreach (Control ctr in this.Controls)
{
if (ctr is Button)
{
Button b = ctr as Button;
b.FlatAppearance.MouseDownBackColor = downColor;
b.FlatAppearance.MouseOverBackColor = overColor;
}
}
foreach (Control ctr in panel1.Controls)
{
if (ctr is Button)
{
Button b = ctr as Button;
b.FlatAppearance.MouseDownBackColor = downColor;
b.FlatAppearance.MouseOverBackColor = overColor;
}
}
foreach (Control ctr in translatePanel.Controls)
{
if (ctr is Button)
{
Button b = ctr as Button;
b.FlatAppearance.MouseDownBackColor = downColor;
b.FlatAppearance.MouseOverBackColor = overColor;
}
}
}
#endregion
#region Notify Icon
private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
if (numberShowBalloonTip == 0)
{
notify.ShowBalloonTip(1, "English learning is still running ...", "Double click tray icon to Open program.\t\nTo exit, click Exit Button. \t\n\t\n Click Here to disable this notify.", ToolTipIcon.Info);
//notify.BalloonTipClicked += new EventHandler(new Delegate(object sender, MouseEventArgs e) { numberShowBalloonTip++; }) ;
notify.BalloonTipClicked += new EventHandler(delegate(object sender2, EventArgs e2)
{
numberShowBalloonTip++;
});
}
this.Hide();
}
private void notify_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
}
private void showEnglishLearningToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Show();
}
private void configurationToolStripMenuItem_Click(object sender, EventArgs e)
{
Config();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
bll.About();
}
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
bll.HelpMe();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
notify.Dispose();
this.Dispose();
}
#endregion
#region Translate Place
// private void txtSearch_TextChanged(object sender, EventArgs e)
// {
// txtMeaning.Text = GoogleService.TranslateGoogle(txtWord.Text, "en", "vi");
// }
private void txtSearch_KeyUp(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Enter) & (!txtSearch.Text.Trim().Equals("")))
{
Translate(txtSearch.Text);
foreach (ListViewItem item in listWord.Items)
{
if (item.Text == txtSearch.Text)
{
item.Selected = true;
if(item.Index+10<listWord.Items.Count)
listWord.EnsureVisible(item.Index+10);
else
{
listWord.EnsureVisible(listWord.Items.Count-1);
}
break;
}
}
if (txtMeaning.Text.Trim().Equals(""))
{
txtMeaning.Text = GoogleService.TranslateGoogle(txtSearch.Text, "en", "vi");
if (!txtMeaning.Text.Trim().Equals("") && (!("\"" + txtSearch.Text + "\"").Equals(txtMeaning.Text)))
{
bll.Add(new Words(txtSearch.Text, txtMeaning.Text, (int)txtMark.Value, imageLink));
LoadDicToListView(dic);
}
}
}
}
private void txtMeaning_TextChanged(object sender, EventArgs e)
{
if (txtMeaning.Lines.Length > 7)
{
txtMeaning.ScrollBars = ScrollBars.Vertical;
}
else
{
txtMeaning.ScrollBars = ScrollBars.None;
}
}
private void txtWord_TextChanged(object sender, EventArgs e)
{
if (txtWord.Lines.Length > 7)
{
txtWord.ScrollBars = ScrollBars.Vertical;
}
else
{
txtWord.ScrollBars = ScrollBars.None;
}
}
private void listWord_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
txtSearch.Text = listWord.SelectedItems[0].Text;
Translate(listWord.SelectedItems[0].Text);
}
catch { }
}
private void btnChangeImage_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Image Files|*.bmp; *.jpg; *.png";
if (ofd.ShowDialog() == DialogResult.OK)
{
//
string file = Directory.GetCurrentDirectory() + "\\ImagesStore\\" + ofd.SafeFileName;
imageLink = "ImagesStore\\" + ofd.SafeFileName;
// Resize Image max size: 175x175px
Image img = Image.FromFile(ofd.FileName);
int w;
int h;
if (img.Width > img.Height)
{
w = 175;
h = img.Height / (img.Width / 175);
}
else
{
h = 175;
w = img.Width / (img.Height / 175);
}
Image im = new Bitmap(w, h);
Graphics g2 = Graphics.FromImage((Image)im);
g2.DrawImage(img, 0, 0, w, h);
try
{
im.Save(file);
}
catch { }
g2.Dispose();
// Set image
wordImage.Image = Image.FromFile(imageLink);
}
}
private void btnDeleteImage_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("You want to delete this image?", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
wordImage.Image = Image.FromFile("images//default_image.jpg");
try
{
//File.Delete()
}
catch { }
}
}
#region Main Button
private void btnAdd_Click(object sender, EventArgs e)
{
currentMode = "add";
EditMode();
ClearPanel();
}
private void btnEdit_Click(object sender, EventArgs e)
{
currentMode = "edit";
EditMode();
}
private void btnRemove_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you want to delete this word?", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
bll.Remove(txtWord.Text);
btnEdit.Enabled = false;
btnRemove.Enabled = false;
dic.Remove(txtWord.Text);
ClearPanel();
LoadDicToListView(dic);
}
}
private void btnOK_Click(object sender, EventArgs e)
{
switch (currentMode)
{
case "add":
if (CheckWord())
{
if (bll.Add(new Words(txtWord.Text, txtMeaning.Text, (int)txtMark.Value, imageLink)))
{
dic.Add(txtWord.Text, new List<string> { txtMeaning.Text, txtMark.Value.ToString(), imageLink });
LoadDicToListView(dic);
ViewMode();
imageLink = "";
}
}
break;
case "edit":
if (CheckWord())
{
if (bll.Edit(txtSearch.Text, new Words(txtWord.Text, txtMeaning.Text, (int)txtMark.Value, imageLink)))
{
dic.Remove(txtSearch.Text);
dic.Add(txtWord.Text, new List<string> { txtMeaning.Text, txtMark.Value.ToString(), imageLink });
LoadDicToListView(dic);
imageLink = "";
ViewMode();
}
}
break;
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
switch (currentMode)
{
case "add":
Translate(txtSearch.Text);
ViewMode();
btnEdit.Enabled = false;
btnRemove.Enabled = false;
txtSearch.Focus();
break;
case "edit":
Translate(txtSearch.Text);
ViewMode();
txtSearch.Focus();
break;
}
}
#endregion
#endregion
#region Other Buttons
private void btnConfig_Click(object sender, EventArgs e)
{
//bll.CloseConnection();
Config();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Dispose();
notify.Dispose();
}
private void btnCopyright_Click(object sender, EventArgs e)
{
bll.Copyright();
}
private void btnChooseColor_Click(object sender, EventArgs e)
{
//bll.CloseConnection();
ChooseColor();
downColor = Color.FromArgb(((int)(((byte)(mainColor.R)))), ((int)(((byte)(mainColor.G - 50)))), ((int)(((byte)(mainColor.B)))));
overColor = Color.FromArgb(((int)(((byte)(mainColor.R)))), ((int)(((byte)(mainColor.G - 30)))), ((int)(((byte)(mainColor.B)))));
PaintButton();
this.Hide();
this.Show();
}
private void btnAbout_Click(object sender, EventArgs e)
{
bll.About();
}
private void btnHelp_Click(object sender, EventArgs e)
{
bll.HelpMe();
}
#endregion
#region Functions
void LoadDicToListView(Dictionary<string, List<string>> dic)
{
listWord.Clear();
ListViewItem lvi;
foreach (var w in dic)
{
lvi = new ListViewItem(w.Key);
listWord.Items.Add(lvi);
}
}
void Translate(string word)
{
List<string> list = null;
try
{
list = dic[word];
}
catch { }
if (!txtMeaning.Text.Trim().Equals(""))
{
btnEdit.Enabled = true;
btnRemove.Enabled = true;
}
else
{
btnEdit.Enabled = false;
btnRemove.Enabled = false;
}
if (list != null)
{
txtWord.Text = word;
txtMeaning.Text = list[0];
txtMark.Value = Convert.ToInt32(list[1]);
try
{
if (!list[2].Equals(""))
{
wordImage.Image = Image.FromFile(list[2]);
imageLink = list[2];
}
else
{
wordImage.Image = Image.FromFile("images//default_image.jpg");
}
}
catch { }
}
else
{
ClearPanel();
txtWord.Text = txtSearch.Text;
}
}
void Config()
{
new ConfigForm().ShowDialog();
}
void ShowInfoForm()
{
infoForm.ShowInfoForm();
// Auto Close Form
System.Windows.Forms.Timer time = new System.Windows.Forms.Timer();
time.Interval = 10000;
time.Tick += new EventHandler(delegate(object sender2, EventArgs e2)
{
infoForm.Dispose();
});
time.Enabled = true;
time.Start();
}
void ShowRandomWordForm()
{
int srcWidth = Screen.PrimaryScreen.Bounds.Width;
int srcHeight = Screen.PrimaryScreen.Bounds.Height;
Point p = new Point(srcWidth - randomWordForm.Width, srcHeight-30-randomWordForm.Height);
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
int t = config.TimeShowWord * 60000;
timer.Interval = t;
timer.Enabled = true;
timer.Tick += new EventHandler(delegate(object sender, EventArgs e)
{
if(randomWordForm.Location != p)
{
if(randomWordForm.SetWord())
{
randomWordForm.ShowRandomWordForm();
config = ConfigBLL.GetConfig();
timer.Interval = config.TimeShowWord * 60000;
}
}
});
timer.Start();
}
void ChooseColor()
{
ColorDialog cd = new ColorDialog();
cd.AllowFullOpen = false;
if (cd.ShowDialog() == DialogResult.OK)
{
if(cd.Color != Color.White)
{
mainColor = cd.Color;
downColor = Color.FromArgb(((int)(((byte)(mainColor.R)))), ((int)(((byte)(mainColor.G - 50)))), ((int)(((byte)(mainColor.B)))));
overColor = Color.FromArgb(((int)(((byte)(mainColor.R)))), ((int)(((byte)(mainColor.G - 30)))), ((int)(((byte)(mainColor.B)))));
// Update to database
config.ColorR = mainColor.R;
config.ColorG = mainColor.G;
config.ColorB = mainColor.B;
configBll.UpdateConfig(config);
}
}
}
void ClearPanel()
{
txtWord.Text = "";
txtMeaning.Text = "";
txtMark.Value = 0;
imageLink = "";
wordImage.Image = Image.FromFile("images//default_image.jpg");
}
void ViewMode()
{
btnAdd.Enabled = true;
btnEdit.Enabled = true;
btnRemove.Enabled = true;
btnChangeImage.Enabled = false;
btnDeleteImage.Enabled = false;
txtWord.ReadOnly = true;
txtWord.BorderStyle = BorderStyle.None;
txtWord.Focus();
txtMeaning.ReadOnly = true;
txtMeaning.BorderStyle = BorderStyle.None;
txtMark.Enabled = false;
btnOK.Visible = false;
btnCancel.Visible = false;
}
void EditMode()
{
btnAdd.Enabled = false;
btnEdit.Enabled = false;
btnRemove.Enabled = false;
btnChangeImage.Enabled = true;
btnDeleteImage.Enabled = true;
txtWord.ReadOnly = false;
txtWord.BorderStyle = BorderStyle.FixedSingle;
txtWord.Focus();
txtMeaning.ReadOnly = false;
txtMeaning.BorderStyle = BorderStyle.FixedSingle;
txtMark.Enabled = true;
btnOK.Visible = true;
btnCancel.Visible = true;
}
bool CheckWord()
{
if (txtWord.Text.Trim().Equals("") | (txtMeaning.Text.Trim().Equals("")))
{
MessageBox.Show("Word or Meaning is not empty!");
return false;
}
else
{
return true;
}
}
#endregion
}
}
| 01301-english-learning | trunk/EnglishLearning/PresentationLayer/MainForm.cs | C# | oos | 23,284 |
using System;
using System.Windows.Forms;
using EnglishLearning.BusinessLayer;
using EnglishLearning.Entities;
namespace EnglishLearning.PresentationLayer
{
public partial class ConfigForm : Form
{
private ConfigBLL bll = new ConfigBLL();
private Config conf;
public ConfigForm()
{
InitializeComponent();
}
private void ConfigForm_Load(object sender, EventArgs e)
{
PaintButton();
conf = ConfigBLL.GetConfig();
txtTimeShowWord.Value = conf.TimeShowWord;
if (conf.OnStart == 1)
chkStart.Checked = true;
txtProxy.Text = conf.Proxy;
txtPort.Text = conf.ProxyPort.ToString();
txtUser.Text = conf.ProxyUser;
txtPassword.Text = conf.ProxyPass;
if (conf.UseProxy == 1)
{
chkProxy.Checked = true;
}
}
void PaintButton()
{
foreach (Control ctr in this.Controls)
{
if (ctr is Button)
{
Button b = ctr as Button;
b.BackColor = MainForm.mainColor;
b.FlatAppearance.MouseDownBackColor = MainForm.downColor;
b.FlatAppearance.MouseOverBackColor = MainForm.overColor;
}
}
}
private void chkStart_CheckedChanged(object sender, EventArgs e)
{
if (chkStart.Checked)
{
conf.OnStart = 1;
}
else
{
conf.OnStart = 0;
}
}
private void chkProxy_CheckedChanged(object sender, EventArgs e)
{
if (chkProxy.Checked)
{
grbProxy.Enabled = true;
conf.UseProxy = 1;
}
else
{
grbProxy.Enabled = false;
conf.UseProxy = 0;
}
}
private void btnConfigOK_Click(object sender, EventArgs e)
{
conf.TimeShowWord = (int)txtTimeShowWord.Value;
conf.Proxy = txtProxy.Text;
conf.ProxyPort = Convert.ToInt32(txtPort.Text);
conf.ProxyUser = txtUser.Text;
conf.ProxyPass = txtPassword.Text;
if (bll.UpdateConfig(conf))
{
this.Dispose();
}
}
private void btnConfigCancel_Click(object sender, EventArgs e)
{
this.Dispose();
}
}
} | 01301-english-learning | trunk/EnglishLearning/PresentationLayer/ConfigForm.cs | C# | oos | 2,687 |
using System;
using System.Windows.Forms;
using EnglishLearning.Utilities;
using EnglishLearning.BusinessLayer;
using EnglishLearning.Entities;
namespace EnglishLearning.PresentationLayer
{
public partial class QuickTranslateForm : Form
{
WordBLL bll;
public QuickTranslateForm()
{
InitializeComponent();
PaintButton();
bll = new WordBLL();
}
public void ShowQuickForm()
{
this.Show();
}
public void ShowQuickForm(string word)
{
PaintButton();
word = word.ToLower();
txtWord.Text = word;
txtMeaning.Text = GoogleService.TranslateGoogle(word, "en", "vi");
this.Show();
}
void PaintButton()
{
foreach (Control ctr in this.Controls)
{
if (ctr is Button)
{
Button b = ctr as Button;
b.BackColor = MainForm.mainColor;
b.FlatAppearance.MouseDownBackColor = MainForm.downColor;
b.FlatAppearance.MouseOverBackColor = MainForm.overColor;
}
}
}
private void txtWord_TextChanged(object sender, EventArgs e)
{
lbMessage.Text = "";
if (!txtWord.Text.Trim().Equals(""))
{
btnSave.Enabled = true;
txtMeaning.Text = GoogleService.TranslateGoogle(txtWord.Text, "en", "vi");
}
else
{
btnSave.Enabled = false;
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Hide();
this.ShowInTaskbar = false;
}
private void QuickTranslateForm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
this.ShowInTaskbar = false;
}
private void btnSave_Click(object sender, EventArgs e)
{
bll.Add(new Words(txtWord.Text, txtMeaning.Text, 0, ""));
lbMessage.Text = "This word or sentence have been save to database.";
btnSave.Enabled = false;
}
}
}
| 01301-english-learning | trunk/EnglishLearning/PresentationLayer/QuickTranslateForm.cs | C# | oos | 2,375 |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using EnglishLearning.BusinessLayer;
using EnglishLearning.Entities;
namespace EnglishLearning.PresentationLayer
{
public partial class RandomWordForm : Form
{
private WordBLL bll = new WordBLL();
public RandomWordForm()
{
InitializeComponent();
}
private void RandomWordForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
SolidBrush sb = new SolidBrush(MainForm.mainColor);
g.FillRectangle(sb, 0, 1, this.Width, 25);
Pen p = new Pen(Color.Black, 1);
g.DrawRectangle(p, 0, 0, this.Width - 1, this.Height - 1);
// Glass
LinearGradientBrush lgb = new LinearGradientBrush(new Point(0, 0), new Point(0, 26), Color.FromArgb(100, 255, 255, 255), Color.Transparent);
g.FillRectangle(lgb, 0, 0, this.Width, 26);
// Middle Line
g.DrawLine(Pens.DarkGray, new Point(txtWord.Location.X, txtWord.Location.Y + txtWord.Height + 3), new Point(txtWord.Location.X + txtWord.Width, txtWord.Location.Y + txtWord.Height + 3));
}
public void ShowRandomWordForm()
{
// Set Location
Point point;
int srcWidth = Screen.PrimaryScreen.Bounds.Width;
int srcHeight = Screen.PrimaryScreen.Bounds.Height;
point = new Point(srcWidth - this.Width, srcHeight);
this.Location = point;
// Effect
Timer time = new Timer();
time.Tick += new EventHandler(delegate(object sender2, EventArgs e2)
{
try
{
if (point.Y > (Screen.PrimaryScreen.Bounds.Height - this.Height - 30))
{
point.Y -= 2;
this.Location = point;
this.Show();
}
}
catch { }
});
time.Interval = 1;
time.Enabled = true;
time.Start();
}
public bool SetWord()
{
// Set word
Words word = bll.GetRandomWord();
if (word != null)
{
txtWord.Text = word.Word;
txtMeaning.Text = word.Meaning;
lbMark.Text = word.Mark.ToString();
try
{
if (!word.ImageLink.Equals(""))
pictureBox1.Image = Image.FromFile(word.ImageLink);
else
pictureBox1.Image = Image.FromFile("images//default_image.jpg");
}
catch { }
return true;
}
return false;
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Hide();
this.Location = new Point(this.Location.X, this.Location.Y - 1);
}
private void txtWord_TextChanged(object sender, EventArgs e)
{
if (txtWord.Lines.Length >= 2)
{
txtWord.ScrollBars = ScrollBars.Vertical;
}
else
{
txtWord.ScrollBars = ScrollBars.None;
}
}
private void txtMeaning_TextChanged(object sender, EventArgs e)
{
if (txtMeaning.Lines.Length >= 2)
{
txtMeaning.ScrollBars = ScrollBars.Vertical;
}
else
{
txtMeaning.ScrollBars = ScrollBars.None;
}
}
private void btnDetail_Click(object sender, EventArgs e)
{
}
}
} | 01301-english-learning | trunk/EnglishLearning/PresentationLayer/RandomWordForm.cs | C# | oos | 3,914 |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using EnglishLearning.BusinessLayer;
namespace EnglishLearning
{
public partial class InfoForm : Form
{
private WordBLL bll = new WordBLL();
public InfoForm()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Dispose();
}
private void InfoForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
SolidBrush sb = new SolidBrush(MainForm.mainColor);
g.FillRectangle(sb, 0, 1, this.Width, 25);
Pen p = new Pen(Color.Black, 1);
g.DrawRectangle(p, 0, 0, this.Width - 1, this.Height - 1);
// Glass
LinearGradientBrush lgb = new LinearGradientBrush(new Point(0, 0), new Point(0, 26), Color.FromArgb(100, 255, 255, 255), Color.Transparent);
g.FillRectangle(lgb, 0, 0, this.Width, 26);
}
private void InfoForm_Load(object sender, EventArgs e)
{
//ShowInfoForm();
}
public void ShowInfoForm()
{
// Show Form
CountWord();
Point point;
int srcWidth = Screen.PrimaryScreen.Bounds.Width;
int srcHeight = Screen.PrimaryScreen.Bounds.Height;
point = new Point(srcWidth - this.Width, srcHeight);
this.Location = point;
Timer time = new Timer();
time.Tick += new EventHandler(delegate(object sender2, EventArgs e2)
{
try
{
if (point.Y > (Screen.PrimaryScreen.Bounds.Height - this.Height - 30))
{
point.Y -= 2;
this.Location = point;
this.Show();
}
}
catch { }
});
time.Interval = 1;
time.Enabled = true;
time.Start();
//bll.CloseConnection();
}
private void CountWord()
{
int[] a = new int[3];
try
{
a = bll.CountWord();
lbNotLearn.Text = a[0].ToString();
lbLearning.Text = a[1].ToString();
lbLearned.Text = a[2].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void InfoForm_MouseLeave(object sender, EventArgs e)
{
}
}
} | 01301-english-learning | trunk/EnglishLearning/PresentationLayer/InfoForm.cs | C# | oos | 2,746 |
using System.Data;
namespace EnglishLearning.Entities
{
internal class Words
{
// Properties
private string _word;
private string _meaning;
private int _mark;
private string _imageLink;
public string Word
{
get { return _word; }
set { _word = value; }
}
public string Meaning
{
get { return _meaning; }
set { _meaning = value; }
}
public int Mark
{
get { return _mark; }
set { _mark = value; }
}
public string ImageLink
{
get { return _imageLink; }
set { _imageLink = value; }
}
// Constructors
public Words()
{
}
public Words(string word, string meaning, int mark, string imageLink)
{
this._word = word;
this._meaning = meaning;
this._mark = mark;
this._imageLink = imageLink;
}
public Words(DataRow row)
{
this._word = row["Word"].ToString();
this._meaning = row["Word_Meaning"].ToString();
this._mark = (int)row["Word_Mark"];
this._imageLink = row["Word_Image"].ToString();
}
}
} | 01301-english-learning | trunk/EnglishLearning/DataTransferObject/Words.cs | C# | oos | 1,374 |
using System.Data;
namespace EnglishLearning.Entities
{
internal class Config
{
private int _timeShowWord;
private int _onStart;
private int _colorR;
private int _colorG;
private int _colorB;
private int _useProxy;
private string _proxy;
private int _proxyPort;
private string _proxyUser;
private string _proxyPass;
public int TimeShowWord
{
get { return _timeShowWord; }
set { _timeShowWord = value; }
}
public int OnStart
{
get { return _onStart; }
set { _onStart = value; }
}
public int ColorR
{
get { return _colorR; }
set { _colorR = value; }
}
public int ColorG
{
get { return _colorG; }
set { _colorG = value; }
}
public int ColorB
{
get { return _colorB; }
set { _colorB = value; }
}
public int UseProxy
{
get { return _useProxy; }
set { _useProxy = value; }
}
public string Proxy
{
get { return _proxy; }
set { _proxy = value; }
}
public int ProxyPort
{
get { return _proxyPort; }
set { _proxyPort = value; }
}
public string ProxyUser
{
get { return _proxyUser; }
set { _proxyUser = value; }
}
public string ProxyPass
{
get { return _proxyPass; }
set { _proxyPass = value; }
}
public Config()
{
}
public Config(int time, int onStart, int r, int g, int b, int useProxy, string proxy, int port, string user, string pass)
{
this._timeShowWord = time;
this._onStart = onStart;
this._colorR = r;
this._colorG = g;
this._colorB = b;
this._useProxy = useProxy;
this._proxy = proxy;
this._proxyPort = port;
this._proxyUser = user;
this._proxyPass = pass;
}
public Config(DataRow row)
{
this._timeShowWord = (int)row["Time_Show_Word"];
this._onStart = (int)row["On_Start"];
this._colorR = (int)row["Color_R"];
this._colorG = (int)row["Color_G"];
this._colorB = (int)row["Color_B"];
this._useProxy = (int)row["Use_Proxy"];
this._proxy = row["Proxy"].ToString();
this._proxyPort = (int)row["Proxy_Port"];
this._proxyUser = row["Proxy_Username"].ToString();
this._proxyPass = row["Proxy_Password"].ToString();
}
}
} | 01301-english-learning | trunk/EnglishLearning/DataTransferObject/Config.cs | C# | oos | 2,922 |
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace EnglishLearning.Utilities
{
internal class GoogleService
{
/// <summary>
/// Translates a string into another language using Google's translate API JSON calls.
/// <seealso>Class TranslationServices</seealso>
/// </summary>
/// <param name="Text">Text to translate. Should be a single word or sentence.</param>
/// <param name="FromCulture">
/// Two letter culture (en of en-us, fr of fr-ca, de of de-ch)
/// </param>
/// <param name="ToCulture">
/// Two letter culture (as for FromCulture)
/// </param>
public static string TranslateGoogle(string text, string fromCulture, string toCulture)
{
fromCulture = fromCulture.ToLower();
toCulture = toCulture.ToLower();
// normalize the culture in case something like en-us was passed
// retrieve only en since Google doesn't support sub-locales
string[] tokens = fromCulture.Split('-');
if (tokens.Length > 1)
fromCulture = tokens[0];
// normalize ToCulture
tokens = toCulture.Split('-');
if (tokens.Length > 1)
toCulture = tokens[0];
string url = string.Format(@"http://translate.google.com/translate_a/t?client=j&text={0}&hl=en&sl={1}&tl={2}", HttpUtility.UrlEncode(text), fromCulture, toCulture);
// Retrieve Translation with HTTP GET call
string html = null;
try
{
WebClient web = new WebClient();
//web.Proxy = new WebProxy("10.22.152.254", 8080);
// MUST add a known browser user agent or else response encoding doen't return UTF-8 (WTF Google?)
web.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0");
web.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8");
// Make sure we have response encoding to UTF-8
web.Encoding = Encoding.UTF8;
html = web.DownloadString(url);
}
catch
{
return null;
}
// Extract out trans":"...[Extracted]...","from the JSON string
string result = Regex.Match(html, "trans\":(\".*?\"),\"", RegexOptions.IgnoreCase).Groups[1].Value;
if (string.IsNullOrEmpty(result))
{
return null;
}
// result string must be JSON decoded
//return WebUtils.DecodeJsString(result);
// Result is a JavaScript string so we need to deserialize it properly
//JavaScriptSerializer ser = new JavaScriptSerializer();
//return ser.Deserialize(result, typeof(string)) as string;
return result;
}
}
} | 01301-english-learning | trunk/EnglishLearning/Utilities/GoogleService.cs | C# | oos | 3,013 |
#region License_Do_Not_Remove
/*
* Made by TheDarkJoker94.
* Check http://thedarkjoker94.cer33.com/ for more C# Tutorials
* and also SUBSCRIBE to my Youtube Channel http://www.youtube.com/user/TheDarkJoker094
* GlobalKeyboardHook is licensed under a Creative Commons Attribution 3.0 Unported License.(http://creativecommons.org/licenses/by/3.0/)
* This means you can use this Code for whatever you want as long as you credit me! That means...
* DO NOT REMOVE THE LINES ABOVE !!!
*/
#endregion License_Do_Not_Remove
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class GlobalKeyboardHook
{
[DllImport("user32.dll")]
private static extern int CallNextHookEx(IntPtr hhk, int code, int wParam, ref keyBoardHookStruct lParam);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookEx(int idHook, LLKeyboardHook callback, IntPtr hInstance, uint theardID);
[DllImport("user32.dll")]
private static extern bool UnhookWindowsHookEx(IntPtr hInstance);
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string lpFileName);
public delegate int LLKeyboardHook(int Code, int wParam, ref keyBoardHookStruct lParam);
public struct keyBoardHookStruct
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private const int WM_KEYUP = 0x0101;
private const int WM_SYSKEYDOWN = 0x0104;
private const int WM_SYSKEYUP = 0x0105;
private LLKeyboardHook llkh;
public List<Keys> HookedKeys = new List<Keys>();
private IntPtr Hook = IntPtr.Zero;
public event KeyEventHandler KeyDown;
public event KeyEventHandler KeyUp;
// This is the Constructor. This is the code that runs every time you create a new GlobalKeyboardHook object
public GlobalKeyboardHook()
{
llkh = new LLKeyboardHook(HookProc);
// This starts the hook. You can leave this as comment and you have to start it manually (the thing I do in the tutorial, with the button)
// Or delete the comment mark and your hook will start automatically when your program starts (because a new GlobalKeyboardHook object is created)
// That's why there are duplicates, because you start it twice! I'm sorry, I haven't noticed this...
// hook(); <-- Choose!
}
~GlobalKeyboardHook()
{ unhook(); }
public void hook()
{
IntPtr hInstance = LoadLibrary("User32");
Hook = SetWindowsHookEx(WH_KEYBOARD_LL, llkh, hInstance, 0);
}
public void unhook()
{
UnhookWindowsHookEx(Hook);
}
public int HookProc(int Code, int wParam, ref keyBoardHookStruct lParam)
{
if (Code >= 0)
{
Keys key = (Keys)lParam.vkCode;
if (HookedKeys.Contains(key))
{
KeyEventArgs kArg = new KeyEventArgs(key);
if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null))
KeyDown(this, kArg);
else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null))
KeyUp(this, kArg);
if (kArg.Handled)
return 1;
}
}
return CallNextHookEx(Hook, Code, wParam, ref lParam);
}
} | 01301-english-learning | trunk/EnglishLearning/Utilities/GlobalKeyBoardHook.cs | C# | oos | 3,597 |
using System.Data;
using EnglishLearning.Entities;
using System.IO;
using System.Data.SQLite;
using System.Linq;
using System;
namespace EnglishLearning.DataLayer
{
internal class ConfigDAL
{
WordsEntities we = new WordsEntities();
public static Config GetConfig()
{
WordsEntities we = new WordsEntities();
var conf = we.Options.First();
return new Config(Convert.ToInt32(conf.Time_Show_Word), Convert.ToInt32(conf.On_Start), Convert.ToInt32(conf.Color_R), Convert.ToInt32(conf.Color_G), Convert.ToInt32(conf.Color_B), Convert.ToInt32(conf.Use_Proxy), conf.Proxy, Convert.ToInt32(conf.Proxy_Port), conf.Proxy_Username, conf.Proxy_Password);
}
public bool UpdateConfig(Config c)
{
// C1: ADO.NET
string query = string.Format("UPDATE Option SET Time_Show_Word = '{0}', On_Start = '{1}', Color_R = '{2}', Color_G = '{3}', Color_B = '{4}', Use_Proxy = '{5}', Proxy = '{6}', Proxy_Port = '{7}', Proxy_Username = '{8}', Proxy_Password = '{9}'", c.TimeShowWord, c.OnStart, c.ColorR, c.ColorG, c.ColorB, c.UseProxy, c.Proxy, c.ProxyPort, c.ProxyUser, c.ProxyPass);
SQLiteConnection con = new SQLiteConnection("data source=WordsStore.db");
con.Open();
if (new SQLiteCommand(query, con).ExecuteNonQuery() > 0)
{
con.Close();
return true;
}
con.Close();
return false;
// C2: Linq
// var op = we.Options.First();
//
// op.On_Start = Convert.ToInt32(c.OnStart);
// op.Time_Show_Word = Convert.ToInt32(c.TimeShowWord);
// op.Color_R = Convert.ToInt32(c.ColorR);
// op.Color_G = Convert.ToInt32(c.ColorG);
// op.Color_B = Convert.ToInt32(c.ColorB);
// op.Use_Proxy = Convert.ToInt32(c.UseProxy);
// op.Proxy = c.Proxy;
// op.Proxy_Port = Convert.ToInt32(c.ProxyPort);
// op.Proxy_Username = "-";
// op.Proxy_Password = "-";
//
// if (Convert.ToInt32(we.SaveChanges()) > 0)
// return true;
// return false;
}
public void FirstRun()
{
string imgPath = Directory.GetCurrentDirectory() + "\\ImagesStore\\";
string dbPath = Directory.GetCurrentDirectory() + "\\WordsStore.db";
string[] query = {
"CREATE TABLE Word(Word VARCHAR(500) PRIMARY KEY NOT NULL, Word_Meaning NVARCHAR(2000) NOT NULL, Word_Mark INT NOT NULL, Word_Image NVARCHAR(2000))",
"CREATE TABLE Option(Time_Show_Word INT,On_Start INT NOT NULL,Color_R INT NOT NULL,Color_G INT NOT NULL,Color_B INT NOT NULL,Use_Proxy INT NOT NULL,Proxy VARCHAR(20),Proxy_Port INT,Proxy_Username VARCHAR(50), Proxy_Password VARCHAR(50))",
"INSERT INTO Option VALUES(2, 0, 9,177,240, 0, '0.0.0.0', '0000', '', '')"
};
if (!Directory.Exists(imgPath))
{
Directory.CreateDirectory(imgPath);
}
if (!File.Exists(dbPath))
{
SQLiteConnection.CreateFile(dbPath);
SQLiteConnection connection = new SQLiteConnection("Data Source=WordsStore.db"); ;
SQLiteCommand command = new SQLiteCommand(connection);
foreach (string q in query)
{
connection.Open();
command.CommandText = q;
command.ExecuteNonQuery();
connection.Close();
}
}
}
}
} | 01301-english-learning | trunk/EnglishLearning/DataAccessLayer/ConfigDAL.cs | C# | oos | 3,797 |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using EnglishLearning.Entities;
using System.Linq;
namespace EnglishLearning.DataLayer
{
internal class WordDAL
{
WordsEntities we = new WordsEntities();
public static Dictionary<string, List<string>> GetDictionary()
{
WordsEntities we = new WordsEntities();
var words = from w in we.Words
select w;
Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
foreach (var w in words)
{
dic.Add(w.Word1, new List<string> { w.Word_Meaning, w.Word_Mark.ToString(), w.Word_Image });
}
return dic;
}
public bool Add(Words w)
{
Word wd = new Word();
wd.Word1 = w.Word;
wd.Word_Meaning = w.Meaning;
wd.Word_Mark = w.Mark;
wd.Word_Image = w.ImageLink;
we.AddToWords(wd);
try
{
if (Convert.ToInt32(we.SaveChanges()) > 0)
return true;
}
catch { System.Windows.Forms.MessageBox.Show("This word is exist!"); }
return false;
}
public bool Edit(string oldWord, Words w)
{
if (Remove(oldWord))
if (Add(w))
return true;
return false;
}
public bool Remove(string word)
{
var wd = (from w in we.Words
where w.Word1 == word
select w).FirstOrDefault();
if (wd != null)
we.Words.DeleteObject(wd);
if (Convert.ToInt32(we.SaveChanges()) > 0)
return true;
return false;
}
public int[] CountWord()
{
int[] count = new int[3];
// Not learned yet
count[0] = we.Words.Where(w => w.Word_Mark <= 3).Count();
// Learning
count[1] = we.Words.Where(w => w.Word_Mark >= 4 & w.Word_Mark <= 7).Count();
// Learned
count[2] = we.Words.Where(w => w.Word_Mark >= 8).Count();
return count;
}
public Words GetRandomWord()
{
int count = we.Words.Where(w => w.Word_Mark>=4 & w.Word_Mark<=7).Count();
int ran = 0;
try
{
ran = new Random().Next(0, count - 1);
}
catch { }
var word = we.Words.Where(w => w.Word_Mark>=4 & w.Word_Mark<=7).OrderBy(w => w.Word1).Skip(ran).FirstOrDefault();
if(word != null)
return new Words(word.Word1, word.Word_Meaning, word.Word_Mark, word.Word_Image);
return null;
}
}
} | 01301-english-learning | trunk/EnglishLearning/DataAccessLayer/WordDAL.cs | C# | oos | 2,981 |
using System;
using System.Windows.Forms;
namespace EnglishLearning
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SplashScreen screen = new SplashScreen();
Application.Run(screen);
if (screen.IsDisposed)
{
Application.Run(new MainForm());
}
}
}
} | 01301-english-learning | trunk/EnglishLearning/Program.cs | C# | oos | 633 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;
using System.IO;
using System.Drawing.Imaging;
namespace EnglishVocabularyHelper
{
public partial class MainSystem : Form
{
#region Declare Varables
bool DelOrCancel = true;
bool EditOrAdd = true;
int IDUser = 1;
Image im;
SQLiteConnection connection;
SQLiteCommand commandInsert;
SQLiteCommand commandSelect;
SQLiteDataReader reader;
String imlink;
#endregion
#region Load Form
public MainSystem()
{
connection = new SQLiteConnection("data source=MyData.db");
commandInsert = new SQLiteCommand(connection);
commandSelect = new SQLiteCommand(connection);
InitializeComponent();
loadUser();
pnCenter.Hide();
pnCreateUser.Hide();
//pnSelectUser.Location = new Point((this.Width - pnSelectUser.Width)/2, (this.Height - pnSelectUser.Height) / 2 - 20);
if(!pnSelectUser.Contains(pnSelectUser1))
{
lbTitle.Text = "Create User";
lbTitle.Location = new Point((this.Width - lbTitle.Width)/2,9);
pnSelectUser.Hide();
pnCreateUser.Show();
// pnCreateUser.Location = new Point((this.Width - pnCreateUser.Width) / 2, (this.Height - pnCreateUser.Height) - 80);
}
}
#endregion
#region Button event
private void btAddUser_Click(object sender, EventArgs e)
{
pnSelectUser.Hide();
pnCreateUser.Show();
lbTitle.Text = "Create User";
lbTitle.Location = new Point((this.Width - lbTitle.Width) / 2, 9);
//pnCreateUser.Location = new Point((this.Width - pnCreateUser.Width) / 2, (this.Height - pnCreateUser.Height) - 80);
}
private void button1_Click(object sender, EventArgs e)
{
pnSelectUser.Show();
}
private void btBrowser_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
opf.Filter = "Image Files|*.bmp; *.jpg; *.png";
if(opf.ShowDialog() == DialogResult.OK)
{
im = new Bitmap(40,40);
Graphics gr = Graphics.FromImage((Image)im);
Image img = Image.FromFile(opf.FileName);
gr.DrawImage(img,0,0,40,40);
btBrowser.Image = im;
}
}
private void button2_Click(object sender, EventArgs e)
{
pnCreateUser.Hide();
tbNameCreate.Text = "";
this.btBrowser.Image = global::EnglishVocabularyHelper.Properties.Resources.picture_add_icon;
pnSelectUser.Show();
lbTitle.Text = "English Vocabulary Helper";
lbTitle.Location = new Point((this.Width - lbTitle.Width) / 2, 9);
//loadUser();
pnSelectUser.Location = new Point((this.Width - pnSelectUser.Width) / 2, (this.Height - pnSelectUser.Height) / 2 - 20);
}
private void btCreateUser_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Confirm", "Do you want create this User?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
connection.Open();
imlink = "img/" + tbNameCreate.Text + ".bmp";
im.Save("img/" + tbNameCreate.Text + ".bmp", ImageFormat.Bmp);
commandInsert.CommandText = "insert into User values (" + IDUser + ",'" + tbNameCreate.Text + "','" + imlink + "')";
commandInsert.ExecuteNonQuery();
IDUser++;
connection.Close();
pnCreateUser.Hide();
tbNameCreate.Text = "";
this.btBrowser.Image = global::EnglishVocabularyHelper.Properties.Resources.picture_add_icon;
pnSelectUser.Show();
loadUser();
// pnSelectUser.Location = new Point((this.Width - pnSelectUser.Width) / 2, (this.Height - pnSelectUser.Height) / 2 - 30);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btSelectUser1_Click(object sender, EventArgs e)
{
IDUser = 1;
pnSelectUser.Hide();
pnCenter.Show();
}
private void btSelectUser2_Click(object sender, EventArgs e)
{
IDUser = 2;
pnSelectUser.Hide();
pnCenter.Show();
}
private void btSelectUser3_Click(object sender, EventArgs e)
{
IDUser = 3;
pnSelectUser.Hide();
pnCenter.Show();
}
private void btSelectUser4_Click(object sender, EventArgs e)
{
IDUser = 4;
pnSelectUser.Hide();
pnCenter.Show();
}
private void btSelectUser5_Click(object sender, EventArgs e)
{
IDUser = 5;
pnSelectUser.Hide();
pnCenter.Show();
}
private void btSelectUser6_Click(object sender, EventArgs e)
{
IDUser = 6;
pnSelectUser.Hide();
pnCenter.Show();
}
private void label6_Click(object sender, EventArgs e)
{
this.Dispose();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
pnHome.Controls.Add(btHome);
if(pnShowWords.Visible){
pnShowWords.Hide();
}
LBListWords.Items.Clear();
connection.Open();
commandSelect.CommandText = String.Format("Select * from Words where UserID={0}", IDUser);
reader = commandSelect.ExecuteReader();
while (reader.Read())
{
LBListWords.Items.Add(reader.GetString(0));
}
reader.Close();
connection.Close();
home();
pnListWords.Show();
}catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
private void btHome_Click_1(object sender, EventArgs e)
{
home();
pnListWords.Hide();
pnShowWords.Show();
}
private void btSearch_Click(object sender, EventArgs e)
{
try
{
connection.Open();
commandSelect.CommandText = String.Format("Select * from Words where UserID = {0} and Word = '{1}'", IDUser, tbSearch.Text);
reader = commandSelect.ExecuteReader();
reader.Read();
LBListWords.Items.Add(reader.GetString(0));
reader.Close();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btRefresh_Click(object sender, EventArgs e)
{
try
{
LBListWords.Items.Clear();
tbSearch.Text = "";
connection.Open();
commandSelect.CommandText = String.Format("Select * from Words where UserID={0}", IDUser);
reader = commandSelect.ExecuteReader();
while (reader.Read())
{
LBListWords.Items.Add(reader.GetString(0));
}
reader.Close();
connection.Close();
pnListWords.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btEdit_Click(object sender, EventArgs e)
{
if (pnShowWords.Visible)
{
pnMenuRight.Controls.Add(btDelete);
pnEditSave.Controls.Add(btSave);
pnHome.Controls.Add(btHome);
pnHome.Controls.Remove(btAddWord);
DelOrCancel = false;
EditOrAdd = true;
Add();
}
}
private void btAddWord_Click(object sender, EventArgs e)
{
pnTranslate.Hide();
pnListWords.Hide();
pnShowWords.Show();
pnMenuRight.Controls.Add(btDelete);
pnEditSave.Controls.Add(btSave);
pnHome.Controls.Add(btHome);
pnHome.Controls.Remove(btAddWord);
DelOrCancel = false;
EditOrAdd = false;
Add();
tbEditEnglishWord.Text = "";
tbEditExam.Text = "";
tbEditVietnamWord.Text = "";
}
private void btSave_Click(object sender, EventArgs e)
{
try
{
if ( EditOrAdd == false)
{
if (MessageBox.Show("Insert", "Are you sure?", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
connection.Open();
commandInsert.CommandText = "insert into Words values ('"+tbEditEnglishWord.Text+"','"+tbEditVietnamWord.Text+"',"+cbPronouns.SelectedIndex+",'"+tbEditExam.Text+"',1,"+IDUser+")";//String.Format("insert into Words values('{0}','{1}',{2},'{3}',1,{4})", tbEditEnglishWord.Text, tbEditVietnamWord.Text, cbPronouns.SelectedIndex.ToString(), tbEditExam.Text, IDUser.ToString());
commandInsert.ExecuteNonQuery();
connection.Close();
}
}
else
{
if (MessageBox.Show("Edit", "Are you sure?", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
connection.Open();
commandInsert.CommandText = String.Format("update set Word = '{0}' Mean = '{1}' Pronous = {2} Exam = {3} where Word = {4} and UserID = {5}", tbEditEnglishWord.Text, tbEditVietnamWord.Text, cbPronouns.SelectedIndex, tbEditExam.Text, lbEnglishWord.Text,IDUser);
commandInsert.ExecuteNonQuery();
connection.Close();
}
}
home();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btDelete_Click(object sender, EventArgs e)
{
try
{
if (DelOrCancel == true)
{
IDUser = 1;
if (MessageBox.Show("Delete", "Are you sure?", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
connection.Open();
commandSelect.CommandText = String.Format("Delete from Words where Word ='{0}' and UserID ={1}", lbEnglishWord.Text,IDUser);
commandSelect.ExecuteNonQuery();
connection.Close();
}
}
else
{
if (MessageBox.Show("Cancel", "Are you sure?", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
home();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btLogout_Click(object sender, EventArgs e)
{
if(MessageBox.Show("Logout","Are you sure?",MessageBoxButtons.OKCancel)==DialogResult.OK){
pnTranslate.Hide();
pnShowWords.Show();
pnCenter.Hide();
pnSelectUser.Show();
}
}
private void LBListWords_MouseDoubleClick(object sender, MouseEventArgs e)
{
try
{
pnListWords.Hide();
pnMenuRight.Controls.Add(btDelete);
connection.Open();
commandSelect.CommandText = String.Format("Select * from Words where UserID = {0} and Word = '{1}'", IDUser, LBListWords.SelectedItem.ToString());
reader = commandSelect.ExecuteReader();
reader.Read();
lbEnglishWord.Text = reader.GetString(0);
lbVietnamWord.Text = reader.GetString(1);
switch (reader.GetInt32(2))
{
case 1:
lbPronouns.Text = "Nouns";
break;
case 2:
lbPronouns.Text = "Verb";
break;
default:
lbPronouns.Text = "Unknow";
break;
}
lbExam.Text = reader.GetString(3);
lbMark.Text = reader.GetInt32(4).ToString();
reader.Close();
connection.Close();
//pnCenter.Controls.Add(pnShowWords);
pnShowWords.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btTranslate_Click(object sender, EventArgs e)
{
pnHome.Controls.Add(btHome);
pnShowWords.Hide();
pnListWords.Hide();
home();
pnTranslate.Show();
}
private void btApplyTranslate_Click(object sender, EventArgs e)
{
tbAfterTranslate.Text = GoogleService.TranslateGoogle(tbBeforeTranslate.Text,"en","vi");
}
#endregion
#region method
private void loadUser()
{
connection.Open();
commandSelect = new SQLiteCommand("Select * from User", connection);
reader = commandSelect.ExecuteReader();
if (reader.Read())
{
lbSelectUser1.Text = reader.GetString(1);
btSelectUser1.Image = Image.FromFile(reader.GetString(2));
pnSelectUser.Controls.Add(pnSelectUser1);
IDUser = 2;
}
if (reader.Read())
{
lbSelectUser2.Text = reader.GetString(1);
btSelectUser2.Image = Image.FromFile(reader.GetString(2));
pnSelectUser.Controls.Add(pnSelectUser2);
IDUser = 3;
}
if (reader.Read())
{
lbSelectUser3.Text = reader.GetString(1);
btSelectUser3.Image = Image.FromFile(reader.GetString(2));
pnSelectUser.Controls.Add(pnSelectUser3);
IDUser = 4;
}
if (reader.Read())
{
lbSelectUser4.Text = reader.GetString(1);
btSelectUser4.Image = Image.FromFile(reader.GetString(2));
pnSelectUser.Controls.Add(pnSelectUser4);
IDUser = 5;
}
if (reader.Read())
{
lbSelectUser5.Text = reader.GetString(1);
btSelectUser5.Image = Image.FromFile(reader.GetString(2));
pnSelectUser.Controls.Add(pnSelectUser5);
IDUser = 6;
}
if (reader.Read())
{
lbSelectUser6.Text = reader.GetString(1);
btSelectUser6.Image = Image.FromFile(reader.GetString(2));
pnSelectUser.Controls.Add(pnSelectUser6);
pnButtonAdd.Hide();
}
pnSelectUser.Location = new Point((this.Width - pnSelectUser.Width) / 2, (this.Height - pnSelectUser.Height) / 2 - 20);
reader.Close();
connection.Close();
}
private void Add()
{
pnEditSave.Controls.Remove(btEdit);
pnEditSave.Controls.Add(btSave);
pnEditSave.Controls.Add(btDelete);
pnPronous.Controls.Remove(lbPronouns);
pnPronous.Controls.Add(cbPronouns);
pnEnglishWord.Controls.Remove(lbEnglishWord);
pnEnglishWord.Controls.Add(tbEditEnglishWord);
tbEditEnglishWord.Text = lbEnglishWord.Text;
tbEditEnglishWord.Size = lbEnglishWord.Size;
pnExam.Controls.Remove(lbExam);
pnExam.Controls.Add(tbEditExam);
tbEditExam.Text = lbExam.Text;
tbEditExam.Size = lbExam.Size;
pnVietnamWord.Controls.Remove(lbVietnamWord);
pnVietnamWord.Controls.Add(tbEditVietnamWord);
tbEditVietnamWord.Text = lbVietnamWord.Text;
tbEditVietnamWord.Size = lbVietnamWord.Size;
}
private void home()
{
pnHome.Controls.Remove(btHome);
pnHome.Controls.Add(btAddWord);
pnEditSave.Controls.Remove(btSave);
pnMenuRight.Controls.Remove(btDelete);
pnEditSave.Controls.Remove(btSave);
pnEditSave.Controls.Add(btEdit);
pnEditSave.Controls.Remove(btDelete);
pnPronous.Controls.Remove(cbPronouns);
pnPronous.Controls.Add(lbPronouns);
pnEnglishWord.Controls.Remove(tbEditEnglishWord);
pnEnglishWord.Controls.Add(lbEnglishWord);
pnExam.Controls.Remove(tbEditExam);
pnExam.Controls.Add(lbExam);
pnVietnamWord.Controls.Remove(tbEditVietnamWord);
pnVietnamWord.Controls.Add(lbVietnamWord);
}
#endregion
}
}
| 01301-english-learning | trunk/EnglishVocabularyHelper/EnglishVocabularyHelper/EnglishVocabularyHelper/MainSystem.cs | C# | oos | 18,431 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EnglishVocabularyHelper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EnglishVocabularyHelper")]
[assembly: AssemblyCopyright("Copyright © 2012 by Vũ Thái Trung")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6ec4f366-7b0a-443c-850c-1df76b643d0c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 01301-english-learning | trunk/EnglishVocabularyHelper/EnglishVocabularyHelper/EnglishVocabularyHelper/Properties/AssemblyInfo.cs | C# | oos | 1,477 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace EnglishVocabularyHelper
{
class GoogleService
{
public static string TranslateGoogle(string text, string fromCulture, string toCulture)
{
fromCulture = fromCulture.ToLower();
toCulture = toCulture.ToLower();
// normalize the culture in case something like en-us was passed
// retrieve only en since Google doesn't support sub-locales
string[] tokens = fromCulture.Split('-');
if (tokens.Length > 1)
fromCulture = tokens[0];
// normalize ToCulture
tokens = toCulture.Split('-');
if (tokens.Length > 1)
toCulture = tokens[0];
string url = string.Format(@"http://translate.google.com/translate_a/t?client=j&text={0}&hl=en&sl={1}&tl={2}",
HttpUtility.UrlEncode(text), fromCulture, toCulture);
// Retrieve Translation with HTTP GET call
string html = null;
try
{
WebClient web = new WebClient();
//web.Proxy = new WebProxy("10.22.152.254", 8080);
// MUST add a known browser user agent or else response encoding doen't return UTF-8 (WTF Google?)
web.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0");
web.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8");
// Make sure we have response encoding to UTF-8
web.Encoding = Encoding.UTF8;
html = web.DownloadString(url);
}
catch (Exception ex)
{
return null;
}
// Extract out trans":"...[Extracted]...","from the JSON string
string result = Regex.Match(html, "trans\":(\".*?\"),\"", RegexOptions.IgnoreCase).Groups[1].Value;
if (string.IsNullOrEmpty(result))
{
return null;
}
return result;
}
}
}
| 01301-english-learning | trunk/EnglishVocabularyHelper/EnglishVocabularyHelper/EnglishVocabularyHelper/GoogleService.cs | C# | oos | 2,249 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace EnglishVocabularyHelper
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// try{
Application.Run(new MainSystem());
// }
// catch (Exception e)
// {
// MessageBox.Show(e.Message);
// }
}
}
}
| 01301-english-learning | trunk/EnglishVocabularyHelper/EnglishVocabularyHelper/EnglishVocabularyHelper/Program.cs | C# | oos | 680 |
package edu.gatech.oad.antlab.pkg2;
/**
* CS2335 Ant Lab
*
* AntLab11.java helper class
*
* @author Robert
* @version 1.0
*/
public class AntLab22 {
/**
* retrieves a pre-stored string message
* @return the string
*/
public String getMessage() {
return " a";
}
} | 00agents-cs2340-seedswap-project | trunk/M4/src/edu/gatech/oad/antlab/pkg2/AntLab22.java | Java | gpl3 | 346 |
package edu.gatech.oad.antlab.pkg2;
/**
* CS2340 Ant Lab
*
* AntLab11.java helper class
*
* @author Robert
* @version 1.0
*/
public class AntLab21 {
/**
* retrieves a pre-stored string message
* @return the string
*/
public String getMessage() {
return " deserve";
}
} | 00agents-cs2340-seedswap-project | trunk/M4/src/edu/gatech/oad/antlab/pkg2/AntLab21.java | Java | gpl3 | 352 |
package edu.gatech.oad.antlab.person;
/**
* A simple class for person 1
* returns their name and a
* modified string
*
* @author Bob
* @version 1.1
*/
public class Person4 {
/** Holds the persons real name */
private String name;
/**
* The constructor, takes in the persons
* name
* @param pname the person's real name
*/
public Person4(String pname) {
name = pname;
}
/**
* This method should take the string
* input and return its characters rotated
* 2 positions.
* given "gtg123b" it should return
* "g123bgt".
*
* @param input the string to be modified
* @return the modified string
*/
private String calc(String input) {
//use the substring method to move the first two characters to the end of the string
return input.substring(2)+input.substring(0,2);
}
/**
* Return a string rep of this object
* that varies with an input string
*
* @param input the varying string
* @return the string representing the
* object
*/
public String toString(String input) {
return name + calc(input);
}
}
| 00agents-cs2340-seedswap-project | trunk/M4/src/edu/gatech/oad/antlab/person/Person4.java | Java | gpl3 | 1,234 |
package edu.gatech.oad.antlab.person;
import java.util.ArrayList;
import java.util.Collections;
/**
* A simple class for person 2
* returns their name and a
* modified string
*
* @author Bob
* @version 1.1
*/
public class Person2 {
/** Holds the persons real name */
private String name;
/**
* The constructor, takes in the persons
* name
* @param pname the person's real name
*/
public Person2(String pname) {
name = pname;
}
/**
* This method should take the string
* input and return its characters in
* random order.
* given "gtg123b" it should return
* something like "g3tb1g2".
*
* @param input the string to be modified
* @return the modified string
*/
private String calc(String input) {
//initializes variables
int index = 0;
String mod = "";
ArrayList<Character> characters = new ArrayList<Character>();
//adds characters into ArrayList
while(index < input.length()){
characters.add(input.charAt(index));
index++;
}
//shuffles the indexes of ArrayList
Collections.shuffle(characters);
//Creates new String using indexes of Character ArrayList
index = 0;
while(index < input.length()){
mod = mod + characters.get(index);
index++;
}
return mod;
}
/**
* Return a string rep of this object
* that varies with an input string
*
* @param input the varying string
* @return the string representing the
* object
*/
public String toString(String input) {
return name + calc(input);
}
}
| 00agents-cs2340-seedswap-project | trunk/M4/src/edu/gatech/oad/antlab/person/Person2.java | Java | gpl3 | 1,592 |
package edu.gatech.oad.antlab.person;
/**
* A simple class for person 5
* returns their name and a
* modified string
*
* @author Bob
* @version 1.1
*/
public class Person5 {
/** Holds the persons real name */
private String name;
/**
* The constructor, takes in the persons
* name
* @param pname the person's real name
*/
public Person5(String pname) {
name = pname;
}
/**
* This method should take the string
* input and return its characters rotated
* 4 positions.
* given "gtg123b" it should return
* "23bgtg1".
*
* @param input the string to be modified
* @return the modified string
*/
private String calc(String input) {
//Person 5 put your implementation here
return null;
}
/**
* Return a string rep of this object
* that varies with an input string
*
* @param input the varying string
* @return the string representing the
* object
*/
public String toString(String input) {
return name + calc(input);
}
}
| 00agents-cs2340-seedswap-project | trunk/M4/src/edu/gatech/oad/antlab/person/Person5.java | Java | gpl3 | 1,063 |
package edu.gatech.oad.antlab.person;
/**
* A simple class for person 3
* returns their name and a
* reversed string
*
* @author Bob
* @version 1.1
*/
public class Person3 {
/** Holds the persons real name */
private String name;
/**
* The constructor, takes in the persons
* name
* @param pname the person's real name
*/
public Person3(String pname){
name = pname;
}
/**
* Return a string rep of this object
* that varies with an input string
*
* @param input the varying string
* @return the string representing the
* object
*/
public String toString(String input) {
return name + calc(input);
}
/**
* This method should take the string
* input and return its reverse.
* given "gtg123b" it should return
* b321gtg.
*
* @param input the string to be reversed
* @return the reversed string
*/
private String calc(String input) {
String ans = "";
for (char c:input.toCharArray()){
ans=c+ans;
}
return ans;
}
}
| 00agents-cs2340-seedswap-project | trunk/M4/src/edu/gatech/oad/antlab/person/Person3.java | Java | gpl3 | 1,015 |
package edu.gatech.oad.antlab.person;
/**
* A simple class for person 1
* returns their name and a
* modified string
*
* @author Bob
* @version 1.1
*/
public class Person1 {
/** Holds the persons real name */
private String name;
/**
* The constructor, takes in the persons
* name
* @param pname the person's real name
*/
public Person1(String pname) {
name = pname;
}
/**
* This method should take the string
* input and return its characters rotated
* 2 positions.
* given "gtg123b" it should return
* "g123bgt".
*
* @param input the string to be modified
* @return the modified string
*/
private String calc(String input) {
//Person 1 put your implementation here
return input.substring(2)+input.substring(0,2);
}
/**
* Return a string rep of this object
* that varies with an input string
*
* @param input the varying string
* @return the string representing the
* object
*/
public String toString(String input) {
return name + calc(input);
}
}
| 00agents-cs2340-seedswap-project | trunk/M4/src/edu/gatech/oad/antlab/person/Person1.java | Java | gpl3 | 1,098 |
package edu.gatech.oad.antlab.pkg1;
/**
* CS2335 Ant Lab
*
* AntLab12.java helper class
*/
public class AntLab12 {
/**
* retrieves a pre-stored string message
* @return the string
*/
public String getMessage() {
return " You";
}
} | 00agents-cs2340-seedswap-project | trunk/M4/src/edu/gatech/oad/antlab/pkg1/AntLab12.java | Java | gpl3 | 308 |
package edu.gatech.oad.antlab.pkg1;
//if you get an error on this import
//you do not have resources.jar on the classpath
import edu.cs2335.antlab.pkg3.*;
import edu.gatech.oad.antlab.person.*;
import edu.gatech.oad.antlab.pkg2.*;
/**
* CS2335 Ant Lab
*
* Prints out a simple message gathered from all of the other classes
* in the package structure
*/
public class AntLabMain {
/**antlab11.java message class*/
private AntLab11 ant11;
/**antlab12.java message class*/
private AntLab12 ant12;
/**antlab21.java message class*/
private AntLab21 ant21;
/**antlab22.java message class*/
private AntLab22 ant22;
/**antlab31 java message class which is contained in a jar resource file*/
private AntLab31 ant31;
/**
* the constructor that initializes all the helper classes
*/
public AntLabMain () {
ant11 = new AntLab11();
ant12 = new AntLab12();
ant21 = new AntLab21();
ant22 = new AntLab22();
//if you get an error here, you do not have resources.jar on the classpath
ant31 = new AntLab31();
}
/**
* gathers a string from all the other classes and prints the message
* out to the console
*
*/
public void printOutMessage() {
String toPrint =
ant11.getMessage() + ant12.getMessage() + ant21.getMessage()
+ ant22.getMessage() + ant31.getMessage();
//Person1 replace P1 with your name
//and ggg000x with your gt num
Person1 p1 = new Person1("Cameron Smith");
toPrint += p1.toString("csmith330");
//Person2 replace P2 with your name
//and ggg000x with your gt num
Person2 p2 = new Person2("Michael Dang");
toPrint += p2.toString("mdang3");
//Person3 replace P3 with your name
//and ggg000x with your gt num
Person3 p3 = new Person3("W Scott Johnson");
toPrint += p3.toString("wjohnson38");
//Person4 replace P4 with your name
//and ggg000x with your gt num
Person4 p4 = new Person4("Seth Pearce");
toPrint += p4.toString("spearce3");
//Person5 replace P5 with your name
//and ggg000x with your gt num
Person5 p5 = new Person5("P5");
toPrint += p5.toString("ggg005x");
System.out.println(toPrint);
}
/**
* entry point for the program
*/
public static void main(String[] args) {
new AntLabMain().printOutMessage();
}
} | 00agents-cs2340-seedswap-project | trunk/M4/src/edu/gatech/oad/antlab/pkg1/AntLabMain.java | Java | gpl3 | 2,701 |
package edu.gatech.oad.antlab.pkg1;
/**
* CS2340 Ant Lab
*
* AntLab11.java helper class
* @author Robert
* @version 1.0
*/
public class AntLab11 {
/**
* retrieves a pre-stored string message
* @return the string
*/
public String getMessage() {
return "Congrats!";
}
} | 00agents-cs2340-seedswap-project | trunk/M4/src/edu/gatech/oad/antlab/pkg1/AntLab11.java | Java | gpl3 | 348 |
package seedswapapplication
import grails.test.mixin.*
import org.junit.*
/**
* See the API for {@link grails.test.mixin.domain.DomainClassUnitTestMixin} for usage instructions
*/
@TestFor(Admin)
class AdminTests {
void testSomething() {
fail "Implement me"
}
}
| 00agents-cs2340-seedswap-project | trunk/SeedSwapApplication/test/unit/seedswapapplication/AdminTests.groovy | Groovy | gpl3 | 286 |
package seedswapapplication
import grails.test.mixin.*
import org.junit.*
/**
* See the API for {@link grails.test.mixin.domain.DomainClassUnitTestMixin} for usage instructions
*/
@TestFor(Seed)
class SeedTests {
void testSomething() {
fail "Implement me"
}
}
| 00agents-cs2340-seedswap-project | trunk/SeedSwapApplication/test/unit/seedswapapplication/SeedTests.groovy | Groovy | gpl3 | 284 |
dataSource {
pooled = true
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:h2:file:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:h2:file:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:h2:file:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
}
}
}
| 00agents-cs2340-seedswap-project | trunk/SeedSwapApplication/grails-app/conf/DataSource.groovy | Groovy | gpl3 | 847 |
modules = {
application {
resource url:'js/application.js'
}
} | 00agents-cs2340-seedswap-project | trunk/SeedSwapApplication/grails-app/conf/ApplicationResources.groovy | Groovy | gpl3 | 78 |
grails.servlet.version = "2.5" // Change depending on target container compliance (2.5 or 3.0)
grails.project.class.dir = "target/classes"
grails.project.test.class.dir = "target/test-classes"
grails.project.test.reports.dir = "target/test-reports"
grails.project.target.level = 1.6
grails.project.source.level = 1.6
//grails.project.war.file = "target/${appName}-${appVersion}.war"
grails.project.dependency.resolution = {
// inherit Grails' default dependencies
inherits("global") {
// uncomment to disable ehcache
// excludes 'ehcache'
}
log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
checksums true // Whether to verify checksums on resolve
repositories {
inherits true // Whether to inherit repository definitions from plugins
grailsPlugins()
grailsHome()
grailsCentral()
mavenCentral()
// uncomment these to enable remote dependency resolution from public Maven repositories
//mavenCentral()
//mavenLocal()
//mavenRepo "http://snapshots.repository.codehaus.org"
//mavenRepo "http://repository.codehaus.org"
//mavenRepo "http://download.java.net/maven/2/"
//mavenRepo "http://repository.jboss.com/maven2/"
}
dependencies {
// specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
// runtime 'mysql:mysql-connector-java:5.1.16'
}
plugins {
runtime ":hibernate:$grailsVersion"
runtime ":jquery:1.7.1"
runtime ":resources:1.1.6"
// Uncomment these (or add new ones) to enable additional resources capabilities
//runtime ":zipped-resources:1.0"
//runtime ":cached-resources:1.0"
//runtime ":yui-minify-resources:0.1.4"
build ":tomcat:$grailsVersion"
}
}
| 00agents-cs2340-seedswap-project | trunk/SeedSwapApplication/grails-app/conf/BuildConfig.groovy | Groovy | gpl3 | 1,894 |
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
}
}
| 00agents-cs2340-seedswap-project | trunk/SeedSwapApplication/grails-app/conf/UrlMappings.groovy | Groovy | gpl3 | 180 |
import grails.util.GrailsUtil
import seedswapapplication.Admin
class BootStrap {
def init = { servletContext ->
def admin = new Admin()
admin = new Admin()
admin.login = "Admin"
admin.password = "share_seeds"
admin.save()
}
def destroy = {
}
}
| 00agents-cs2340-seedswap-project | trunk/SeedSwapApplication/grails-app/conf/BootStrap.groovy | Groovy | gpl3 | 273 |
// Place your Spring DSL code here
beans = {
}
| 00agents-cs2340-seedswap-project | trunk/SeedSwapApplication/grails-app/conf/spring/resources.groovy | Groovy | gpl3 | 47 |
// locations to search for config files that get merged into the main config
// config files can either be Java properties files or ConfigSlurper scripts
// grails.config.locations = [ "classpath:${appName}-config.properties",
// "classpath:${appName}-config.groovy",
// "file:${userHome}/.grails/${appName}-config.properties",
// "file:${userHome}/.grails/${appName}-config.groovy"]
// if (System.properties["${appName}.config.location"]) {
// grails.config.locations << "file:" + System.properties["${appName}.config.location"]
// }
grails.project.groupId = appName // change this to alter the default package name and Maven publishing destination
grails.mime.file.extensions = true // enables the parsing of file extensions from URLs into the request format
grails.mime.use.accept.header = false
grails.mime.types = [ html: ['text/html','application/xhtml+xml'],
xml: ['text/xml', 'application/xml'],
text: 'text/plain',
js: 'text/javascript',
rss: 'application/rss+xml',
atom: 'application/atom+xml',
css: 'text/css',
csv: 'text/csv',
all: '*/*',
json: ['application/json','text/json'],
form: 'application/x-www-form-urlencoded',
multipartForm: 'multipart/form-data'
]
// URL Mapping Cache Max Size, defaults to 5000
//grails.urlmapping.cache.maxsize = 1000
// What URL patterns should be processed by the resources plugin
grails.resources.adhoc.patterns = ['/images/*', '/css/*', '/js/*', '/plugins/*']
// The default codec used to encode data with ${}
grails.views.default.codec = "none" // none, html, base64
grails.views.gsp.encoding = "UTF-8"
grails.converters.encoding = "UTF-8"
// enable Sitemesh preprocessing of GSP pages
grails.views.gsp.sitemesh.preprocess = true
// scaffolding templates configuration
grails.scaffolding.templates.domainSuffix = 'Instance'
// Set to false to use the new Grails 1.2 JSONBuilder in the render method
grails.json.legacy.builder = false
// enabled native2ascii conversion of i18n properties files
grails.enable.native2ascii = true
// packages to include in Spring bean scanning
grails.spring.bean.packages = []
// whether to disable processing of multi part requests
grails.web.disable.multipart=false
// request parameters to mask when logging exceptions
grails.exceptionresolver.params.exclude = ['password']
// enable query caching by default
grails.hibernate.cache.queries = true
// set per-environment serverURL stem for creating absolute links
environments {
development {
grails.logging.jul.usebridge = true
}
production {
grails.logging.jul.usebridge = false
// TODO: grails.serverURL = "http://www.changeme.com"
}
}
// log4j configuration
log4j = {
// Example of changing the log pattern for the default console
// appender:
//
//appenders {
// console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n')
//}
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages', // GSP
'org.codehaus.groovy.grails.web.sitemesh', // layouts
'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
'org.codehaus.groovy.grails.web.mapping', // URL mapping
'org.codehaus.groovy.grails.commons', // core / classloading
'org.codehaus.groovy.grails.plugins', // plugins
'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
'org.springframework',
'org.hibernate',
'net.sf.ehcache.hibernate'
}
| 00agents-cs2340-seedswap-project | trunk/SeedSwapApplication/grails-app/conf/Config.groovy | Groovy | gpl3 | 3,857 |
package seedswapapplication
/*
* SeedStorageController handles all access to the database with regards to Seeds
*/
class SeedStorageController {
/*
* This action takes search parameters and generates a list of seeds for display
* based on those search parameters. It then directs to a page that can display
* the search results. Invalid searches and failed searches are handled here
*/
def searchResults =
{
if(!params.hardinessZone && !params.scientificName)
{
flash.message = "Please select Hardiness Zone or Scientific Name to search by."
redirect(controller:'client',action:'searchSeedPage')
}
else
{
def seedList
if(params.hardinessZone)
seedList = Seed.findAllByHardiness(params.query)
else
seedList = Seed.findAllByScientificName(params.query)
if(seedList)
[seedList:seedList,query:params.query]
else
{
flash.message = "We're sorry. Your search for \""+params.query+"\" did not return any results. Please try another search"
redirect(controller:'client', action: 'searchSeedPage')
}
}
}
/*
* This action searches the database to find all seeds owned by the current user
* and directs to a page to display this list
*/
def viewSeeds =
{
if(session.username)
{
def seedList = Seed.findAllByFarmerName(session.username)
[seedList:seedList,username:session.username]
}
else
{
flash.message = "You must be logged in to view seeds. Please log in or register."
redirect(url:"/")
}
}
/*
* This action finds a seed based on input params and directs to a page
* to display all information for that seed.
*/
def displaySeed =
{
Seed seed = Seed.get(params.id)
if(seed)
[seed:seed]
else
{
flash.message = "Error displaying seed. Please try again."
redirect(url:"/")
}
}
/*
* This action handles the actual creation of a seed and adding it to the database
* based on input parameters
*/
def createSeed =
{
def seed = new Seed()
seed.hardiness = params.hardiness
seed.harvesting = params.harvesting
seed.commonName = params.commonName
seed.scientificName = params.scientificName
seed.seasonAvailable = params.seasonAvailable
seed.tips = params.tips
seed.specialRequirements = params.specialRequirements
seed.farmerName = session.username
seed.save()
redirect(action: 'viewSeeds')
}
}
| 00agents-cs2340-seedswap-project | trunk/SeedSwapApplication/grails-app/controllers/seedswapapplication/SeedStorageController.groovy | Groovy | gpl3 | 2,441 |
package seedswapapplication
/*
* UserStorageController controls all access to the database with regards to Farmers and Admins
*/
class UserStorageController {
/*
* This action searches the database for all locked out farmers and then directs to a page where
* these farmers are listed and can be unlocked
*/
def unlockFarmerPage = {
if(!session.isAdmin)
{
flash.message = "You must be logged in as an admin to access this page."
redirect(url:"/")
}
else
{
def lockedList = Farmer.findAllByLoginAttemptsGreaterThan(2)
[lockedList:lockedList]
}
}
/*
* This action is called when a login attempt is made.
* The database is searched for both farmers and admins.
* Incorrect logins and lockouts are handled and this action redirects
* to the appropriate home page for a farmer or an admin upon a successful login
*/
def authenticate = {
def farmer = Farmer.findWhere(login:params.username)
boolean success = false;
boolean locked = false;
if (farmer)
{
if(farmer.loginAttempts>2)
{
flash.message = "Your account is locked. Please contact an administrator."
locked=true;
redirect(controller:'client',action: 'login')
}
else
{
if(farmer.password.equals(params.password))
{
success=true;
}
else
{
farmer.loginAttempts++
}
}
session.isAdmin = false
}
def administrator = Admin.findByLoginAndPassword(params.username, params.password)
if(administrator)
{
session.username = params.username
session.loggedInMessage = "Current Administrator: "+session.username
session.isAdmin = true
redirect(controller:'client',action: 'adminPage')
}
else if(!locked)
{
if(success)
{
session.username = params.username
session.loggedInMessage = "Current User: "+session.username
redirect(url: '/')
}
else
{
flash.message = "Login failed"
redirect(controller:'client',action: 'login')
}
}
}
/*
* This action handles unlocking a farmer
*/
def unlockFarmer =
{
Farmer toUnlock = Farmer.findWhere(login: params.login)
if(toUnlock)
toUnlock.loginAttempts = 0
redirect(action: 'unlockFarmerPage')
}
/*
* This action actually adds a farmer to the database based on parameters defined in params
*/
def createFarmer = {
def farmer = Farmer.findWhere(login:params.username)
if (farmer){
flash.message = "Username "+params.username+" is already taken. Select another username."
redirect(controller:'client',action: 'register')
}else{
flash.message = "Registration successful. Login with your new username and password"
farmer = new Farmer()
farmer.login = params.username
farmer.password = params.password
farmer.loginAttempts = 0
farmer.email = params.email
farmer.climateZone = params.zone
farmer.address = params.address
farmer.name = params.name
farmer.interests = params.interests
farmer.save();
redirect(controller:'client',action: 'login')
}
}
}
| 00agents-cs2340-seedswap-project | trunk/SeedSwapApplication/grails-app/controllers/seedswapapplication/UserStorageController.groovy | Groovy | gpl3 | 3,107 |