kimi
2020-05-27 2893347bf72477c4d108e8589a0f61e3e97a990c
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
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
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
package com.highdatas.mdm.service.act.impl;
 
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.highdatas.mdm.process.canvas.ProcessDiagramGenerator;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
@Slf4j
@Service
public class RepositoryServiceImpl extends BaseServiceImpl implements com.highdatas.mdm.service.act.RepositoryService{
 
    private static final String MODEL_NAME = "name";
    private static final String MODEL_REVISION = "revision";
    private static final String MODEL_DESCRIPTION = "description";
    @Autowired
    RepositoryService service;
    @Autowired
    HistoryService historyService;
 
    @Autowired
    ObjectMapper objectMapper;
    @Value("${img.url}")
    String basePath;
    //download
    /**
     *
     * @description:  通过model获取流程图片
     * @param modelId model的id
     * @return: 图片的流
     *
     */
    @Override
    public InputStream getModelImg(String modelId) {
        InputStream resource = null;
        try{
            Model model = service.createModelQuery().modelId(modelId).singleResult();
            JsonNode editorNode = new ObjectMapper().readTree(service.getModelEditorSource(model.getId()));
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
            ProcessDiagramGenerator diagramGenerator = new ProcessDiagramGenerator();
            resource = diagramGenerator.generateDiagram(bpmnModel, "png",null,null, "宋体","宋体" ,null, null,0);
            return resource;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        finally {
            if (resource != null) {
                try {
                    resource.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    /**
     *
     * @description:  删除model
     * @param modelId model的id
     * @return: 是否删除
     *
     */
 
    @Override
    public boolean deleteModel(String modelId) {
        try {
            Model model = service.getModel(modelId);
            String deploymentId = model.getDeploymentId();
            if (deploymentId != null) {
                //TODO
                service.deleteDeployment(deploymentId,true);
            }
            service.deleteModel(modelId);
            return true;
            //resultPool.addValue("delete model successful");
        } 
        catch (Exception e) {
            e.printStackTrace();
            log.debug("delete model failed");
            return false;
        }
 
    }
    /**
     *
     * @description:  通过id获取model
     * @param modelId model的id
     * @return: model 对象
     *
     */
    public Model getModel(String modelId) {
        Model model = service.getModel(modelId);
        ObjectNode modelNode;
 
        if (model != null) {
          try {
            if (StringUtils.isNotEmpty(model.getMetaInfo())) {
              modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            } 
            else {
              modelNode = objectMapper.createObjectNode();
              modelNode.put(ModelDataJsonConstants.MODEL_NAME, model.getName());
            }
            
            modelNode.put(ModelDataJsonConstants.MODEL_ID, model.getId());
            ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(new String(service.getModelEditorSource(model.getId()), "utf-8"));
            modelNode.put("model", editorJsonNode);
 
//            resultPool.addValue("name",model.getName());
//            resultPool.addValue("description", model.getMetaInfo());
//            resultPool.addValue("modelId", modelId);
//            resultPool.addJson("model", editorJsonNode.toString());
          } 
          catch (Exception e) {
            log.error("Error creating model JSON", e);
            throw new ActivitiException("Error creating model JSON", e);
          }
        }
        return model;
    }
    /**
     *
     * @description: 保存/更新model对象
     * @param modelId model的id
     * @param request 请求对象
     * @return: 是否保存成功
     *
     */
    public boolean saveModel(String modelId, HttpServletRequest request)  {
      HashMap<String,String> hashMap = new HashMap<String, String>();
      StringBuilder builder  = new StringBuilder();
      FileOutputStream fileOutputStream2 = null;
      ByteArrayOutputStream outStream = null;
      FileOutputStream fileOutputStream = null;
      try {
          //1.1
          request.setCharacterEncoding("utf-8");
          Map<String, String[]> parameterMap = request.getParameterMap();
          Set<String> keys = parameterMap.keySet();
          for (String key : keys) {
              String[] strings = parameterMap.get(key);
              for (String string : strings) {
                  builder.append(string);
              }
              hashMap.put(key, builder.toString());
              builder.setLength(0);
          }
 
          String jsonXmlString = hashMap.get("json_xml");
          jsonXmlString = jsonXmlString.replaceAll("\\+\\+", "&&");
          hashMap.put("json_xml", jsonXmlString);
          
          Model model = service.getModel(modelId);
          Integer version = model.getVersion();
          String key = model.getKey();
          //1.2 add new model version++ 
          Model newModel = service.newModel();
          ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
          modelJson.put(MODEL_NAME, hashMap.get("name"));
          modelJson.put(MODEL_DESCRIPTION, hashMap.get("description"));
          modelJson.put(MODEL_REVISION, (version + 1));
          
          newModel.setMetaInfo(modelJson.toString());
          newModel.setVersion((version + 1));
          newModel.setName(hashMap.get("name"));
          newModel.setKey(key);
          
          //1.3
          ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(hashMap.get("json_xml").getBytes("utf-8"));
          BpmnModel bpmnModel = new BpmnJsonConverter().convertToBpmnModel(modelNode);
          if (bpmnModel.getProcesses().size() == 0) {
              return false;
          }
          byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(bpmnModel);
          String processName = newModel.getName()+ ".bpmn20.xml";
          Deployment deployment = service.createDeployment().name(newModel.getName()).addString(processName,new String(bpmnBytes,"UTF-8")).deploy();
          newModel.setDeploymentId(deployment.getId());
          newModel.setCategory(deployment.getId());
 
          service.saveModel(newModel);
          
          //1.4
          service.addModelEditorSource(newModel.getId(), hashMap.get("json_xml").getBytes("utf-8"));
          
          InputStream svgStream = new ByteArrayInputStream(hashMap.get("svg_xml").getBytes("utf-8"));
          TranscoderInput input = new TranscoderInput(svgStream);
          PNGTranscoder transcoder = new PNGTranscoder();
          outStream = new ByteArrayOutputStream();
          TranscoderOutput output = new TranscoderOutput(outStream);
          transcoder.transcode(input, output);
          final byte[] result = outStream.toByteArray();
          service.addModelEditorSourceExtra(newModel.getId(), result);
          String newModelId = newModel.getId();
          //TODO dir 2.
          String path =  basePath  + newModelId;
          File dir = new File(path);
          if (!dir.exists()) {
              dir.mkdirs();
          }
          //2.1 save model xml to server
        
          File file = new File(path,newModelId + ".bpmn20.xml");
          if (file.exists()) {
            file.delete();
          }
          log.info(file.getAbsolutePath());
          file.createNewFile();
          fileOutputStream2 = new FileOutputStream(file);
          fileOutputStream2.write(bpmnBytes);
          
          //2.2 save model png to server
          fileOutputStream = new FileOutputStream(new File(path,newModelId + ".png"));
          InputStream svgs =  new ByteArrayInputStream(hashMap.get("svg_xml").getBytes("utf-8"));
          TranscoderInput inputs = new TranscoderInput(svgs);
          TranscoderOutput outputs = new TranscoderOutput(fileOutputStream);
          transcoder.transcode(inputs, outputs);
          fileOutputStream.flush(); 
          return true;
        } catch (Exception e) {
            log.error("Error saving model", e);
            return false;
        }
          finally {
              try {
                  if (fileOutputStream != null) {
                      fileOutputStream.close();
                }
                  if (fileOutputStream2 != null) {
                      fileOutputStream2.close();
                }
                  if (outStream != null) {
                      outStream.close();
                }
                
            } 
              catch (IOException e) {
                  log.error("Error  close ioStream ", e);
                e.printStackTrace();
                return false;
            }
          }
    }
}