欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Day35:航班管理系统

程序员文章站 2024-02-26 21:27:46
...

主要实现功能为航班信息的增删改查,解析XML文件,保存信息到TXT文件。
使用反射以及依赖注入。

代码如下:
flights.xml

<flights>
<flight flightNo="NA1234">
<departureCity>北京</departureCity>
<departureTime>2019-08-02 13:30:00</departureTime>
<arrivalCity>上海</arrivalCity>
<arrivalTime>2019-08-02 15:28:00</arrivalTime>
</flight>
<flight flightNo="NA2345">
<departureCity>北京</departureCity>
<departureTime>2019-08-02 11:00:00</departureTime>
<arrivalCity>广州</arrivalCity>
<arrivalTime>2019-08-02 15:28:00</arrivalTime>
</flight>
<flight flightNo="CZ1234">
<departureCity>北京</departureCity>
<departureTime>2019-08-02 17:30:00</departureTime>
<arrivalCity>上海</arrivalCity>
<arrivalTime>2019-08-02 19:28:00</arrivalTime>
</flight>
<flight flightNo="AB1234">
<departureCity>大连</departureCity>
<departureTime>2019-05-06 16:03:00</departureTime>
<arrivalCity>上海</arrivalCity>
<arrivalTime>2019-05-06 19:33:00</arrivalTime>
</flight>
<flight flightNo="CA1234">
<departureCity>北京</departureCity>
<departureTime>2019-08-02 10:30:00</departureTime>
<arrivalCity>上海</arrivalCity>
<arrivalTime>2019-08-02 12:28:00</arrivalTime>
</flight>
</flights>

applicationContext.xml

<beans>
<bean id="flightDao" class="com.biubiubiu.dongtianbao.dao.impl.FlightDaoImpl"/>
<bean id="flightService" class="com.biubiubiu.dongtianbao.service.impl.FlightServiceImpl">
<!--  name是类的属性名名   ref这个放的是bean中id的值  -->
<property name="flightDao" ref="flightDao"/>
</bean>
<bean id="flightAction" class="com.biubiubiu.dongtianbao.action.FlightAction">
<!--  name是类的属性名名   ref这个放的是bean中id的值  -->
<property name="flightService" ref="flightService"/>
</bean>
</beans>

Flight.java

package com.biubiubiu.dongtianbao.entity;

import java.util.Date;

import com.biubiubiu.dongtianbao.common.Utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
 * 实体类
 * @author 11142
 *
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Flight implements Comparable<Flight>{
	private String flightNo;
	private String departureCity;
	private String arrivalCity;
	private Date departureTime;
	private Date arrivalTime;
	@Override
	public int compareTo(Flight o) {
		String str1 = Utils.dateToStr(this.getDepartureTime());
		String str2 = Utils.dateToStr(o.getDepartureTime());
		return str1.compareTo(str2);
	}
}

FlightDao.java

package com.biubiubiu.dongtianbao.dao;

import java.util.List;

import com.biubiubiu.dongtianbao.entity.Flight;


public interface FlightDao {
	/**
	 * 显示所有航班信息(起飞时间升序)
	 */
	List<Flight> showAllFlightsInfo();
	/**
	 * 添加航班
	 */
	boolean addFlight(Flight flight);
	/**
	 * 删除航班
	 */
	boolean deleteFlight(int index);
	/**
	 * 保存更新XML文件
	 */
	void saveXML();
	/**
	 * 保存查询结果到TXT文件
	 */
	void saveTXT(String info);
}

FlightDaoImpl.java

package com.biubiubiu.dongtianbao.dao.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.biubiubiu.dongtianbao.common.Utils;
import com.biubiubiu.dongtianbao.dao.FlightDao;
import com.biubiubiu.dongtianbao.entity.Flight;

public class FlightDaoImpl implements FlightDao {
	private Map<String,Flight> flightMap = new HashMap<String, Flight>();

	public FlightDaoImpl() {
		try {
			InputStream is = FlightDaoImpl.class.getClassLoader().getResourceAsStream("flights.xml");
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(is);
			Element root = document.getRootElement();
			List<Element> elements = root.elements();
			for (Element element : elements) {
				String flightNo = element.attributeValue("flightNo");
				String departureCity = element.element("departureCity").getText();
				String arrivalCity = element.element("arrivalCity").getText();
				String departureTime = element.element("departureTime").getText();
				String arrivalTime = element.element("arrivalTime").getText();
				Flight flight = new Flight(flightNo, departureCity, arrivalCity, Utils.strToDate(departureTime), Utils.strToDate(arrivalTime));
				flightMap.put(flight.getFlightNo(), flight);
			}
			
			
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public List<Flight> showAllFlightsInfo() {
		List<Flight> list = new ArrayList<Flight>();
		for (Flight flight : flightMap.values()) {
			list.add(flight);
		}
		Collections.sort(list);
		return list;
	}

	@Override
	public boolean addFlight(Flight flight) {
		if (flightMap.containsKey(flight.getFlightNo())) {
			return false;
		} else {
			flightMap.put(flight.getFlightNo(), flight);
			return true;
		}
	}

	@Override
	public boolean deleteFlight(int index) {
		Flight flight = showAllFlightsInfo().get(index);
		return flightMap.remove(flight.getFlightNo()) != null ? true : false;
	}

	@Override
	public void saveXML() {
		try {
			InputStream is = FlightDaoImpl.class.getClassLoader().getResourceAsStream("flights.xml");
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(is);
			Element root = document.getRootElement();
			List<Element> elements = root.elements();
			for (Element element : elements) {
				element.getParent().remove(element);
			}
			for (Flight flight : flightMap.values()) {
				Element element = root.addElement("flight");
				element.addAttribute("flightNo", flight.getFlightNo());
				element.addElement("departureCity").setText(flight.getDepartureCity());
				element.addElement("arrivalCity").setText(flight.getArrivalCity());
				element.addElement("departureTime").setText(Utils.dateToStr(flight.getDepartureTime()));
				element.addElement("arrivalTime").setText(Utils.dateToStr(flight.getArrivalTime()));
			}
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			String path = "E:\\JAVA\\JAVA_WorkSpace\\KGC_Senior\\Senior1031\\src\\main\\resources\\flights.xml";
			XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(path)),format);
			writer.write(document);
			writer.close();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void saveTXT(String info) {
		File file = new File("E:\\JAVA\\JAVA_WorkSpace\\KGC_Senior\\Senior1031\\src\\main\\resources\\flights.txt");
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file, true);
			String str = info + "\n";
			byte[] bytes = str.getBytes();
			fos.write(bytes);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

FlightService.java

package com.biubiubiu.dongtianbao.service;

import java.util.List;

import com.biubiubiu.dongtianbao.entity.Flight;


public interface FlightService {
	/**
	 * 显示所有航班信息(起飞时间升序),业务操作
	 */
	List<Flight> showAllFlightsInfo();
	/**
	 * 添加航班,业务操作
	 */
	String addFlight(Flight flight);
	
	/**
	 * 删除航班,业务操作
	 */
	String deleteFlight(int index);
	
	/**
	 * 保存更新XML文件
	 */
	void saveXML();
	
	/**
	 * 保存查询结果到TXT文件
	 */
	void saveTXT(String info);
}

FlightServiceImpl.java

package com.biubiubiu.dongtianbao.service.impl;

import java.util.List;

import com.biubiubiu.dongtianbao.dao.FlightDao;
import com.biubiubiu.dongtianbao.entity.Flight;
import com.biubiubiu.dongtianbao.service.FlightService;

public class FlightServiceImpl implements FlightService{
	private FlightDao flightDao;

	@Override
	public List<Flight> showAllFlightsInfo() {
		List<Flight> list = flightDao.showAllFlightsInfo();
		return list;
	}

	@Override
	public String addFlight(Flight flight) {
		String message = "";
		boolean result = flightDao.addFlight(flight);
		message = result?"添加成功":"添加失败~航班编号不能相同~";
		return message;
	}

	@Override
	public String deleteFlight(int index) {
		String message = "";
		if(index<=0 || index>flightDao.showAllFlightsInfo().size()) {
			message = "您要删除的航班信息不存在~";
		}else {
			boolean result = flightDao.deleteFlight(index - 1);
			message = result?"删除成功~":"删除失败~";
		}
		return message;
	}

	@Override
	public void saveXML() {
		flightDao.saveXML();
	}
	@Override
	public void saveTXT(String info) {
		flightDao.saveTXT(info);
	}
}

FlightAction.java

package com.biubiubiu.dongtianbao.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.biubiubiu.dongtianbao.common.Utils;
import com.biubiubiu.dongtianbao.entity.Flight;
import com.biubiubiu.dongtianbao.service.FlightService;

/**
 * 航空管理界面层
 * 
 * @author 11142
 *
 */
public class FlightAction {

	private FlightService flightService;

	public void menu() {
		System.out.println("1  显示所有航班信息(起飞时间升序显示)");
		System.out.println("2  查询航班(起飞时间升序显示)");
		System.out.println("3  添加航班");
		System.out.println("4  删除航班");
		System.out.println("0  退出系统");
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入功能号:>>");
		try {
			int n = sc.nextInt();
			switch (n) {
			case 1:
				showAllFlight();
				break;
			case 2:
				queryFlight();
				break;
			case 3:
				addFlight();
				break;
			case 4:
				delectFlight();
				break;
			case 0:
				if (exit()) {
					return;
				}
				break;
			default:
				System.out.println("输入的序号有误,请重新输入!");
			}

		} catch (Exception e) {
			System.out.println("请输入合法序号!");
		}
		menu();
	}

	/**
	 * 显示所有航班信息
	 */
	public void showAllFlight() {
		List<Flight> list = flightService.showAllFlightsInfo();
		if (list.isEmpty()) {
			System.out.println("暂时没有航班信息~");
		} else {
			for (int i = 0; i < list.size(); i++) {
				System.out.println((i + 1) + "、" + list.get(i).getFlightNo() + "," + 
						list.get(i).getDepartureCity() + " - " + list.get(i).getArrivalCity() + 
						"," + Utils.dateToStr(list.get(i).getDepartureTime()) + " - "
						+ Utils.dateToStr(list.get(i).getArrivalTime()));
			}
			System.out.println();
		}
	}

	/**
	 * 查询航班信息
	 */
	public void queryFlight() {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入起飞城市:");
		String startCity = sc.nextLine();
		System.out.println("请输入到达城市:");
		String endCity = sc.nextLine();
		List<Flight> list = flightService.showAllFlightsInfo();
		List<String> results = new ArrayList<String>();
		String info = ""; 
		boolean flag = false;
		for(int i=0; i<list.size(); i++) {
			if(list.get(i).getDepartureCity().equals(startCity) && list.get(i).getArrivalCity().equals(endCity)) {
				flag = true;
				System.out.println("查询成功,结果如下:");
				System.out.println((i + 1) + "、" + list.get(i).getFlightNo() + "," + 
						list.get(i).getDepartureCity() + " - " + list.get(i).getArrivalCity() + 
						"," + Utils.dateToStr(list.get(i).getDepartureTime()) + " - "
						+ Utils.dateToStr(list.get(i).getArrivalTime()));
				
				info = list.get(i).getFlightNo() + "  " + list.get(i).getDepartureCity() + "  " + Utils.dateToStr(list.get(i).getDepartureTime())
				+ "  " + list.get(i).getArrivalCity() + "  " + Utils.dateToStr(list.get(i).getArrivalTime());
				results.add(info);
			}
		}
		if(!flag) {
			System.out.println("没有找到您要查询的航班信息~");
		}
		if(flag) {
			System.out.print("按任意键继续...");
			String goON = sc.next();
			System.out.println("请问是否要将查询结果导出到txt文件:(y-保存/任意键-不保存)");
			String str = sc.next();
			if(str.equalsIgnoreCase("y")) {
				for (String string : results) {
					flightService.saveTXT(string);
				}
				System.out.println("导出成功,文件在src\\main\\resources\\flights.txt");
			}
		}
	}

	/**
	 * 添加航班
	 */
	public void addFlight() {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入航班编号:");
		String flightNo = sc.nextLine();
		System.out.println("起飞城市:");
		String departureCity = sc.nextLine();
		System.out.println("起飞时间(格式为:2019-05-06 15:08:00):");
		Scanner sc2 = new Scanner(System.in);
		String departureTime = sc2.nextLine();
		System.out.println("到达城市:");
		String arrivalCity = sc.nextLine();
		System.out.println("到达时间(格式为:2019-05-06 15:08:00):");
		Scanner sc3 = new Scanner(System.in);
		String arrivalTime = sc3.nextLine();
		Flight flight = new Flight(flightNo, departureCity, arrivalCity, Utils.strToDate(departureTime), Utils.strToDate(arrivalTime));
		String message = flightService.addFlight(flight);
		System.out.println(message);
	}

	/**
	 * 删除航班
	 */
	public void delectFlight() {
		showAllFlight();
		System.out.println("请输入您要删除的航班序号:");
		Scanner sc = new Scanner(System.in);
		int index = sc.nextInt();
		String message = flightService.deleteFlight(index);
		System.out.println(message);
	}

	/**
	 * 退出系统
	 * 
	 * @return
	 */
	public boolean exit() {
		System.out.println("确定退出吗?(y/任意键返回)");
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		if (s.equalsIgnoreCase("y")) {
			System.out.println("是否保存更新XML文件?(y保存并退出/任意键直接退出)");
			String s2 = sc.next();
			if(s2.equalsIgnoreCase("y")) {
				flightService.saveXML();
				System.out.println("保存成功~");
			}
			System.out.println("程序退出成功~");
			return true;
		} else {
			System.out.println("取消了退出,程序继续运行~");
			return false;
		}
	}
}

Bean.java

package com.biubiubiu.dongtianbao.common;

import java.util.HashMap;
import java.util.Map;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Bean {
	private String id; // 存放id属性值
	private String classname;// 存放class属性值
	private Map<String, String> propertylist = new HashMap<String, String>();// 存放property标签中name属性和ref属性值
}

BeanUtil.java

package com.biubiubiu.dongtianbao.common;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class BeanUtil {
	static Map<String, Bean> map = new HashMap<String, Bean>();
	static Map<String, Object> objMap = new HashMap<String, Object>();
	static {
		try {
			InputStream is = BeanUtil.class.getClassLoader().getResourceAsStream("applicationContext.xml");
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(is);
			Element root = document.getRootElement();
			List<Element> elements = root.elements();
			for (Element element : elements) {
				String id = element.attributeValue("id");
				String classname = element.attributeValue("class");
				List<Element> propertiesList = element.elements();
				Map<String, String> properties = new HashMap<String, String>();
				for (Element element2 : propertiesList) {
					String attname = element2.attributeValue("name");
					String value = element2.attributeValue("ref");
					properties.put(attname, value);
				}
				Bean bean = new Bean(id, classname, properties);
				map.put(id, bean);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	public static <E> E getInstance(String key) {
		E obj = null;
		try {
			if (objMap.containsKey(key)) {
				obj = (E) objMap.get(key);
			} else {
				Bean bean = map.get(key);
				Class clazz = Class.forName(bean.getClassname());
				obj = (E) clazz.newInstance();
				Map<String, String> properties = bean.getPropertylist();
				if(!properties.isEmpty()) {
					for (String attribute : properties.keySet()) {
						Field field = clazz.getDeclaredField(attribute);
						field.setAccessible(true);
						field.set(obj, getInstance(properties.get(attribute)));
					}
				}
				objMap.put(key, obj);
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}

		return obj;
	}

}

Utils.java

package com.biubiubiu.dongtianbao.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
/**
 * 工具类
 */
import java.util.Date;
import java.util.HashMap;
import java.util.Map;



public class Utils {
	
	public final static String A_D = "flightDAO";
	public final static String A_S = "flightService";
	static Map<String, String> map = new HashMap<String, String>();
	static {
		map.put("flightDAO", "com.biubiubiu.dongtianbao.dao.impl.FlightDaoImpl");
		map.put("flightService", "com.biubiubiu.dongtianbao.service.impl.FlightServiceImpl");
	}
	public static String getValue(String key) {
		return map.get(key);
	}
	
	/**
	 * 把字符串转为日期
	 * @param str
	 * @return
	 */
	public static Date strToDate(String str) {
		Date date = null;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			date = df.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}


	/**
	 * 日期转为字符串
	 * @param date
	 * @return
	 */
	public static String dateToStr(Date date) {
		String str = "";
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		str = ft.format(date);
		return str;
	}
	
}

Test.java

package com.biubiubiu.dongtianbao.test;

import com.biubiubiu.dongtianbao.action.FlightAction;
import com.biubiubiu.dongtianbao.common.BeanUtil;
/**
 * 测试类
 * @author 11142
 *
 */
public class Test {
	public static void main(String[] args) {
		FlightAction flightAction = BeanUtil.getInstance("flightAction");
		flightAction.menu();
	}
}