Save message draft

@param peer  destination peer
@param draft message draft
541299
@ObjectiveCName("saveDraftWithPeer:withDraft:")
    public void saveDraft(Peer peer, String draft) {
        modules.getMessagesModule().saveDraft(peer, draft);
    }
604515
@ObjectiveCName("sendMessageWithMentionsDetect:withText:withMarkdownText:")
    public void sendMessageWithMentionsDetect(@NotNull Peer peer, @NotNull String text, @NotNull String markdownText) {
        sendMessage(peer, text, markdownText, null, true);
    }
676831
public void saveGroupcontainer(
        final CmsGroupContainer groupContainer,
        final CmsGroupContainerElementPanel groupContainerElement) {

        if (getGroupcontainer() != null) {
            CmsRpcAction<CmsGroupContainerSaveResult> action = new CmsRpcAction<CmsGroupContainerSaveResult>() {

                /**
                 * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()
                 */
                @Override
                public void execute() {

                    start(0, true);
                    getContainerpageService().saveGroupContainer(
                        getData().getRpcContext(),
                        getData().getDetailId(),
                        getRequestParams(),
                        groupContainer,
                        getPageState(),
                        getLocale(),
                        this);
                }

                /**
                 * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)
                 */
                @Override
                protected void onResponse(CmsGroupContainerSaveResult saveResult) {

                    stop(false);
                    Map<String, CmsContainerElementData> elementData = saveResult.getElementData();
                    m_elements.putAll(elementData);
                    try {
                        replaceContainerElement(groupContainerElement, elementData.get(groupContainerElement.getId()));
                    } catch (Exception e) {
                        CmsDebugLog.getInstance().printLine("Error replacing group container element");
                    }
                    addToRecentList(groupContainerElement.getId(), null);
                    CmsNotification.get().send(
                        Type.NORMAL,
                        Messages.get().key(Messages.GUI_NOTIFICATION_GROUP_CONTAINER_SAVED_0));
                    List<CmsRemovedElementStatus> removedElements = saveResult.getRemovedElements();
                    for (CmsRemovedElementStatus removedElement : removedElements) {
                        askWhetherRemovedElementShouldBeDeleted(removedElement);
                    }

                }
            };
            action.execute();

        }
    }
1059105
@ObjectiveCName("sendLocationWithPeer:withLongitude:withLatitude:withStreet:withPlace:")
    public void sendLocation(@NotNull Peer peer,
                             @NotNull Double longitude, @NotNull Double latitude,
                             @Nullable String street, @Nullable String place) {
        modules.getMessagesModule().sendLocation(peer, longitude, latitude, street, place);
    }
675833
@ObjectiveCName("sendDocumentWithPeer:withName:withMime:withThumb:withDescriptor:")
    public void sendDocument(Peer peer, String fileName, String mimeType, FastThumb fastThumb,
                             String descriptor) {
        modules.getMessagesModule().sendDocument(peer, fileName, mimeType, fastThumb, descriptor);
    }
788416
def publish(self):
        
        if self.is_draft:
            # If the object has previously been linked then patch the
            # placeholder data and remove the previously linked object.
            # Otherwise set the published date.
            if self.publishing_linked:
                self.patch_placeholders()
                # Unlink draft and published copies then delete published.
                # NOTE: This indirect dance is necessary to avoid
                # triggering unwanted MPTT tree structure updates via
                # `save`.
                type(self.publishing_linked).objects \
                    .filter(pk=self.publishing_linked.pk) \
                    .delete()  # Instead of self.publishing_linked.delete()
            else:
                self.publishing_published_at = timezone.now()

            # Create a new object copying all fields.
            publish_obj = deepcopy(self)

            # If any fields are defined not to copy set them to None.
            for fld in self.publishing_publish_empty_fields + (
                'urlnode_ptr_id', 'publishing_linked_id'
            ):
                setattr(publish_obj, fld, None)

            # Set the state of publication to published on the object.
            publish_obj.publishing_is_draft = False

            # Update Fluent's publishing status field mechanism to correspond
            # to our own notion of publication, to help use work together more
            # easily with Fluent Pages.
            if isinstance(self, UrlNode):
                self.status = UrlNode.DRAFT
                publish_obj.status = UrlNode.PUBLISHED

            # Set the date the object should be published at.
            publish_obj.publishing_published_at = self.publishing_published_at

            # Perform per-model preparation before saving published copy
            publish_obj.publishing_prepare_published_copy(self)

            # Save the new published object as a separate instance to self.
            publish_obj.save()
            # Sanity-check that we successfully saved the published copy
            if not publish_obj.pk:  # pragma: no cover
                raise PublishingException("Failed to save published copy")

            # As it is a new object we need to clone each of the
            # translatable fields, placeholders and required relations.
            self.clone_parler_translations(publish_obj)
            self.clone_fluent_placeholders_and_content_items(publish_obj)
            self.clone_fluent_contentitems_m2m_relationships(publish_obj)

            # Extra relationship-cloning smarts
            publish_obj.publishing_clone_relations(self)

            # Link the published object to the draft object.
            self.publishing_linked = publish_obj

            # Flag draft instance when it is being updated as part of a
            # publish action, for use in `publishing_set_update_time`
            self._skip_update_publishing_modified_at = True

            # Signal the pre-save hook for publication, save then signal
            # the post publish hook.
            publishing_signals.publishing_publish_pre_save_draft.send(
                sender=type(self), instance=self)

            # Save the draft and its new relationship with the published copy
            publishing_signals.publishing_publish_save_draft.send(
                sender=type(self), instance=self)

            publishing_signals.publishing_post_publish.send(
                sender=type(self), instance=self)
            return publish_obj
867035
public void addPreMessageReceivedEventListener(Executor executor, PreMessageReceivedEventListener listener) {
        peersPreMessageReceivedEventListeners.add(new ListenerRegistration<>(checkNotNull(listener), executor));
        for (Peer peer : getConnectedPeers())
            peer.addPreMessageReceivedEventListener(executor, listener);
        for (Peer peer : getPendingPeers())
            peer.addPreMessageReceivedEventListener(executor, listener);
    }
417944
@Override
    public void write(RtpPacket packet, RTPFormat format) {
        // checking format
        if (format == null) {
            if (logger.isTraceEnabled()) {
                logger.trace("No format specified. Packet dropped!");
            }
            return;
        }

        boolean locked = false;
        try {
            locked = this.lock.tryLock() || this.lock.tryLock(5, TimeUnit.MILLISECONDS);
            if (locked) {
                safeWrite(packet, format);
            }
        } catch (InterruptedException e) {
            if (logger.isTraceEnabled()) {
                logger.trace("Could not aquire write lock for jitter buffer. Dropped packet.");
            }
        } finally {
            if (locked) {
                this.lock.unlock();
            }
        }
    }
465674
public void addPeer(TrackedPeer peer) {
    this.peers.put(new PeerUID(peer.getAddress(), this.getHexInfoHash()), peer);
  }
483049
public void forwardBroadcast (Name from, byte levelOrMode, String bundle, String msg)
    {
        for (PeerNode peer : _peers.values()) {
            if (peer.nodeobj != null) {
                ((CrowdNodeObject)peer.nodeobj).crowdPeerService.deliverBroadcast(
                    from, levelOrMode, bundle, msg);
            }
        }
    }
279915
public void put(DelayableImmutableMessage delayableImmutableMessage) {
        if (messagePersister.persist(messageQueueId, delayableImmutableMessage)) {
            logger.trace("Message {} was persisted for messageQueueId {}",
                         delayableImmutableMessage.getMessage(),
                         messageQueueId);
        } else {
            logger.trace("Message {} was not persisted for messageQueueId {}",
                         delayableImmutableMessage.getMessage(),
                         messageQueueId);
        }
        delayableImmutableMessages.put(delayableImmutableMessage);
    }
473720
private void saveSortedPomFile(final String sortedXml) {
        fileUtil.savePomFile(sortedXml);
        log.info("Saved sorted pom file to " + pomFile.getAbsolutePath());
    }
533947
def publish(ctx, test=False, force=False, draft=False):
    

    previous_version = get_previous_version(ctx)
    current_version = parver.Version.parse(metadata["version"])

    if current_version <= previous_version and not force:
        error_message = (
            f"current version ({current_version!s}) is <= to previous version "
            f"({previous_version!s}), use 'package.version' to update current version"
        )
        report.error(ctx, "publish", error_message)
        raise ValueError(error_message)

    report.info(ctx, "publish", f"publishing project {ctx.metadata['name']!r}")
    report.warning(
        ctx,
        "publish",
        f"drafting publish for project {ctx.metadata['name']!r} (has no effect)",
    )

    commit_message = f"Release {current_version!s}"
    report.info(ctx, "publish", f"git commiting release {commit_message!r}")
    git_commit_command = f"git commit -asm {commit_message!r}"
    if not draft:
        ctx.run(git_commit_command)

    tag_content = get_tag_content(ctx).replace('"', '\\"')
    git_tag_command = (
        f'git tag -a "v{current_version!s}" -m '
        f'"Version {current_version!s}\n\n{tag_content}"'
    )
    report.info(
        ctx, "publish", f"git tagging commit as release for version {current_version!s}"
    )
    if not draft:
        ctx.run(git_tag_command)

    artifact_paths = [f"{_.as_posix()!r}" for _ in get_artifact_paths(ctx)]
    for artifact_path in artifact_paths:
        report.debug(ctx, "publish", f"publishing artifact {artifact_path}")
    publish_command = f"twine upload {' '.join(artifact_paths)}"
    if test:
        publish_command += " --repository 'https://test.pypi.org/legacy/'"

    # get user to confirm publish
    try:
        input(
            report._get_text(
                ctx,
                "success",
                "publish",
                "about to publish, [Enter] to continue, [Ctrl-C] to abort: ",
            )
        )

        while True:
            (username, password) = get_username_password(
                ctx, "PyPi Username: ", "PyPi Password: "
            )
            # TODO: check if username and password are valid before tyring to post
            report.info(ctx, "publish", f"publishing project {ctx.metadata['name']!s}")
            if not draft:
                publish_command += f" -u {username!r} -p {password!r}"
                publish_result = ctx.run(publish_command, warn=True)
                if publish_result.exited:
                    report.error(
                        ctx,
                        "publish",
                        f"failed to publish {ctx.metadata['name']!s} (retrying)",
                    )
                    continue
            break

        git_push_command = "git push --tags"
        report.info(ctx, "publish", f"pushing git tags")
        if not draft:
            ctx.run(git_push_command)
    except KeyboardInterrupt:
        print()
        report.error(ctx, "publish", "aborting publish!")
        git_remove_tag_command = f"git tag -d {current_version!s}"
        report.warn(ctx, "publish", "removing git tags")
        if not draft:
            ctx.run(git_remove_tag_command)
        git_reset_command = f"git reset --soft HEAD^"
        report.warn(ctx, "publish", "softly reseting commit")
        if not draft:
            ctx.run(git_reset_command)
1351475
private function prepareDraftForCommit(AbstractClassContent $content, Revision $draft, array $data)
    {
        if ($content instanceof ContentSet) {
            if (!isset($data['elements']) || false === $data['elements']) {
                $draft->clear();
                foreach ($content->getData() as $element) {
                    $draft->push($element);
                }
            }
        } elseif (AbstractClassContent::STATE_NORMAL === $content->getState()) {
            foreach ($content->getData() as $key => $element) {
                if (!isset($data['elements']) || !in_array($key, $data['elements'])) {
                    $draft->$key = $content->$key;
                }
            }
        }

        if (isset($data['parameters'])) {
            foreach ($content->getAllParams() as $key => $params) {
                if (!in_array($key, $data['parameters'])) {
                    $draft->setParam($key, $content->getParamValue($key));
                }
            }
        }

        if (isset($data['message'])) {
            $draft->setComment($data['message']);
        }

        return $this;
    }
284097
def insert_draft_child(self, child_pid):
        """"""
        if child_pid.status != PIDStatus.RESERVED:
            raise PIDRelationConsistencyError(
                "Draft child should have status 'RESERVED'")

        if not self.draft_child:
            with db.session.begin_nested():
                super(PIDNodeVersioning, self).insert_child(child_pid,
                                                            index=-1)
        else:
            raise PIDRelationConsistencyError(
                "Draft child already exists for this relation: {0}".format(
                    self.draft_child))
963451
public void writeUncommitted(SIMPMessage m)
                    throws SIResourceException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "writeUncommitted", new Object[] { m });

        TickRange tr = null;

        JsMessage jsMsg = m.getMessage();
        long stamp = jsMsg.getGuaranteedValueValueTick();

        long starts = jsMsg.getGuaranteedValueStartTick();
        long ends = jsMsg.getGuaranteedValueEndTick();
        long completedPrefix;

        tr = TickRange.newUncommittedTick(stamp);
        tr.startstamp = starts;
        tr.endstamp = ends;

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        {
            SibTr.debug(tc, "writeUncommitted at: " + stamp + " with Silence from: " + starts + " to " + ends + " on Stream " + streamID);
        }

        synchronized (this)
        {
            // write into stream
            oststream.writeCombinedRange(tr);

            completedPrefix = oststream.getCompletedPrefix();

            sendSilence(starts, completedPrefix);

            // SIB0105
            // If this is the first uncommitted messages to be added to the stream, start off the 
            // blocked message health state timer. This will check back in the future to see if the
            // message successfully sent.
            if (blockedStreamAlarm == null)
            {
                blockedStreamAlarm = new BlockedStreamAlarm(this, getCompletedPrefix());
                am.create(GDConfig.BLOCKED_STREAM_HEALTH_CHECK_INTERVAL, blockedStreamAlarm);
            }

        } // end synchronized

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "writeUncommitted");

    }
1092154
def sync_mptt_tree_fields_from_draft_to_published_post_save(
        sender, instance, **kwargs):
    
    mptt_opts = getattr(instance, '_mptt_meta', None)
    published_copy = getattr(instance, 'publishing_linked', None)
    if mptt_opts and published_copy:
        sync_mptt_tree_fields_from_draft_to_published(instance)