Search in sources :

Example 1 with WebsocketNotConnectedException

use of org.java_websocket.exceptions.WebsocketNotConnectedException in project ably-java by ably.

the class WebSocketTransport method send.

@Override
public void send(ProtocolMessage msg) throws AblyException {
    Log.d(TAG, "send(); action = " + msg.action);
    try {
        if (channelBinaryMode) {
            byte[] encodedMsg = ProtocolSerializer.writeMsgpack(msg);
            if (Log.level <= Log.VERBOSE) {
                ProtocolMessage decodedMsg = ProtocolSerializer.readMsgpack(encodedMsg);
                Log.v(TAG, "send(): " + decodedMsg.action + ": " + new String(ProtocolSerializer.writeJSON(decodedMsg)));
            }
            wsConnection.send(encodedMsg);
        } else {
            if (Log.level <= Log.VERBOSE)
                Log.v(TAG, "send(): " + new String(ProtocolSerializer.writeJSON(msg)));
            wsConnection.send(ProtocolSerializer.writeJSON(msg));
        }
    } catch (WebsocketNotConnectedException e) {
        if (connectListener != null) {
            connectListener.onTransportUnavailable(this, AblyException.fromThrowable(e).errorInfo);
        } else
            throw AblyException.fromThrowable(e);
    } catch (Exception e) {
        throw AblyException.fromThrowable(e);
    }
}
Also used : WebsocketNotConnectedException(org.java_websocket.exceptions.WebsocketNotConnectedException) ProtocolMessage(io.ably.lib.types.ProtocolMessage) AblyException(io.ably.lib.types.AblyException) WebsocketNotConnectedException(org.java_websocket.exceptions.WebsocketNotConnectedException)

Example 2 with WebsocketNotConnectedException

use of org.java_websocket.exceptions.WebsocketNotConnectedException in project GDBoard by Alphatism.

the class Main method main.

public static void main(String[] args) {
    iconImages.add(newIcon16);
    iconImages.add(newIcon32);
    JFrame starting = new JFrame("loquibot");
    starting.setSize(200, 200);
    starting.setResizable(false);
    starting.setLocationRelativeTo(null);
    starting.setUndecorated(true);
    starting.setBackground(new Color(0, 0, 0, 0));
    starting.add(new JLabel(Assets.loquibotLarge));
    starting.getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    starting.setIconImages(iconImages);
    starting.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    starting.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            Main.close();
        }
    });
    starting.setVisible(true);
    System.out.println("> Start");
    // Saves defaults of UI Elements before switching to Nimbus
    // Sets to Nimbus, then sets defaults back
    setUI();
    Settings.loadSettings();
    System.out.println("> Settings Loaded");
    // Places config files in JRE folder in the GDBoard AppData as I forgot to
    // include them in the bundled JRE
    createConfFiles();
    System.out.println("> Config Files Created");
    if (Settings.getSettings("onboarding").exists()) {
        try {
            TwitchAccount.setInfo();
            new Thread(ChannelPointSettings::refresh).start();
        } catch (Exception e) {
            e.printStackTrace();
            APIs.setOauth();
            TwitchAccount.setInfo();
            new Thread(ChannelPointSettings::refresh).start();
        }
    }
    System.out.println("> Twitch Loaded");
    try {
        Language.startFileChangeListener();
        Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
        logger.setLevel(Level.OFF);
        logger.setUseParentHandlers(false);
        new Thread(Assets::loadAssets).start();
        Defaults.initializeThemeInfo();
        new Thread(Defaults::startMainThread).start();
        System.out.println("> Main Threads Started");
        if (!Settings.getSettings("onboarding").exists()) {
            Onboarding.createPanel();
            Onboarding.refreshUI();
            Onboarding.frame.setVisible(true);
            Onboarding.isLoading = true;
            while (Onboarding.isLoading) {
                Thread.sleep(100);
            }
            TwitchAccount.setInfo();
            new Thread(ChannelPointSettings::refresh).start();
        }
        LoadGD.load();
        System.out.println("> LoadGD Loaded");
        new Thread(Variables::loadVars).start();
        System.out.println("> Variables Loaded");
        new Thread(() -> {
            while (keepConnecting) {
                try {
                    if (chatReader != null) {
                        try {
                            chatReader.disconnect();
                        } catch (WebsocketNotConnectedException ignored) {
                        }
                    }
                    chatReader = new ChatListener(TwitchAccount.login);
                    chatReader.connect(Settings.getSettings("oauth").asString(), TwitchAccount.login);
                    while (!chatReader.isClosed()) {
                        Thread.sleep(100);
                    }
                } catch (Exception ignored) {
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(() -> {
            while (keepConnecting) {
                serverBot = new ServerBot();
                serverBot.connect();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                }
            }
        }).start();
        if (!Settings.getSettings("monitor").asString().equalsIgnoreCase("")) {
            Settings.writeSettings("monitor", "0");
        }
        Window.initFrame();
        CommandEditor.createPanel();
        RequestsTab.createPanel();
        // ActionsTab.createPanel();
        ChatbotTab.createPanel();
        SettingsTab.createPanel();
        OfficerWindow.create();
        Window.loadTopComponent();
        LoadCommands.loadCommands();
        System.out.println("> Panels Created");
        // Runs keyboard hook for global keybinds
        new Thread(Main::runKeyboardHook).start();
        // Reads channel point redemptions for channel point triggers
        new Thread(() -> {
            try {
                while (true) {
                    channelPointListener = new ChannelPointListener(new URI("wss://pubsub-edge.twitch.tv"));
                    channelPointListener.connectBlocking();
                    while (channelPointListener.isOpen()) {
                        Thread.sleep(10);
                    }
                    Thread.sleep(2000);
                }
            } catch (URISyntaxException | InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        // Refresh GD Username in Account Settings
        // AccountSettings.refreshGD(LoadGD.username);
        Window.loadSettings();
        Themes.refreshUI();
        starting.setVisible(false);
        Window.setVisible(true);
        System.out.println("> Window Visible");
        Window.setOnTop(Settings.getSettings("onTop").asBoolean());
        OutputSettings.setOutputStringFile(RequestsUtils.parseInfoString(Settings.getSettings("outputString").asString(), 0));
        Path initialJS = Paths.get(Defaults.saveDirectory + "\\GDBoard\\initial.js");
        if (Files.exists(initialJS)) {
            new Thread(() -> {
                try {
                    if (!Files.readString(initialJS, StandardCharsets.UTF_8).equalsIgnoreCase("")) {
                        Command.run(TwitchAccount.display_name, true, true, new String[] { "dummy" }, Files.readString(initialJS, StandardCharsets.UTF_8), 0, null, -1);
                    }
                } catch (Exception ignored) {
                }
            }).start();
        } else {
            Files.createFile(initialJS);
        }
        if (!Settings.getSettings("basicMode").asBoolean()) {
            Path file = Paths.get(Defaults.saveDirectory + "\\GDBoard\\saved.txt");
            if (Files.exists(file)) {
                Scanner sc = null;
                try {
                    sc = new Scanner(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                assert sc != null;
                while (sc.hasNextLine()) {
                    String[] level = sc.nextLine().split(",");
                    try {
                        // name
                        RequestsUtils.forceAdd(// name
                        level[0], // creator
                        level[1], // ID
                        Long.parseLong(level[2]), // difficulty
                        level[3], // demonDifficulty
                        level[4], // isDemon
                        Boolean.parseBoolean(level[5]), // isAuto
                        Boolean.parseBoolean(level[6]), // isEpic
                        Boolean.parseBoolean(level[7]), // featuredScore
                        Integer.parseInt(level[8]), // stars
                        Integer.parseInt(level[9]), // requestedStars
                        Integer.parseInt(level[10]), // requester
                        level[11], // gameVersion
                        Integer.parseInt(level[12]), // coinCount
                        Integer.parseInt(level[13]), // description
                        new String(Base64.getDecoder().decode(level[14].getBytes())), // likes
                        Integer.parseInt(level[15]), // downloads
                        Integer.parseInt(level[16]), // length
                        level[17], // levelVersion
                        Integer.parseInt(level[18]), // songID
                        Long.parseLong(level[19]), // songTitle
                        new String(Base64.getDecoder().decode(level[20].getBytes())), // songArtist
                        level[21], // objectCount
                        Integer.parseInt(level[22]), // originalLevelID
                        Long.parseLong(level[23]), // containsVulgar
                        Boolean.parseBoolean(level[24]), // containsImage
                        Boolean.parseBoolean(level[25]), // coinsVerified
                        Boolean.parseBoolean(level[26]));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                sc.close();
            }
        } else {
            RequestsTab.setBasicMode(Settings.getSettings("basicMode").asBoolean(), false);
            Path file = Paths.get(Defaults.saveDirectory + "\\GDBoard\\savedBasic.txt");
            if (Files.exists(file)) {
                Scanner sc = null;
                try {
                    sc = new Scanner(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                assert sc != null;
                while (sc.hasNextLine()) {
                    String[] level = sc.nextLine().split(",");
                    try {
                        RequestsUtils.forceAddBasic(// ID
                        Long.parseLong(level[0]), // requester
                        level[1]);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                sc.close();
            }
        }
        allowRequests = true;
        RequestFunctions.saveFunction();
        RequestsTab.getLevelsPanel().setSelect(0);
        new Thread(APIs::checkViewers).start();
        if (!Settings.getSettings("basicMode").asBoolean()) {
            try {
                if (RequestsTab.getQueueSize() != 0) {
                    new Thread(() -> RequestsTab.loadComments(0, false)).start();
                }
            } catch (Exception ignored) {
            }
        }
        sendMessages = true;
        // if (Settings.getSettings("isHigher").asBoolean()) sendMessage(Utilities.format("🔷 | $STARTUP_MESSAGE_MOD_VIP$"));
        /*Reflections reflections =
                    new Reflections(new ConfigurationBuilder()
                            .filterInputsBy(new FilterBuilder().includePackage("com.alphalaneous"))
                            .setUrls(ClasspathHelper.forPackage("com.alphalaneous"))
                            .setScanners(new SubTypesScanner(false)));

            Set<String> typeList = reflections.getAllTypes();

            for(String str : typeList){
                if(str.equals("com.alphalaneous.Board")){
                    Class.forName(str).getMethod("bwomp").invoke(null);
                }
                System.out.println(Class.forName(str).getName());
            }*/
        APIs.setAllViewers();
        if (!Settings.getSettings("isHigher").exists()) {
            if (APIs.allMods.contains("gdboard") || APIs.allVIPs.contains("gdboard"))
                Settings.writeSettings("isHigher", "true");
            else
                Settings.writeSettings("isHigher", "false");
        }
        Board.testSearchPing();
        programLoaded = true;
    } catch (Exception e) {
        e.printStackTrace();
        DialogBox.showDialogBox("Error!", "<html>" + e + ": " + e.getStackTrace()[0], "Please report to Alphalaneous#9687 on Discord.", new String[] { "Close" });
        close(true, false);
    }
}
Also used : Path(java.nio.file.Path) FileNotFoundException(java.io.FileNotFoundException) WindowAdapter(java.awt.event.WindowAdapter) WebsocketNotConnectedException(org.java_websocket.exceptions.WebsocketNotConnectedException) Logger(java.util.logging.Logger) URI(java.net.URI) NativeHookException(org.jnativehook.NativeHookException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) WebsocketNotConnectedException(org.java_websocket.exceptions.WebsocketNotConnectedException) WindowEvent(java.awt.event.WindowEvent)

Example 3 with WebsocketNotConnectedException

use of org.java_websocket.exceptions.WebsocketNotConnectedException in project Java-WebSocket by TooTallNate.

the class ServerStressTest method send.

public void send() {
    notyetconnected = 0;
    String payload = text.getText();
    long time1 = System.currentTimeMillis();
    synchronized (websockets) {
        for (WebSocketClient cl : websockets) {
            try {
                cl.send(payload);
            } catch (WebsocketNotConnectedException e) {
                notyetconnected++;
            }
        }
    }
    System.out.println(websockets.size() + "/" + notyetconnected + " clients sent \"" + payload + "\"" + (System.currentTimeMillis() - time1));
}
Also used : WebsocketNotConnectedException(org.java_websocket.exceptions.WebsocketNotConnectedException) WebSocketClient(org.java_websocket.client.WebSocketClient)

Example 4 with WebsocketNotConnectedException

use of org.java_websocket.exceptions.WebsocketNotConnectedException in project Java-WebSocket by TooTallNate.

the class WebSocketImpl method send.

private void send(Collection<Framedata> frames) {
    if (!isOpen()) {
        throw new WebsocketNotConnectedException();
    }
    if (frames == null) {
        throw new IllegalArgumentException();
    }
    ArrayList<ByteBuffer> outgoingFrames = new ArrayList<>();
    for (Framedata f : frames) {
        log.trace("send frame: {}", f);
        outgoingFrames.add(draft.createBinaryFrame(f));
    }
    write(outgoingFrames);
}
Also used : Framedata(org.java_websocket.framing.Framedata) ArrayList(java.util.ArrayList) WebsocketNotConnectedException(org.java_websocket.exceptions.WebsocketNotConnectedException) ByteBuffer(java.nio.ByteBuffer)

Example 5 with WebsocketNotConnectedException

use of org.java_websocket.exceptions.WebsocketNotConnectedException in project Java-WebSocket by TooTallNate.

the class WebSocketServer method doBroadcast.

/**
 * Private method to cache all the frames to improve memory footprint and conversion time
 *
 * @param data    the data to broadcast
 * @param clients the clients to send the message to
 */
private void doBroadcast(Object data, Collection<WebSocket> clients) {
    String strData = null;
    if (data instanceof String) {
        strData = (String) data;
    }
    ByteBuffer byteData = null;
    if (data instanceof ByteBuffer) {
        byteData = (ByteBuffer) data;
    }
    if (strData == null && byteData == null) {
        return;
    }
    Map<Draft, List<Framedata>> draftFrames = new HashMap<>();
    List<WebSocket> clientCopy;
    synchronized (clients) {
        clientCopy = new ArrayList<>(clients);
    }
    for (WebSocket client : clientCopy) {
        if (client != null) {
            Draft draft = client.getDraft();
            fillFrames(draft, draftFrames, strData, byteData);
            try {
                client.sendFrame(draftFrames.get(draft));
            } catch (WebsocketNotConnectedException e) {
            // Ignore this exception in this case
            }
        }
    }
}
Also used : Draft(org.java_websocket.drafts.Draft) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) WebsocketNotConnectedException(org.java_websocket.exceptions.WebsocketNotConnectedException) ByteBuffer(java.nio.ByteBuffer) WebSocket(org.java_websocket.WebSocket) AbstractWebSocket(org.java_websocket.AbstractWebSocket)

Aggregations

WebsocketNotConnectedException (org.java_websocket.exceptions.WebsocketNotConnectedException)7 IOException (java.io.IOException)2 ByteBuffer (java.nio.ByteBuffer)2 ArrayList (java.util.ArrayList)2 AblyException (io.ably.lib.types.AblyException)1 ProtocolMessage (io.ably.lib.types.ProtocolMessage)1 SEPAProtocolException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException)1 Notification (it.unibo.arces.wot.sepa.commons.response.Notification)1 WindowAdapter (java.awt.event.WindowAdapter)1 WindowEvent (java.awt.event.WindowEvent)1 FileNotFoundException (java.io.FileNotFoundException)1 ConnectException (java.net.ConnectException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 Path (java.nio.file.Path)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 Logger (java.util.logging.Logger)1 ConditionTimeoutException (org.awaitility.core.ConditionTimeoutException)1