Example usage for org.apache.wicket.protocol.ws.api IWebSocketConnection sendMessage

List of usage examples for org.apache.wicket.protocol.ws.api IWebSocketConnection sendMessage

Introduction

In this page you can find the example usage for org.apache.wicket.protocol.ws.api IWebSocketConnection sendMessage.

Prototype

void sendMessage(IWebSocketPushMessage message);

Source Link

Document

Broadcasts a push message to the wicket page (and it's components) associated with this connection.

Usage

From source file:com.googlecode.wicket.jquery.ui.plugins.whiteboard.WhiteboardBehavior.java

License:Apache License

protected void respond(final AjaxRequestTarget target) {

    RequestCycle cycle = RequestCycle.get();
    WebRequest webRequest = (WebRequest) cycle.getRequest();

    if (webRequest.getQueryParameters().getParameterValue("editedElement").toString() != null) {
        String editedElement = webRequest.getQueryParameters().getParameterValue("editedElement").toString();

        try {/*www  .  ja va  2s. com*/

            if (snapShot == null && snapShotCreation == null) {
                snapShot = new ArrayList<Element>();
                snapShotCreation = new ArrayList<Boolean>();
            }

            //Mapping JSON String to Objects and Adding to the Element List
            JSONObject jsonEditedElement = new JSONObject(editedElement);
            Element element = getElementObject(jsonEditedElement);

            if (elementMap.containsKey(element.getId()) && !elementMap.isEmpty()) {
                snapShot.add(elementMap.get(element.getId()));
                snapShotCreation.add(false);
            } else {
                snapShot.add(element);
                snapShotCreation.add(true);
            }

            if (!"PointFree".equals(element.getType())) {
                if (undoSnapshots.size() == 20) {
                    undoSnapshots.pollFirst();
                    undoSnapshotCreationList.pollFirst();
                }

                if ("PencilCurve".equals(element.getType())) {
                    ArrayList<Element> lastElementSnapshot = undoSnapshots.getLast();
                    Element lastSnapshotElement = lastElementSnapshot.get(lastElementSnapshot.size() - 1);

                    if ((lastSnapshotElement instanceof PencilCurve)
                            && (lastSnapshotElement.getId() == element.getId())) {
                        ArrayList<Boolean> lastCreationSnapshot = undoSnapshotCreationList.getLast();

                        for (int i = 0; i < snapShot.size(); i++) {
                            lastElementSnapshot.add(snapShot.get(i));
                            lastCreationSnapshot.add(snapShotCreation.get(i));
                        }
                    } else {
                        undoSnapshots.addLast(snapShot);
                        undoSnapshotCreationList.addLast(snapShotCreation);
                    }

                } else {
                    undoSnapshots.addLast(snapShot);
                    undoSnapshotCreationList.addLast(snapShotCreation);
                }

                snapShot = null;
                snapShotCreation = null;
            }

            // Synchronizing newly added element between whiteboards
            if (element != null) {
                elementMap.put(element.getId(), element);

                IWebSocketConnectionRegistry reg = IWebSocketSettings.Holder.get(Application.get())
                        .getConnectionRegistry();
                for (IWebSocketConnection c : reg.getConnections(Application.get())) {
                    try {
                        JSONObject jsonObject = new JSONObject(editedElement);
                        c.sendMessage(getAddElementMessage(jsonObject).toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else if (webRequest.getQueryParameters().getParameterValue("undo").toString() != null) {
        if (!undoSnapshots.isEmpty()) {
            ArrayList<Boolean> undoCreationList = undoSnapshotCreationList.pollLast();
            ArrayList<Element> undoElement = undoSnapshots.pollLast();

            String deleteList = "";
            JSONArray changeList = new JSONArray();

            IWebSocketConnectionRegistry reg = IWebSocketSettings.Holder.get(Application.get())
                    .getConnectionRegistry();

            for (int i = 0; i < undoElement.size(); i++) {
                if (undoCreationList.get(i)) {
                    elementMap.remove(undoElement.get(i).getId());
                    if ("".equals(deleteList)) {
                        deleteList = "" + undoElement.get(i).getId();
                    } else {
                        deleteList += "," + undoElement.get(i).getId();
                    }
                } else {
                    elementMap.put(undoElement.get(i).getId(), undoElement.get(i));
                    changeList.put(undoElement.get(i).getJSON());
                }
            }

            for (IWebSocketConnection c : reg.getConnections(Application.get())) {
                try {
                    c.sendMessage(getUndoMessage(changeList, deleteList).toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    } else if (webRequest.getQueryParameters().getParameterValue("eraseAll").toString() != null) {
        elementMap.clear();
        IWebSocketConnectionRegistry reg = IWebSocketSettings.Holder.get(Application.get())
                .getConnectionRegistry();
        for (IWebSocketConnection c : reg.getConnections(Application.get())) {
            try {
                JSONArray jsonArray = new JSONArray();
                c.sendMessage(getWhiteboardMessage(jsonArray).toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else if (webRequest.getQueryParameters().getParameterValue("save").toString() != null) {
        JSONArray elementArray = new JSONArray();
        for (int elementID : elementMap.keySet()) {
            elementArray.put(elementMap.get(elementID).getJSON());
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        Date date = new Date();
        File whiteboardFile = new File("Whiteboard_" + dateFormat.format(date) + ".json");

        FileWriter writer = null;
        try {
            whiteboardFile.createNewFile();
            System.out.println(whiteboardFile.getAbsolutePath());
            writer = new FileWriter(whiteboardFile);
            writer.write(elementArray.toString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    else if (webRequest.getQueryParameters().getParameterValue("clipArt").toString() != null) {

        IWebSocketConnectionRegistry reg = IWebSocketSettings.Holder.get(Application.get())
                .getConnectionRegistry();
        for (IWebSocketConnection c : reg.getConnections(Application.get())) {
            try {
                JSONArray jsonArray = new JSONArray();
                jsonArray.put("http://icons.iconarchive.com/icons/femfoyou/angry-birds/64/angry-bird-icon.png");
                jsonArray.put(
                        "http://icons.iconarchive.com/icons/femfoyou/angry-birds/64/angry-bird-yellow-icon.png");
                c.sendMessage(getClipArtListMessage(jsonArray).toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.apache.openmeetings.core.util.WebSocketHelper.java

License:Apache License

private static void doSend(IWebSocketConnection c, String msg, String suffix) {
    try {/*from   w  w  w  . j  a va2  s. c  om*/
        c.sendMessage(msg);
    } catch (IOException e) {
        log.error("Error while sending message to {}", suffix, e);
    }
}

From source file:org.apache.openmeetings.web.components.user.ChatPanel.java

License:Apache License

public ChatPanel(String id) {
    super(id);//from   w w w.  j  av  a2  s .  com
    setOutputMarkupId(true);
    setMarkupId(id);

    add(new Behavior() {
        private static final long serialVersionUID = -2205036360048419129L;

        @Override
        public void renderHead(Component component, IHeaderResponse response) {
            ChatDao dao = Application.getBean(ChatDao.class);
            try {
                StringBuilder sb = new StringBuilder();
                for (ChatMessage m : dao.get(0, Integer.MAX_VALUE)) {
                    sb.append("addChatMessage(").append(getMessage(m).toString()).append(");");
                }
                if (sb.length() > 0) {
                    response.render(OnDomReadyHeaderItem.forScript(sb.toString()));
                }
            } catch (JSONException e) {

            }
            super.renderHead(component, response);
        }
    });
    add(new WebMarkupContainer("messages").setMarkupId("messageArea"));
    final Form<Void> f = new Form<Void>("sendForm");
    f.add(new TextArea<String>("message", new PropertyModel<String>(ChatPanel.this, "message"))
            .setOutputMarkupId(true));
    f.add(new Button("send").add(new AjaxFormSubmitBehavior("onclick") {
        private static final long serialVersionUID = -3746739738826501331L;

        protected void onSubmit(AjaxRequestTarget target) {
            ChatDao dao = Application.getBean(ChatDao.class);
            ChatMessage m = new ChatMessage();
            m.setMessage(message);
            m.setSent(new Date());
            m.setFromUser(Application.getBean(UsersDao.class).get(WebSession.getUserId()));
            dao.update(m);
            IWebSocketConnectionRegistry reg = IWebSocketSettings.Holder.get(getApplication())
                    .getConnectionRegistry();
            for (IWebSocketConnection c : reg.getConnections(getApplication())) {
                try {
                    c.sendMessage(getMessage(m).toString());
                } catch (Exception e) {
                    log.error("Error while sending message", e);
                }
            }
            ChatPanel.this.message = "";
            target.add(f);
        };
    }));
    add(f.setOutputMarkupId(true));
}

From source file:org.apache.openmeetings.web.user.ChatPanel.java

License:Apache License

private static void sendRoom(ChatMessage m, String msg) {
    IWebSocketConnectionRegistry reg = WebSocketSettings.Holder.get(Application.get()).getConnectionRegistry();
    for (Client c : getRoomUsers(m.getToRoom().getId())) {
        try {/*  www . j  a v a 2 s  .co  m*/
            if (!m.isNeedModeration() || (m.isNeedModeration() && c.hasRight(Client.Right.moderator))) {
                IWebSocketConnection con = reg.getConnection(Application.get(), c.getSessionId(),
                        new PageIdKey(c.getPageId()));
                if (con != null) {
                    con.sendMessage(msg);
                }
            }
        } catch (Exception e) {
            log.error("Error while sending message to room", e);
        }
    }
}

From source file:org.efaps.esjp.common.pushmsg.MessageSender_Base.java

License:Apache License

/**
 * Send a TextMessage to a user, group or role.
 * @param _parameter Parameter as passed by the eFaps API
 * @return new Return//from  ww w  . j av a  2 s. c o m
 * @throws EFapsException on error
 */
public Return sendTextMessage(final Parameter _parameter) throws EFapsException {
    String reciever = getProperty(_parameter, "Reciever");
    String message = getProperty(_parameter, "Message");
    if (reciever == null) {
        reciever = _parameter.getParameterValue("Reciever");
    }
    if (message == null) {
        message = _parameter.getParameterValue("Message");
    }
    if (reciever != null && !reciever.isEmpty()) {
        final List<Person> persons = new ArrayList<>();
        AbstractUserObject user;
        if (isUUID(reciever)) {
            user = AbstractUserObject.getUserObject(UUID.fromString(reciever));
        } else {
            user = AbstractUserObject.getUserObject(reciever);
        }
        if (user instanceof Role || user instanceof Group) {
            final QueryBuilder queryBldr = new QueryBuilder(
                    user instanceof Role ? CIAdminUser.Person2Role : CIAdminUser.Person2Group);
            queryBldr.addWhereAttrEqValue(CIAdminUser._Abstract2Abstract.UserToAbstractLink, user.getId());
            final MultiPrintQuery multi = queryBldr.getPrint();
            multi.addAttribute(CIAdminUser._Abstract2Abstract.UserFromAbstractLink);
            multi.executeWithoutAccessCheck();
            while (multi.next()) {
                final Long personid = multi
                        .<Long>getAttribute(CIAdminUser._Abstract2Abstract.UserFromAbstractLink);
                persons.add(Person.get(personid));
            }
        }
        for (final Person person : persons) {
            final List<IWebSocketConnection> conns = RegistryManager.getConnections4User(person.getName());
            for (final IWebSocketConnection conn : conns) {
                conn.sendMessage(new PushMsg(message));
            }
        }
    }
    return new Return();
}

From source file:org.efaps.ui.wicket.components.connection.MessagePanel.java

License:Apache License

/**
 * @param _wicketId wicketId of this component
 * @param _pageReference reference to the page
 * @throws EFapsException on error//from  ww  w  . j  av a2  s .c om
 */
public MessagePanel(final String _wicketId, final PageReference _pageReference) throws EFapsException {
    super(_wicketId);
    final Form<Void> msgForm = new Form<>("msgForm");
    add(msgForm);

    final AjaxSubmitLink sendMsgBtn = new AjaxSubmitLink("sendMsgBtn", msgForm) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onAfterSubmit(final AjaxRequestTarget _target, final Form<?> _form) {
            final StringBuilder msg = new StringBuilder();
            _form.visitChildren(TextArea.class, new IVisitor<TextArea<String>, Void>() {
                @Override
                public void component(final TextArea<String> _textArea, final IVisit<Void> _visit) {
                    _textArea.setEscapeModelStrings(false);
                    msg.append(_textArea.getDefaultModelObjectAsString());
                    _visit.stop();
                }
            });

            if (msg.length() > 0) {
                _form.visitChildren(CheckBox.class, new IVisitor<CheckBox, Void>() {

                    @Override
                    public void component(final CheckBox _checkBox, final IVisit<Void> _visit) {
                        final Boolean selected = (Boolean) _checkBox.getDefaultModelObject();
                        if (selected) {
                            final CheckBoxPanel panel = (CheckBoxPanel) _checkBox.getParent();
                            final UIUser user = (UIUser) panel.getDefaultModelObject();
                            final List<IWebSocketConnection> conns = RegistryManager
                                    .getConnections4User(user.getUserName());
                            for (final IWebSocketConnection conn : conns) {
                                conn.sendMessage(new PushMsg(msg.toString()));
                            }
                        }
                    }
                });
            }
        }
    };
    msgForm.add(sendMsgBtn);

    final AjaxSubmitLink broadcastMsgBtn = new AjaxSubmitLink("broadcastMsgBtn", msgForm) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onAfterSubmit(final AjaxRequestTarget _target, final Form<?> _form) {

            final StringBuilder msg = new StringBuilder();
            _form.visitChildren(TextArea.class, new IVisitor<TextArea<String>, Void>() {

                @Override
                public void component(final TextArea<String> _textArea, final IVisit<Void> _visit) {
                    _textArea.setEscapeModelStrings(false);
                    msg.append(_textArea.getDefaultModelObjectAsString());
                    _visit.stop();
                }
            });

            if (msg.length() > 0) {
                final WebSocketSettings webSocketSettings = WebSocketSettings.Holder.get(getApplication());
                final WebSocketPushBroadcaster broadcaster = new WebSocketPushBroadcaster(
                        webSocketSettings.getConnectionRegistry());
                broadcaster.broadcastAll(EFapsApplication.get(), new PushMsg(msg.toString()));
            }
        }
    };
    msgForm.add(broadcastMsgBtn);

    final TextArea<String> msg = new TextArea<>("msg", Model.of(""));
    msgForm.add(msg);

    final MessageTablePanel messageTable = new MessageTablePanel("messageTable", _pageReference,
            new UserProvider());
    msgForm.add(messageTable);
}

From source file:org.efaps.ui.wicket.ConnectionRegistry.java

License:Apache License

/**
 * Send the KeepAlive./*from w  w w . ja v  a2 s. c  o  m*/
 * @param _application Application the KeepAlive will be send for
 */
public void sendKeepAlive(final Application _application) {
    final long reference = new Date().getTime();
    final ConcurrentMap<String, IKey> sessionId2key = _application.getMetaData(ConnectionRegistry.SESSION2KEY);
    final ConcurrentMap<String, Long> keepalive = _application.getMetaData(ConnectionRegistry.KEEPALIVE);
    if (keepalive != null) {
        for (final Entry<String, Long> entry : keepalive.entrySet()) {
            if (reference
                    - entry.getValue() > Configuration.getAttributeAsInteger(ConfigAttribute.WEBSOCKET_KATH)
                            * 1000) {
                final IKey key = sessionId2key.get(entry.getKey());
                if (key != null) {
                    final IWebSocketConnectionRegistry registry = WebSocketSettings.Holder.get(_application)
                            .getConnectionRegistry();
                    final IWebSocketConnection conn = registry.getConnection(_application, entry.getKey(), key);
                    if (conn != null) {
                        try {
                            conn.sendMessage(KeepAliveBehavior.MSG);
                            ConnectionRegistry.LOG.debug("Send KeepAlive for Session: {}", entry.getKey());
                        } catch (final IOException e) {
                            ConnectionRegistry.LOG.error("Catched error", e);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.wicketstuff.whiteboard.WhiteboardBehavior.java

License:Apache License

/**
 * Mapping JSON String to Objects and Adding to the Element List
 * /*w w  w .ja va 2  s  .  c  o  m*/
 * @param editedElement
 * @return
 */
private boolean handleEditedElement(String editedElement) {
    try {
        JSONObject jsonEditedElement = new JSONObject(editedElement);
        Element element = getElementObject(jsonEditedElement);

        boolean isLoaded = false;

        if (!elementMap.isEmpty() && loadedElementMap.get(element.getId()) != null
                && !loadedElementMap.isEmpty()) {
            isLoaded = isEqual(element.getJSON(), loadedElementMap.get(element.getId()).getJSON());
        }

        // If the edited element is not from file loaded content this clause executes
        if (!isLoaded) {

            // Adding the element creation/editing is add to the undo snapshots
            if (snapShot == null && snapShotCreation == null) {
                snapShot = new ArrayList<Element>();
                snapShotCreation = new ArrayList<Boolean>();
            }

            if (elementMap.containsKey(element.getId()) && !elementMap.isEmpty()) {
                snapShot.add(elementMap.get(element.getId()));
                snapShotCreation.add(false);

            } else {
                snapShot.add(element);
                snapShotCreation.add(true);
            }

            if (Type.PointFree != element.getType()) {
                if (undoSnapshots.size() == 20) {
                    undoSnapshots.pollFirst();
                    undoSnapshotCreationList.pollFirst();
                }

                if (Type.PencilCurve == element.getType()) {
                    List<Element> lastElementSnapshot = undoSnapshots.peekLast();
                    if (lastElementSnapshot != null) {
                        Element lastSnapshotElement = lastElementSnapshot.get(lastElementSnapshot.size() - 1);

                        if ((lastSnapshotElement instanceof PencilCurve)
                                && (lastSnapshotElement.getId() == element.getId())) {
                            List<Boolean> lastCreationSnapshot = undoSnapshotCreationList.getLast();

                            for (int i = 0; i < snapShot.size(); i++) {
                                lastElementSnapshot.add(snapShot.get(i));
                                lastCreationSnapshot.add(snapShotCreation.get(i));
                            }
                        } else {
                            undoSnapshots.addLast(snapShot);
                            undoSnapshotCreationList.addLast(snapShotCreation);
                            isElementSnapshotList.addLast(true);
                        }
                    }
                } else if (Type.ClipArt == element.getType()) {
                    List<Element> snapShotTemp = undoSnapshots.pollLast();
                    List<Boolean> snapShotCreationTemp = undoSnapshotCreationList.pollLast();

                    for (int i = 0; i < snapShotTemp.size(); i++) {
                        snapShot.add(snapShotTemp.get(i));
                        snapShotCreation.add(snapShotCreationTemp.get(i));
                    }
                    undoSnapshots.addLast(snapShot);
                    undoSnapshotCreationList.addLast(snapShotCreation);
                    isElementSnapshotList.addLast(true);

                } else {

                    undoSnapshots.addLast(snapShot);
                    undoSnapshotCreationList.addLast(snapShotCreation);
                    isElementSnapshotList.addLast(true);
                }

                snapShot = null;
                snapShotCreation = null;
            }

            // Synchronizing newly added/edited element between whiteboard clients
            if (element != null) {
                elementMap.put(element.getId(), element);

                IWebSocketConnectionRegistry reg = WebSocketSettings.Holder.get(Application.get())
                        .getConnectionRegistry();
                for (IWebSocketConnection c : reg.getConnections(Application.get())) {
                    try {
                        JSONObject jsonObject = new JSONObject(editedElement);
                        c.sendMessage(getAddElementMessage(jsonObject).toString());
                    } catch (Exception e) {
                        log.error("Unexpected error while sending message through the web socket", e);
                    }
                }
            }
        }
        return true;
    } catch (JSONException e) {
        log.error("Unexpected error while editing element", e);
    }
    return false;
}

From source file:org.wicketstuff.whiteboard.WhiteboardBehavior.java

License:Apache License

/**
 * Synchronizing newly added/edited background between whiteboard clients
 * //from   ww  w.java2 s .  c  o m
 * @param backgroundString
 * @return
 */
private boolean handleBackground(String backgroundString) {
    try {
        JSONObject backgroundJSON = new JSONObject(backgroundString);
        Background backgroundObject = new Background(backgroundJSON);
        background = backgroundObject;

        Background previousBackground = new Background("Background", "", 0.0, 0.0, 0.0, 0.0);
        if (whiteboardMap.get(whiteboardObjectId).getBackground() != null) {
            previousBackground = whiteboardMap.get(whiteboardObjectId).getBackground();
        }
        whiteboardMap.get(whiteboardObjectId).setBackground(background);

        undoSnapshotCreationList_Background.addLast(previousBackground == null);
        undoSnapshots_Background.addLast(previousBackground);
        isElementSnapshotList.addLast(false);

        IWebSocketConnectionRegistry reg = WebSocketSettings.Holder.get(Application.get())
                .getConnectionRegistry();
        for (IWebSocketConnection c : reg.getConnections(Application.get())) {
            try {
                JSONObject jsonObject = new JSONObject(backgroundString);
                c.sendMessage(getAddBackgroundMessage(jsonObject).toString());
            } catch (Exception e) {
                log.error("Unexpected error while sending message through the web socket", e);
            }
        }

        return true;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:org.wicketstuff.whiteboard.WhiteboardBehavior.java

License:Apache License

/**
 * Undo one step and synchronizing undo between whiteboard clients
 * //w  ww .  ja  v  a2  s  .c  om
 * @return
 */
private boolean handleUndo() {
    if (!isElementSnapshotList.isEmpty()) {

        if (isElementSnapshotList.pollLast()) {
            List<Boolean> undoCreationList = undoSnapshotCreationList.pollLast();
            List<Element> undoElement = undoSnapshots.pollLast();

            String deleteList = "";
            JSONArray changeList = new JSONArray();

            IWebSocketConnectionRegistry reg = WebSocketSettings.Holder.get(Application.get())
                    .getConnectionRegistry();

            for (int i = 0; i < undoElement.size(); i++) {
                if (undoCreationList.get(i)) {
                    elementMap.remove(undoElement.get(i).getId());
                    if (loadedElementMap.containsKey(undoElement.get(i).getId())) {
                        loadedContent = "";
                        whiteboardMap.get(whiteboardObjectId).setLoadedContent("");
                        loadedElementMap.remove(undoElement.get(i).getId());
                    }
                    if ("".equals(deleteList)) {
                        deleteList = "" + undoElement.get(i).getId();
                    } else {
                        deleteList += "," + undoElement.get(i).getId();
                    }
                } else {
                    elementMap.put(undoElement.get(i).getId(), undoElement.get(i));
                    try {
                        changeList.put(undoElement.get(i).getJSON());
                    } catch (JSONException e) {
                        log.error("Unexpected error while getting JSON", e);
                    }
                }
            }

            for (IWebSocketConnection c : reg.getConnections(Application.get())) {
                try {
                    c.sendMessage(getUndoMessage(changeList, deleteList).toString());
                } catch (Exception e) {
                    log.error("Unexpected error while sending message through the web socket", e);
                }
            }
        } else {
            Background previousBackground = undoSnapshots_Background.pollLast();
            background = previousBackground;
            whiteboardMap.get(whiteboardObjectId).setBackground(previousBackground);

            IWebSocketConnectionRegistry reg = WebSocketSettings.Holder.get(Application.get())
                    .getConnectionRegistry();
            for (IWebSocketConnection c : reg.getConnections(Application.get())) {
                try {
                    if (previousBackground != null) {
                        c.sendMessage(getAddBackgroundMessage(previousBackground.getJSON()).toString());
                    } else {
                        c.sendMessage(getAddBackgroundMessage(new JSONObject()).toString());
                    }
                } catch (Exception e) {
                    log.error("Unexpected error while sending message through the web socket", e);
                }
            }

        }
        return true;
    }
    return false;
}