package cn.com.qmth.im; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import cn.com.qmth.multithread.Consumer; import cn.com.qmth.param.Param; import cn.com.qmth.run.ImportPaperByCourse; import okhttp3.Response; public class MyConsumer extends Consumer { private static Logger logger = LogManager.getLogger(MyConsumer.class); @Override public void consume(ConsumerDto dto) { importCoursePaper(dto); ImportPaperByCourse.addDisposeCount(); } private void importCoursePaper(ConsumerDto dto) { File file = new File(Param.dataDir + "/paper/" + dto.getIc().getSubjectCode() + "/"); if (!file.exists()) { return; } File zfile = new File(Param.dataDir + "/paper/" + dto.getIc().getSubjectCode() + ".zip"); try { List files = new ArrayList<>(); getPaperFile(file, files); if (files.size() == 0) { throw new NoPaperException("1000", "没有试卷信息:" + file.getName()); } if (zfile.exists()) { zfile.delete(); } FileUtil.doZip(file, zfile); submitZip(dto, zfile); } catch (NoPaperException e1) { logger.debug("忽略:" + e1.getDesc()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (zfile.exists()) { zfile.delete(); } } } private void getPaperFile(File file, List ret) { if (file.isFile()) { if (file.getName().endsWith(".json")) { ret.add(file); } return; } else { for (File paperDir : file.listFiles()) { getPaperFile(paperDir, ret); } } } private void submitZip(ConsumerDto dto, File zfile) { List cs = dto.getIc().getCourses().stream().map(e -> e.getCode()).collect(Collectors.toList()); Map params = Maps.newHashMap(); String courseCodes = StringUtils.join(cs, ","); params.put("rootOrgId", Param.rootOrgId); params.put("batch", dto.getBatch()); params.put("courseCodes", courseCodes); Map headers = Maps.newHashMap(); headers.put("key", Param.key); headers.put("token", Param.token); List fileList = Lists.newArrayList(); fileList.add(new FormFilePart("dataFile", zfile.getName(), zfile)); Response resp = null; try { // OKHttpUtil.initOkHttpClient(); resp = OKHttpUtil.call(HttpMethod.POST, Param.host + "/api/ecs_ques/importYunkaiPaper", headers, params, fileList); if (resp.code() != 200) { throw new Exception( zfile.getName() + "| courseCodes:" + courseCodes + "| body:" + resp.body().string()); } else { logger.debug("成功处理:" + zfile.getName()); } } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(resp); } } }