ImportExcel.java 12.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
package leaf.plugin.dataimport;

import leaf.database.service.SqlServiceContext;
import leaf.plugin.csv.CsvParse;
import leaf.plugin.poi.usermodel.ExcelParse;
import leaf.service.ServiceInstance;
import leaf.service.http.HttpServiceInstance;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import uncertain.composite.CompositeMap;
import uncertain.composite.TextParser;
import uncertain.core.UncertainEngine;
import uncertain.proc.AbstractEntry;
import uncertain.proc.ProcedureRunner;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

public class ImportExcel extends AbstractEntry {
	public static final String XLS_KEY = ".xls";
	public static final String XLSX_KEY = ".xlsx";
	public static final String CSV_KEY = ".csv";
	public static final String TXT_KEY = ".txt";
	String maxFileSize = null;
	public String fileName;
	public String separator = ",";
	public String header_id;
	public String user_id = "${/session/@user_id}";
	public String template_code;
	public String job_id;
	public String attribute1;
	public String attribute2;
	public String attribute3;
	public String attribute4;
	public String attribute5 = "N"; // 是否保存文件,不为N时保存文件。一般格式为  filePath,tableName,tablePkValue
	public String dataSourceName;
	UncertainEngine mUncertainEngine;
	Connection conn;
	CallableStatement lineCstm = null;
	boolean is_first = true;
	int count = 0;
	int maxcell;

	public ImportExcel(UncertainEngine uncertainEngine) {
		mUncertainEngine = uncertainEngine;
	}

	public String getTemplate_code() {
		return template_code;
	}

	public void setTemplate_code(String template_code) {
		this.template_code = template_code;
	}

	public String getDataSourceName() {
		return dataSourceName;
	}

	public void setDataSourceName(String dataSourceName) {
		this.dataSourceName = dataSourceName;
	}

	public void run(ProcedureRunner runner) throws Exception {
		CompositeMap context = runner.getContext();
		validatePara(context);
		HttpServiceInstance serviceInstance = (HttpServiceInstance) ServiceInstance
				.getInstance(context);
		SqlServiceContext sqlServiceContext = SqlServiceContext
				.createSqlServiceContext(context);

		conn = sqlServiceContext.getNamedConnection(dataSourceName);

		if (conn == null) {
			sqlServiceContext.initConnection(
					mUncertainEngine.getObjectRegistry(), dataSourceName);
			conn = sqlServiceContext.getNamedConnection(dataSourceName);
		}
		if (dataSourceName == null && conn == null) {
			conn = sqlServiceContext.getConnection();
		}

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload up = new ServletFileUpload(factory);
		long fileSizeMaxLong = 10 * 1024 * 1024;
		if (this.getMaxFileSize() != null)
			fileSizeMaxLong = Long.parseLong(this.getMaxFileSize());
		up.setSizeMax(fileSizeMaxLong);
		List items = up.parseRequest(serviceInstance.getRequest());
		Iterator i = items.iterator();
		while (i.hasNext()) {
			FileItem fileItem = (FileItem) i.next();
			if (!fileItem.isFormField()) {
				fileName = fileItem.getName();
				saveHead();
				String suffix = fileName.substring(fileName.lastIndexOf("."));
				parseFile(fileItem.getInputStream(), suffix.toLowerCase(), this);

				// 新增 2016-12-19 yangyang 在导入excel同时保存文件到服务器
				if(!"N".equals(attribute5)){  // 不为N时保存文件
					String[] parts = attribute5.split(",");
					if(parts.length == 3){  // 由三个部分组成,以‘,’分割
						String filePath = parts[0].replaceAll("\\\\", "/");
						String tableName = parts[1];
						String tablePkValue = parts[2];
						InputStream inputStream = fileItem.getInputStream();
						if(!filePath.endsWith("/")){
							filePath = filePath + "/";
						}
						filePath = filePath + UUID.randomUUID().toString();
						saveParseExcel(inputStream, filePath,fileName,suffix,tableName,tablePkValue);
					}else{
						throw new IllegalArgumentException("attribute5没有按照正确的格式设定savePath,tableName,tablePkValue");
					}
				}
				// 新增结束 2016-12-19
				executeBatchUpdate();
			}
		}
	}

	/**
	 *
	 * @param in 文件输入流
	 * @param savePath 文件保存的路径
	 * @param fileName 文件名
	 * @param fileTypeCode 文件类型
	 * @throws Exception
	 * <p>
	 *  当in为null时,抛出IllegalArgumentException.
	 *  可能还会抛出SQLException
	 *  </p>
	 */
	void saveParseExcel(InputStream in, String savePath, String fileName,
						String fileTypeCode,String tableName,String tablePkValue)
			throws Exception{
		if(in == null){
			throw new IllegalArgumentException();
		}
		FileOutputStream fout = new FileOutputStream(savePath);
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
		try {
			byte[] buffer = new byte[1024];
			int len = 0;
			int size = 0;
			while ((len = in.read(buffer)) > 0) {
				fout.write(buffer, 0, len);
				size += len;
			}
			fout.flush();
			fout.close();
			in.close();

			// 保存记录到数据库
			//fnd_atm_attachment

			String sql = "{call fnd_atm_attachment_pkg.insert_fnd_atm_attachment(?,?,?,?,?,?,?,?,?) }";
			CallableStatement cstm = conn.prepareCall(sql);
			cstm.registerOutParameter(1, java.sql.Types.NUMERIC);
			cstm.setString(2, "fnd_atm_attachment_multi"); // v_source_type_code
			cstm.setString(3, "123"); // v_source_pk_value
			cstm.setString(4, fileTypeCode); // v_file_type_code
			cstm.setString(5, "application/vnd.ms-excel"); // v_mime_type
			cstm.setString(6, fileName); // v_file_name
			cstm.setLong(7, size); // v_file_size
			cstm.setString(8, savePath); // v_file_path
			cstm.setLong(9, Long.valueOf(user_id)); // v_user_id
			cstm.execute();
			Long aid = cstm.getLong(1);
			cstm.close();

			//fnd_atm_attachment_multi
			sql = "{call fnd_atm_attachment_all_pkg.insert_fnd_attachment_multi(?,?,?,?)}";
			cstm = conn.prepareCall(sql);
			cstm.setString(1, tableName);// tableName
			cstm.setString(2, tablePkValue);// tablePkValue
			cstm.setLong(3, aid);// attachment_id
			cstm.setLong(4, Long.valueOf(user_id));// user_id
			cstm.execute();
			cstm.close();
		}finally{
			if(fout!=null){
				fout.close();
			}
			if(in!=null){
				in.close();
			}
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
		}

	}

	void saveHead() throws SQLException {
		CallableStatement cstm = null;
		String headSql = "fnd_interface_load_pkg.ins_fnd_interface_headers(?,?,?,?,?,?,?,?,?,?,?)";
		try {
			cstm = conn.prepareCall("{call " + headSql + "}");
			cstm.setLong(1, new Long(header_id));
			if (job_id == null)
				cstm.setNull(2, java.sql.Types.NUMERIC);
			else
				cstm.setLong(2, new Long(job_id));
			cstm.setString(3, "NEW");
			cstm.setString(4, user_id);
			cstm.setString(5, fileName);
			if (template_code == null)
				cstm.setNull(6, java.sql.Types.VARCHAR);
			else
				cstm.setString(6, template_code);
			if (attribute1 == null)
				cstm.setNull(7, java.sql.Types.VARCHAR);
			else
				cstm.setString(7, attribute1);
			if (attribute2 == null)
				cstm.setNull(8, java.sql.Types.VARCHAR);
			else
				cstm.setString(8, attribute2);
			if (attribute3 == null)
				cstm.setNull(9, java.sql.Types.VARCHAR);
			else
				cstm.setString(9, attribute3);
			if (attribute4 == null)
				cstm.setNull(10, java.sql.Types.VARCHAR);
			else
				cstm.setString(10, attribute4);
			if (attribute5 == null)
				cstm.setNull(11, java.sql.Types.VARCHAR);
			else
				cstm.setString(11, attribute5);
			cstm.execute();
		} finally {
			if (cstm != null)
				cstm.close();
		}
	}

	void parseFile(InputStream is, String suffix, ImportExcel importExcel)
			throws Exception {
		try {
			if (XLS_KEY.equals(suffix) || XLSX_KEY.equals(suffix)) {
				ExcelParse xlsParse = new ExcelParse();
				xlsParse.parseFile(is, importExcel, suffix);
			} else if (CSV_KEY.equals(suffix) || TXT_KEY.equals(suffix)) {
				if (separator == null)
					throw new IllegalArgumentException("separator is undefined");
				CsvParse cvsParser = new CsvParse();
				cvsParser.parseFile(is, importExcel);
			}
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {

				}
			}
		}
	}

	void validatePara(CompositeMap context) {
		header_id = TextParser.parse(header_id, context);
		if (header_id == null||"".equals(header_id))
			throw new IllegalArgumentException("header_id is undefined");
		user_id = TextParser.parse(user_id, context);
		if (user_id == null && "".equals(user_id))
			throw new IllegalArgumentException("user_id is undefined");
		template_code = TextParser.parse(template_code, context);
		job_id = TextParser.parse(job_id, context);
		attribute1 = TextParser.parse(attribute1, context);
		attribute2 = TextParser.parse(attribute2, context);
		attribute3 = TextParser.parse(attribute3, context);
		attribute4 = TextParser.parse(attribute4, context);
		attribute5 = TextParser.parse(attribute5, context);
	}

	public void saveLine(CompositeMap data, int rownum) throws SQLException {
		boolean is_new = data.getBoolean("is_new", false);
		count++;
		if (validateData(data))
			return;
		if (is_first || is_new) {
			executeBatchUpdate();
			generateSql();
			is_first = false;
			count=0;
		}
		addBatchUpdate(data, rownum);
		if (count % 1000 == 0){
			executeBatchUpdate();
			count=0;
		}
	}

	boolean validateData(CompositeMap data) {
		boolean isValidate = true;
		if (data.getLong("maxCell") == null)
			return isValidate;
		if (maxcell != data.getInt("maxCell")) {
			maxcell = data.getInt("maxCell");
			this.is_first = true;
		}
		for (int i = 0; i < maxcell; i++) {
			String valueString = data.getString("C" + i);
			if (valueString != null && !"".equals(valueString)) {
				isValidate = false;
				break;
			}
		}
		return isValidate;
	}

	void generateSql() throws SQLException {
		StringBuffer lineSql = new StringBuffer(
				"fnd_interface_load_pkg.ins_fnd_interface_lines(?,?,?,?,?,?,?");
		for (int i = 0; i < maxcell; i++) {
			lineSql.append(",?");
		}
		lineSql.append(")");
		this.lineCstm = conn.prepareCall("{call " + lineSql + "}");
	}

	void executeBatchUpdate() throws SQLException {
		if (lineCstm != null) {
			try {
				lineCstm.executeBatch();
				is_first = true;
			} finally {
				if (this.lineCstm != null) {
					try {
						lineCstm.close();
					} catch (Exception e) {

					}
					this.lineCstm = null;
				}
			}
		}
	}

	void addBatchUpdate(CompositeMap data, int rownum) throws SQLException {
		try {
			lineCstm.setLong(1, new Long(header_id));
			lineCstm.setNull(2, java.sql.Types.VARCHAR);
			lineCstm.setNull(3, java.sql.Types.VARCHAR);
			lineCstm.setString(4, user_id);
			lineCstm.setLong(5, rownum);
			String sheetName = data.getString("sheetName");
			if (sheetName == null)
				lineCstm.setNull(6, java.sql.Types.VARCHAR);
			else
				lineCstm.setString(6, sheetName);
			lineCstm.setNull(7, java.sql.Types.NUMERIC);
			String valueString;
			for (int i = 0; i < maxcell; i++) {
				valueString = data.getString("C" + i);
				if (valueString == null)
					lineCstm.setNull(8 + i, java.sql.Types.VARCHAR);
				else
					lineCstm.setString(8 + i, valueString);
			}
			lineCstm.addBatch();
		} catch (SQLException e) {
			if (lineCstm != null)
				try {
					lineCstm.close();
				} catch (SQLException ex) {
				}
			throw e;
		}
	}

	public String getHeader_id() {
		return header_id;
	}

	public void setHeader_id(String header_id) {
		this.header_id = header_id;
	}

	public String getSeparator() {
		return separator;
	}

	public void setSeparator(String separator) {
		this.separator = separator;
	}

	public String getUser_id() {
		return user_id;
	}

	public void setUser_id(String user_id) {
		this.user_id = user_id;
	}

	public String getJob_id() {
		return job_id;
	}

	public void setJob_id(String job_id) {
		this.job_id = job_id;
	}

	public String getAttribute1() {
		return attribute1;
	}

	public void setAttribute1(String attribute1) {
		this.attribute1 = attribute1;
	}

	public String getAttribute2() {
		return attribute2;
	}

	public void setAttribute2(String attribute2) {
		this.attribute2 = attribute2;
	}

	public String getAttribute3() {
		return attribute3;
	}

	public void setAttribute3(String attribute3) {
		this.attribute3 = attribute3;
	}

	public String getAttribute4() {
		return attribute4;
	}

	public void setAttribute4(String attribute4) {
		this.attribute4 = attribute4;
	}

	public String getAttribute5() {
		return attribute5;
	}

	public void setAttribute5(String attribute5) {
		this.attribute5 = attribute5;
	}

	public String getMaxFileSize() {
		return maxFileSize;
	}

	public void setMaxFileSize(String maxFileSize) {
		this.maxFileSize = maxFileSize;
	}

	public static void main(String[] args) throws Exception {
		ImportExcel importExcel = new ImportExcel(null);
		InputStream is = new FileInputStream(
				"/Volumes/MacintoshHD/download/a.xls");
		importExcel.parseFile(is, ".xls", importExcel);
	}
}