@SuppressWarnings("unchecked")
    public void process(Exchange exchange) throws Exception {
      CxfPayload<SoapHeader> in = exchange.getIn().getBody(CxfPayload.class);

      // verify request
      assertEquals(1, in.getBody().size());

      Map<String, String> ns = new HashMap<String, String>();
      ns.put("ns", MtomTestHelper.SERVICE_TYPES_NS);
      ns.put("xop", MtomTestHelper.XOP_NS);

      XPathUtils xu = new XPathUtils(ns);
      Element body = new XmlConverter().toDOMElement(in.getBody().get(0));
      Element ele =
          (Element) xu.getValue("//ns:Detail/ns:photo/xop:Include", body, XPathConstants.NODE);
      String photoId = ele.getAttribute("href").substring(4); // skip "cid:"
      assertEquals(MtomTestHelper.REQ_PHOTO_CID, photoId);

      ele = (Element) xu.getValue("//ns:Detail/ns:image/xop:Include", body, XPathConstants.NODE);
      String imageId = ele.getAttribute("href").substring(4); // skip "cid:"
      assertEquals(MtomTestHelper.REQ_IMAGE_CID, imageId);

      DataHandler dr = exchange.getIn().getAttachment(photoId);
      assertEquals("application/octet-stream", dr.getContentType());
      MtomTestHelper.assertEquals(
          MtomTestHelper.REQ_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream()));

      dr = exchange.getIn().getAttachment(imageId);
      assertEquals("image/jpeg", dr.getContentType());
      MtomTestHelper.assertEquals(
          MtomTestHelper.requestJpeg, IOUtils.readBytesFromStream(dr.getInputStream()));

      // create response
      List<Source> elements = new ArrayList<Source>();
      elements.add(
          new DOMSource(
              DOMUtils.readXml(new StringReader(MtomTestHelper.RESP_MESSAGE))
                  .getDocumentElement()));
      CxfPayload<SoapHeader> sbody =
          new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(), elements, null);
      exchange.getOut().setBody(sbody);
      exchange
          .getOut()
          .addAttachment(
              MtomTestHelper.RESP_PHOTO_CID,
              new DataHandler(
                  new ByteArrayDataSource(
                      MtomTestHelper.RESP_PHOTO_DATA, "application/octet-stream")));

      exchange
          .getOut()
          .addAttachment(
              MtomTestHelper.RESP_IMAGE_CID,
              new DataHandler(new ByteArrayDataSource(MtomTestHelper.responseJpeg, "image/jpeg")));
    }
  public void overwriteTemplate(Template template) throws CoreException {
    try {
      // get the directory
      String projectName = folderSelected.getProject().getName();
      IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
      IProject project = root.getProject(projectName);
      IPath pathFolder = folderSelected.getProjectRelativePath();
      String templateFileName = template.getFileName();

      DataHandler dh = template.getContent();
      InputStream is = dh.getInputStream();

      IPath pathNewFile = pathFolder.append(templateFileName);
      IFile newFile = project.getFile(pathNewFile);

      // create new File
      if (newFile.exists()) {
        newFile.delete(true, null);
      }
      newFile.create(is, true, null);
      // set the dirty property to true
      newFile.setPersistentProperty(SpagoBIStudioConstants.DIRTY_MODEL, "true");

    } catch (IOException e1) {

      MessageDialog.openError(
          PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
          "Error",
          "Error in writing the file");
      logger.error("Error in writing the file", e1);

      return;
    }
  }
Пример #3
0
 public void addEndpointTemplate(DataHandler dh) throws IOException, XMLStreamException {
   XMLStreamReader parser =
       XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream());
   // create the builder
   StAXOMBuilder builder = new StAXOMBuilder(parser);
   OMElement endpointTemplate = builder.getDocumentElement();
   endpointTemplateAdminStub.addEndpointTemplate(endpointTemplate.toString());
 }
 public void addExistingConfiguration(DataHandler dh)
     throws IOException, LocalEntryAdminException, XMLStreamException {
   XMLStreamReader parser =
       XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream());
   StAXOMBuilder builder = new StAXOMBuilder(parser);
   OMElement configSourceElem = builder.getDocumentElement();
   configServiceAdminStub.addExistingConfiguration(configSourceElem.toString());
 }
Пример #5
0
 public void addLocalEntry(String sessionCookie, DataHandler dh)
     throws LocalEntryAdminException, IOException, XMLStreamException {
   AuthenticateStub.authenticateStub(sessionCookie, localEntryAdminServiceStub);
   XMLStreamReader parser =
       XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream());
   // create the builder
   StAXOMBuilder builder = new StAXOMBuilder(parser);
   OMElement localEntryElem = builder.getDocumentElement();
   localEntryAdminServiceStub.addEntry(localEntryElem.toString());
 }
Пример #6
0
  /**
   * adding sequence
   *
   * @param dh
   * @throws SequenceAdminServiceSequenceEditorException
   * @throws IOException
   * @throws XMLStreamException
   */
  public void addSequence(DataHandler dh)
      throws SequenceAdminServiceSequenceEditorException, IOException, XMLStreamException {

    XMLStreamReader parser =
        XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream());
    // create the builder
    StAXOMBuilder builder = new StAXOMBuilder(parser);
    OMElement sequenceElem = builder.getDocumentElement();
    sequenceAdminServiceStub.addSequence(sequenceElem);
  }
Пример #7
0
 private static String addStudyPOIsAndGetPatientID(
     List<ParticipantObjectIdentification> studyPOIs, RetrieveDocumentSetResponseType rsp) {
   Attributes attrs = null;
   String studyIUID, classUID;
   HashMap<String, HashMap<String, List<String>>> studySopClassMap =
       new HashMap<String, HashMap<String, List<String>>>();
   HashMap<String, List<String>> sopClassInstanceMap;
   List<String> instances;
   for (DocumentResponse doc : rsp.getDocumentResponse()) {
     BufferedInputStream is = null;
     DicomInputStream dis = null;
     try {
       DataHandler dh = doc.getDocument();
       is = new BufferedInputStream(dh.getInputStream(), BUF_SIZE);
       is.mark(BUF_SIZE);
       dis = new DicomInputStream(new BufferedInputStream(is));
       attrs = dis.readDataset(-1, Tag.SeriesInstanceUID);
       is.reset();
       doc.setDocument(new DataHandler(new InputStreamDataSource(is, dh.getContentType())));
       studyIUID = attrs.getString(Tag.StudyInstanceUID);
       classUID = attrs.getString(Tag.SOPClassUID);
       sopClassInstanceMap = studySopClassMap.get(studyIUID);
       if (sopClassInstanceMap == null) {
         sopClassInstanceMap = new HashMap<String, List<String>>();
         studySopClassMap.put(studyIUID, sopClassInstanceMap);
         instances = null;
       } else {
         instances = sopClassInstanceMap.get(classUID);
       }
       if (instances == null) {
         instances = new ArrayList<String>();
         sopClassInstanceMap.put(classUID, instances);
       }
       instances.add(attrs.getString(Tag.SOPInstanceUID));
     } catch (IOException x) {
       log.warn("Failed to read DICOM attachment! instanceUID:" + doc.getDocumentUniqueId(), x);
     }
   }
   for (Entry<String, HashMap<String, List<String>>> e : studySopClassMap.entrySet()) {
     ParticipantObjectDescription pod = new ParticipantObjectDescription();
     studyPOIs.add(createStudyPOI(e.getKey(), pod));
     for (Entry<String, List<String>> e1 : e.getValue().entrySet()) {
       SOPClass sc = new SOPClass();
       sc.setUID(e1.getKey());
       sc.setNumberOfInstances(e1.getValue().size());
       for (String iuid : e1.getValue()) {
         Instance inst = new Instance();
         inst.setUID(iuid);
         sc.getInstance().add(inst);
       }
       pod.getSOPClass().add(sc);
     }
   }
   return attrs == null ? null : attrs.getString(Tag.PatientID);
 }
Пример #8
0
 @Override
 protected byte[] getBytes(Object object) {
   DataHandler handler = (DataHandler) object;
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   try {
     InputStream stream = handler.getInputStream();
     IOUtils.copy(stream, baos);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
   return baos.toByteArray();
 }
Пример #9
0
  public void setCommandContext(String var1, DataHandler var2) throws IOException {
    InputStream var3 = var2.getInputStream();
    ByteArrayOutputStream var4 = new ByteArrayOutputStream();
    byte[] var5 = new byte[4096];

    for (int var6 = var3.read(var5); var6 != -1; var6 = var3.read(var5)) {
      var4.write(var5, 0, var6);
    }

    var3.close();
    String var7 = var4.toString();
    this.setText(var7);
  }
Пример #10
0
  private void manageDetails(final GetItemResponse response, final DataHandler stream) {

    InputStream is = null;
    ContentHandler contenthandler = new BodyContentHandler();
    Metadata metadata = new Metadata();
    // metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName());
    Parser parser = new AutoDetectParser();
    ParseContext context = new ParseContext();

    try {
      is = stream.getInputStream();

      parser.parse(is, contenthandler, metadata, context);
      is.close();
      is.reset();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (TikaException e) {
      e.printStackTrace();
    }

    String contentAuthorValue = metadata.get(Metadata.AUTHOR);
    String contentAuthorKey = currentProperties.getProperty(KpeopleLabel.getCorePropertiesAuthor());
    if (contentAuthorValue != null) {
      eventResult.setDetail(contentAuthorKey, contentAuthorValue);
    }

    String contentCreationDateValue = metadata.get(Metadata.CREATION_DATE);
    String contentCreationDateKey =
        currentProperties.getProperty(KpeopleLabel.getCorePropertiesCreationDate());
    if (contentCreationDateValue != null) {
      eventResult.setDetail(contentCreationDateKey, contentCreationDateValue);
    }

    String contentKeywordsValue = metadata.get(Metadata.KEYWORDS);
    String contentKeywordsKey =
        currentProperties.getProperty(KpeopleLabel.getCorePropertiesKeywords());
    if (contentKeywordsValue != null) {
      eventResult.setDetail(contentKeywordsKey, contentKeywordsValue);
    }

    String[] names = metadata.names();

    /*
     * for (int i = 0; i < names.length; i++) {
     * System.out.println(names[i]); }
     */

  }
Пример #11
0
  private void manageAttachments(KpeopleAction action, DataHandler stream) throws IOException {

    InputStream is = null;
    String hashcode = null;
    try {
      is = stream.getInputStream();
      hashcode = Hashcode.getHashcode(is, Hashcode.SHA512);
    } catch (IOException e) {
      e.printStackTrace();
      throw e;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }

    String path = (String) currentProperties.get(KpeopleLabel.getEventXMLPath());
    try {
      path = ActionDataProcessorUtil.checkEventXMLPath(path);
    } catch (Exception e1) {
      e1.printStackTrace();
    }

    FileOutputStream outputStream = null;
    File tmpFilePath = null;
    try {
      path = path + action.getIdAction() + "-" + fileName;
      tmpFilePath = new File(path);
      outputStream = new FileOutputStream(tmpFilePath);
      stream.writeTo(outputStream);

      outputStream.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // ActionDataProcessorUtil.deleteEventFile(tmpFilePath);

    String idAttachmentId = Long.toString(action.getIdAction()) + "-" + hashcode.substring(0, 6);

    KpeopleAttachment attachment = new KpeopleAttachment();
    attachment.setAttachmentName(fileName);
    attachment.setAttachmentHashcode(hashcode);
    attachment.setAttachmentData(path);
    attachment.setIdAttachment(idAttachmentId);
    attachment.setAttachmentType(eventResult.getContentType());

    eventResult.addAttachment(attachment);
  }
Пример #12
0
 public static boolean writeData(DataHandler dh, long size, FileOutputStream out)
     throws IOException {
   byte[] dataBuf = new byte[4096];
   long sizeCounter = 0;
   //		FileOutputStream out = null;
   BufferedInputStream br = null;
   InputStream in = dh.getInputStream();
   br = new BufferedInputStream(in);
   try {
     int numBytes;
     while ((numBytes = br.read(dataBuf)) != -1) {
       sizeCounter += numBytes;
       if (sizeCounter <= size) {
         out.write(dataBuf, 0, numBytes);
       }
     }
   } finally {
     br.close();
     out.close();
   }
   return true;
 }
 /**
  * <b>function:</b>传递文件
  *
  * @author hoojo
  * @createDate Dec 18, 2010 1:27:58 PM
  * @param handler DataHandler这个参数必须
  * @param fileName 文件名称
  * @return upload Info
  */
 public String upload(DataHandler handler, String fileName) {
   if (fileName != null && !"".equals(fileName)) {
     File file = new File("D:/" + fileName);
     if (handler != null) {
       InputStream is = null;
       FileOutputStream fos = null;
       try {
         is = handler.getInputStream();
         fos = new FileOutputStream(file);
         byte[] buff = new byte[1024 * 8];
         int len = 0;
         while ((len = is.read(buff)) > 0) {
           fos.write(buff, 0, len);
         }
       } catch (FileNotFoundException e) {
         return "fileNotFound";
       } catch (Exception e) {
         return "upload File failure";
       } finally {
         try {
           if (fos != null) {
             fos.flush();
             fos.close();
           }
           if (is != null) {
             is.close();
           }
         } catch (Exception e) {
           e.printStackTrace();
         }
       }
       return "file absolute path:" + file.getAbsolutePath();
     } else {
       return "handler is null";
     }
   } else {
     return "fileName is null";
   }
 }
 private byte[] getFileContent(SDKFile importExportSDKFile) throws NotAllowedOperationException {
   byte[] toReturn = null;
   logger.debug("IN");
   int maxSize = ImportUtilities.getImportFileMaxSize();
   logger.debug("Import/export file max size: " + maxSize);
   if (importExportSDKFile != null) {
     InputStream is = null;
     try {
       DataHandler dh = importExportSDKFile.getContent();
       is = dh.getInputStream();
       try {
         toReturn = SpagoBIUtilities.getByteArrayFromInputStream(is, maxSize);
       } catch (SecurityException e) {
         logger.error(
             "A security exception was thrown when getting import/export file content: file is too big",
             e);
         NotAllowedOperationException ex = new NotAllowedOperationException();
         ex.setFaultString("File in input is too big");
         throw ex;
       }
     } catch (NotAllowedOperationException e) {
       throw e;
     } catch (Exception e) {
       if (is != null) {
         try {
           is.close();
         } catch (IOException ioe) {
           logger.error("Error closing input stream of attachment", ioe);
         }
       }
       throw new SpagoBIRuntimeException("Error while getting SDK file content", e);
     } finally {
       logger.debug("OUT");
     }
   }
   return toReturn;
 }
Пример #15
0
  /**
   * Prepares the mediator for the invocation of an external script
   *
   * @param synCtx MessageContext script
   * @throws ScriptException For any errors , when compile the script
   */
  protected synchronized void prepareExternalScript(MessageContext synCtx) throws ScriptException {

    // TODO: only need this synchronized method for dynamic registry entries. If there was a way
    // to access the registry entry during mediator initialization then for non-dynamic entries
    // this could be done just the once during mediator initialization.

    // Derive actual key from xpath expression or get static key
    String generatedScriptKey = key.evaluateValue(synCtx);
    Entry entry = synCtx.getConfiguration().getEntryDefinition(generatedScriptKey);
    boolean needsReload =
        (entry != null) && entry.isDynamic() && (!entry.isCached() || entry.isExpired());
    synchronized (resourceLock) {
      if (scriptSourceCode == null || needsReload) {
        Object o = synCtx.getEntry(generatedScriptKey);
        if (o instanceof OMElement) {
          scriptSourceCode = ((OMElement) (o)).getText();
          scriptEngine.eval(scriptSourceCode);
        } else if (o instanceof String) {
          scriptSourceCode = (String) o;
          scriptEngine.eval(scriptSourceCode);
        } else if (o instanceof OMText) {

          DataHandler dataHandler = (DataHandler) ((OMText) o).getDataHandler();
          if (dataHandler != null) {
            BufferedReader reader = null;
            try {
              reader = new BufferedReader(new InputStreamReader(dataHandler.getInputStream()));
              scriptEngine.eval(reader);

            } catch (IOException e) {
              handleException("Error in reading script as a stream ", e, synCtx);
            } finally {

              if (reader != null) {
                try {
                  reader.close();
                } catch (IOException e) {
                  handleException("Error in closing input stream ", e, synCtx);
                }
              }
            }
          }
        }
      }
    }

    // load <include /> scripts; reload each script if needed
    for (Value includeKey : includes.keySet()) {

      String includeSourceCode = (String) includes.get(includeKey);

      String generatedKey = includeKey.evaluateValue(synCtx);

      Entry includeEntry = synCtx.getConfiguration().getEntryDefinition(generatedKey);
      boolean includeEntryNeedsReload =
          (includeEntry != null)
              && includeEntry.isDynamic()
              && (!includeEntry.isCached() || includeEntry.isExpired());
      synchronized (resourceLock) {
        if (includeSourceCode == null || includeEntryNeedsReload) {
          log.debug("Re-/Loading the include script with key " + includeKey);
          Object o = synCtx.getEntry(generatedKey);
          if (o instanceof OMElement) {
            includeSourceCode = ((OMElement) (o)).getText();
            scriptEngine.eval(includeSourceCode);
          } else if (o instanceof String) {
            includeSourceCode = (String) o;
            scriptEngine.eval(includeSourceCode);
          } else if (o instanceof OMText) {

            DataHandler dataHandler = (DataHandler) ((OMText) o).getDataHandler();
            if (dataHandler != null) {
              BufferedReader reader = null;
              try {
                reader = new BufferedReader(new InputStreamReader(dataHandler.getInputStream()));
                scriptEngine.eval(reader);

              } catch (IOException e) {
                handleException("Error in reading script as a stream ", e, synCtx);
              } finally {

                if (reader != null) {
                  try {
                    reader.close();
                  } catch (IOException e) {
                    handleException("Error in closing input" + " stream ", e, synCtx);
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  protected void createProcess() throws Exception {
    try {
      if (this.processNameT.getValue().compareTo("") == 0
          || this.nativeTypesLB.getSelectedItem() == null
          || this.nativeTypesLB.getSelectedItem() != null
              && this.nativeTypesLB.getSelectedItem().getLabel().compareTo("") == 0) {
        Messagebox.show(
            "Please enter a value for each mandatory field.",
            "Attention",
            Messagebox.OK,
            Messagebox.ERROR);
      } else {
        String domain = this.domainCB.getValue();
        String processName = this.processNameT.getValue();
        String owner = UserSessionManager.getCurrentUser().getUsername();
        String nativeType = this.nativeTypesLB.getSelectedItem().getLabel();
        boolean makePublic = this.makePublicCb.isChecked();
        String versionNumber = "1.0";
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
        String creationDate = dateFormat.format(new Date());

        DataHandler initialNativeFormat =
            getService()
                .readInitialNativeFormat(
                    nativeType, null, null, owner, processName, "0.0", creationDate);

        // Documentation and Last Update are set to NULL & No Canoniser properties are used
        // TODO show canoniser properties
        Integer folderId = 0;
        if (UserSessionManager.getCurrentFolder() != null) {
          folderId = UserSessionManager.getCurrentFolder().getId();
        }

        ImportProcessResultType importResult =
            getService()
                .importProcess(
                    owner,
                    folderId,
                    nativeType,
                    processName,
                    versionNumber,
                    initialNativeFormat.getInputStream(),
                    domain,
                    null,
                    creationDate,
                    null,
                    makePublic,
                    new HashSet<RequestParameterType<?>>());

        this.mainC.displayNewProcess(importResult.getProcessSummary());
        this.mainC.showPluginMessages(importResult.getMessage());

        /* keep list of domains update */
        this.domainCB.addItem(domain);

        /* call editor */
        editProcess(importResult.getProcessSummary());
        closePopup();
      }
    } catch (WrongValueException | IOException | ExceptionImport e) {
      e.printStackTrace();
      Messagebox.show(
          "Creation failed (" + e.getMessage() + ")", "Attention", Messagebox.OK, Messagebox.ERROR);
    }
  }
  protected RestVariable createBinaryExecutionVariable(
      Execution execution,
      int responseVariableType,
      UriInfo uriInfo,
      boolean isNew,
      MultipartBody multipartBody) {

    boolean debugEnabled = log.isDebugEnabled();
    Response.ResponseBuilder responseBuilder = Response.ok();

    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments =
        multipartBody.getAllAttachments();

    int attachmentSize = attachments.size();

    if (attachmentSize <= 0) {
      throw new ActivitiIllegalArgumentException("No Attachments found with the request body");
    }
    AttachmentDataHolder attachmentDataHolder = new AttachmentDataHolder();

    for (int i = 0; i < attachmentSize; i++) {
      org.apache.cxf.jaxrs.ext.multipart.Attachment attachment = attachments.get(i);

      String contentDispositionHeaderValue = attachment.getHeader("Content-Disposition");
      String contentType = attachment.getHeader("Content-Type");

      if (debugEnabled) {
        log.debug("Going to iterate:" + i);
        log.debug("contentDisposition:" + contentDispositionHeaderValue);
      }

      if (contentDispositionHeaderValue != null) {
        contentDispositionHeaderValue = contentDispositionHeaderValue.trim();

        Map<String, String> contentDispositionHeaderValueMap =
            Utils.processContentDispositionHeader(contentDispositionHeaderValue);
        String dispositionName = contentDispositionHeaderValueMap.get("name");
        DataHandler dataHandler = attachment.getDataHandler();

        OutputStream outputStream = null;

        if ("name".equals(dispositionName)) {
          try {
            outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
          } catch (IOException e) {
            throw new ActivitiIllegalArgumentException("Attachment Name Reading error occured", e);
          }

          if (outputStream != null) {
            String fileName = outputStream.toString();
            attachmentDataHolder.setName(fileName);
          }

        } else if ("type".equals(dispositionName)) {
          try {
            outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
          } catch (IOException e) {
            throw new ActivitiIllegalArgumentException("Attachment Type Reading error occured", e);
          }

          if (outputStream != null) {
            String typeName = outputStream.toString();
            attachmentDataHolder.setType(typeName);
          }

        } else if ("scope".equals(dispositionName)) {
          try {
            outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
          } catch (IOException e) {
            throw new ActivitiIllegalArgumentException(
                "Attachment Description Reading error occured", e);
          }

          if (outputStream != null) {
            String description = outputStream.toString();
            attachmentDataHolder.setScope(description);
          }
        }

        if (contentType != null) {
          if ("file".equals(dispositionName)) {

            InputStream inputStream = null;
            try {
              inputStream = dataHandler.getInputStream();
            } catch (IOException e) {
              throw new ActivitiIllegalArgumentException(
                  "Error Occured During processing empty body.", e);
            }

            if (inputStream != null) {
              attachmentDataHolder.setContentType(contentType);
              byte[] attachmentArray = new byte[0];
              try {
                attachmentArray = IOUtils.toByteArray(inputStream);
              } catch (IOException e) {
                throw new ActivitiIllegalArgumentException("Processing Attachment Body Failed.", e);
              }
              attachmentDataHolder.setAttachmentArray(attachmentArray);
            }
          }
        }
      }
    }

    attachmentDataHolder.printDebug();

    if (attachmentDataHolder.getName() == null) {
      throw new ActivitiIllegalArgumentException("Attachment name is required.");
    }

    if (attachmentDataHolder.getAttachmentArray() == null) {
      throw new ActivitiIllegalArgumentException(
          "Empty attachment body was found in request body after " + "decoding the request" + ".");
    }
    String variableScope = attachmentDataHolder.getScope();
    String variableName = attachmentDataHolder.getName();
    String variableType = attachmentDataHolder.getType();

    if (log.isDebugEnabled()) {
      log.debug(
          "variableScope:"
              + variableScope
              + " variableName:"
              + variableName
              + " variableType:"
              + variableType);
    }

    try {

      // Validate input and set defaults
      if (variableName == null) {
        throw new ActivitiIllegalArgumentException("No variable name was found in request body.");
      }

      if (variableType != null) {
        if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)
            && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
          throw new ActivitiIllegalArgumentException(
              "Only 'binary' and 'serializable' are supported as variable type.");
        }
      } else {
        variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
      }

      RestVariable.RestVariableScope scope = RestVariable.RestVariableScope.LOCAL;
      if (variableScope != null) {
        scope = RestVariable.getScopeFromString(variableScope);
      }

      if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
        // Use raw bytes as variable value
        setVariable(
            execution, variableName, attachmentDataHolder.getAttachmentArray(), scope, isNew);

      } else {
        // Try deserializing the object
        InputStream inputStream =
            new ByteArrayInputStream(attachmentDataHolder.getAttachmentArray());
        ObjectInputStream stream = new ObjectInputStream(inputStream);
        Object value = stream.readObject();
        setVariable(execution, variableName, value, scope, isNew);
        stream.close();
      }

      if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) {
        return new RestResponseFactory()
            .createBinaryRestVariable(
                variableName,
                scope,
                variableType,
                null,
                null,
                execution.getId(),
                uriInfo.getBaseUri().toString());
      } else {
        return new RestResponseFactory()
            .createBinaryRestVariable(
                variableName,
                scope,
                variableType,
                null,
                execution.getId(),
                null,
                uriInfo.getBaseUri().toString());
      }

    } catch (IOException ioe) {
      throw new ActivitiIllegalArgumentException("Could not process multipart content", ioe);
    } catch (ClassNotFoundException ioe) {
      throw new BPMNContentNotSupportedException(
          "The provided body contains a serialized object for which the class is nog found: "
              + ioe.getMessage());
    }
  }
Пример #18
0
 /**
  * Set the Content and the MimeType from the DatHandler. This method defers to the
  * setContent(InputStream) method by passing it the InputStream retrieved from the DataHandler.
  * That means it currently blocks while reading, consuming, and encoding the InputStream. TODO:
  * The better approach would be to simple store the DataHandler in the exts table directly and
  * use a custom TypeAdapter for the BinaryObject to read and consume the DataHandler during the
  * actual Serialization.
  */
 public M data(DataHandler data, Hasher hash, CompressionCodec... comps) throws IOException {
   data(data.getInputStream(), hash, comps);
   if (!a) mimeType(data.getContentType());
   return (M) this;
 }