class AttachmentProcessingHelper {

    public static void setDataToFileResourceWithValidation(InputStream inputStream, ResourceReference fileReference, String partName)
            throws IllegalParameterValueException, MandatoryParameterNotFoundException {

        final Resource localResource = fileReference != null ? fileReference.getLocalResource() : null;
        final boolean noFile = fileReference == null;
        final boolean isNonLocalResource = !noFile && !fileReference.isLocal();
        final boolean isLocalFile = !noFile && !isNonLocalResource && localResource instanceof FileResource;
        final boolean isFileReference = isLocalFile && ((FileResource)localResource).isReference();
        final boolean hasData = isLocalFile && ((FileResource) localResource).getData() != null;
        final boolean isNewFile = isLocalFile &&  fileReference.getLocalResource().getVersion() == Resource.VERSION_NEW;
        if(
                (noFile || isNonLocalResource || (isFileReference || hasData || !isNewFile))
                        && inputStream == null){
            // no file or file is reference or file data are not empty (already set) or it's not new file (update)
            // and no attachment. Do nothing.
            return;
        }
        if (fileReference == null) {
            throw new MandatoryParameterNotFoundException(partName);
        }
        if (!fileReference.isLocal() || (fileReference.isLocal() && fileReference.getLocalResource() instanceof FileResource
                && ((FileResource) fileReference.getLocalResource()).isReference())) {
            throw new IllegalParameterValueException(partName, partName + "Reference");
        }
        if (!(fileReference.getLocalResource() instanceof FileResource)) {
            throw new IllegalStateException(partName + " resource should be of type FileResource");
        }
        if (inputStream == null) {
            throw new MandatoryParameterNotFoundException("Multipart item " + partName);
        }
        final FileResource file = (FileResource) fileReference.getLocalResource();
        try {
            file.setData(IOUtils.toByteArray(inputStream));
        } catch (IOException e) {
            throw new RuntimeException("Can't read attachment " + partName, e);
        }
    }

}