Example usage for io.netty.channel.socket.nio NioSocketChannel attr

List of usage examples for io.netty.channel.socket.nio NioSocketChannel attr

Introduction

In this page you can find the example usage for io.netty.channel.socket.nio NioSocketChannel attr.

Prototype

<T> Attribute<T> attr(AttributeKey<T> key);

Source Link

Document

Get the Attribute for the given AttributeKey .

Usage

From source file:com.linkedin.r2.transport.http.client.Http2ClientPipelineInitializer.java

License:Apache License

@Override
protected void initChannel(NioSocketChannel channel) throws Exception {
    Http2Connection connection = new DefaultHttp2Connection(false /* not server */);
    channel.attr(HTTP2_CONNECTION_ATTR_KEY).set(connection);
    channel.attr(CALLBACK_ATTR_KEY).set(connection.newKey());
    channel.attr(CHANNEL_POOL_HANDLE_ATTR_KEY).set(connection.newKey());

    Http2InitializerHandler initializerHandler = new Http2InitializerHandler(_maxHeaderSize, _maxChunkSize,
            _maxResponseSize, _streamingTimeout, _scheduler, connection, _sslContext, _sslParameters);
    channel.pipeline().addLast("initializerHandler", initializerHandler);
}

From source file:com.vexsoftware.votifier.NuVotifierBukkit.java

License:Open Source License

@Override
public void onEnable() {
    NuVotifierBukkit.instance = this;

    // Set the plugin version.
    version = getDescription().getVersion();

    if (!getDataFolder().exists()) {
        getDataFolder().mkdir();// www.j  ava  2  s . co  m
    }

    // Handle configuration.
    File config = new File(getDataFolder() + "/config.yml");
    YamlConfiguration cfg;
    File rsaDirectory = new File(getDataFolder() + "/rsa");

    /*
     * Use IP address from server.properties as a default for
     * configurations. Do not use InetAddress.getLocalHost() as it most
     * likely will return the main server address instead of the address
     * assigned to the server.
     */
    String hostAddr = Bukkit.getServer().getIp();
    if (hostAddr == null || hostAddr.length() == 0)
        hostAddr = "0.0.0.0";

    /*
     * Create configuration file if it does not exists; otherwise, load it
     */
    if (!config.exists()) {
        try {
            // First time run - do some initialization.
            getLogger().info("Configuring Votifier for the first time...");

            // Initialize the configuration file.
            config.createNewFile();

            // Load and manually replace variables in the configuration.
            String cfgStr = new String(ByteStreams.toByteArray(getResource("bukkitConfig.yml")),
                    StandardCharsets.UTF_8);
            String token = TokenUtil.newToken();
            cfgStr = cfgStr.replace("%default_token%", token).replace("%ip%", hostAddr);
            Files.write(cfgStr, config, StandardCharsets.UTF_8);

            /*
             * Remind hosted server admins to be sure they have the right
             * port number.
             */
            getLogger().info("------------------------------------------------------------------------------");
            getLogger()
                    .info("Assigning NuVotifier to listen on port 8192. If you are hosting Craftbukkit on a");
            getLogger().info("shared server please check with your hosting provider to verify that this port");
            getLogger().info("is available for your use. Chances are that your hosting provider will assign");
            getLogger().info("a different port, which you need to specify in config.yml");
            getLogger().info("------------------------------------------------------------------------------");
            getLogger().info("Your default NuVotifier token is " + token + ".");
            getLogger().info("You will need to provide this token when you submit your server to a voting");
            getLogger().info("list.");
            getLogger().info("------------------------------------------------------------------------------");
        } catch (Exception ex) {
            getLogger().log(Level.SEVERE, "Error creating configuration file", ex);
            gracefulExit();
            return;
        }
    }

    // Load configuration.
    cfg = YamlConfiguration.loadConfiguration(config);

    /*
     * Create RSA directory and keys if it does not exist; otherwise, read
     * keys.
     */
    try {
        if (!rsaDirectory.exists()) {
            rsaDirectory.mkdir();
            keyPair = RSAKeygen.generate(2048);
            RSAIO.save(rsaDirectory, keyPair);
        } else {
            keyPair = RSAIO.load(rsaDirectory);
        }
    } catch (Exception ex) {
        getLogger().log(Level.SEVERE, "Error reading configuration file or RSA tokens", ex);
        gracefulExit();
        return;
    }

    debug = cfg.getBoolean("debug", false);

    boolean setUpPort = cfg.getBoolean("enableExternal", true); //Always default to running the external port

    if (setUpPort) {
        // Load Votifier tokens.
        ConfigurationSection tokenSection = cfg.getConfigurationSection("tokens");

        if (tokenSection != null) {
            Map<String, Object> websites = tokenSection.getValues(false);
            for (Map.Entry<String, Object> website : websites.entrySet()) {
                tokens.put(website.getKey(), KeyCreator.createKeyFrom(website.getValue().toString()));
                getLogger().info("Loaded token for website: " + website.getKey());
            }
        } else {
            String token = TokenUtil.newToken();
            tokenSection = cfg.createSection("tokens");
            tokenSection.set("default", token);
            tokens.put("default", KeyCreator.createKeyFrom(token));
            try {
                cfg.save(config);
            } catch (IOException e) {
                getLogger().log(Level.SEVERE, "Error generating Votifier token", e);
                gracefulExit();
                return;
            }
            getLogger().info("------------------------------------------------------------------------------");
            getLogger().info("No tokens were found in your configuration, so we've generated one for you.");
            getLogger().info("Your default Votifier token is " + token + ".");
            getLogger().info("You will need to provide this token when you submit your server to a voting");
            getLogger().info("list.");
            getLogger().info("------------------------------------------------------------------------------");
        }

        // Initialize the receiver.
        final String host = cfg.getString("host", hostAddr);
        final int port = cfg.getInt("port", 8192);
        if (debug)
            getLogger().info("DEBUG mode enabled!");

        final boolean disablev1 = cfg.getBoolean("disable-v1-protocol");
        if (disablev1) {
            getLogger().info("------------------------------------------------------------------------------");
            getLogger().info("Votifier protocol v1 parsing has been disabled. Most voting websites do not");
            getLogger().info("currently support the modern Votifier protocol in NuVotifier.");
            getLogger().info("------------------------------------------------------------------------------");
        }

        serverGroup = new NioEventLoopGroup(1);

        new ServerBootstrap().channel(NioServerSocketChannel.class).group(serverGroup)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.attr(VotifierSession.KEY).set(new VotifierSession());
                        channel.attr(VotifierPlugin.KEY).set(NuVotifierBukkit.this);
                        channel.pipeline().addLast("greetingHandler", new VotifierGreetingHandler());
                        channel.pipeline().addLast("protocolDifferentiator",
                                new VotifierProtocolDifferentiator(false, !disablev1));
                        channel.pipeline().addLast("voteHandler",
                                new VoteInboundHandler(NuVotifierBukkit.this));
                    }
                }).bind(host, port).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            serverChannel = future.channel();
                            getLogger()
                                    .info("Votifier enabled on socket " + serverChannel.localAddress() + ".");
                        } else {
                            SocketAddress socketAddress = future.channel().localAddress();
                            if (socketAddress == null) {
                                socketAddress = new InetSocketAddress(host, port);
                            }
                            getLogger().log(Level.SEVERE, "Votifier was not able to bind to " + socketAddress,
                                    future.cause());
                        }
                    }
                });
    } else {
        getLogger().info(
                "You have enableExternal set to false in your config.yml. NuVotifier will NOT listen to votes coming in from an external voting list.");
    }

    ConfigurationSection forwardingConfig = cfg.getConfigurationSection("forwarding");
    if (forwardingConfig != null) {
        String method = forwardingConfig.getString("method", "none").toLowerCase(); //Default to lower case for case-insensitive searches
        if ("none".equals(method)) {
            getLogger().info(
                    "Method none selected for vote forwarding: Votes will not be received from a forwarder.");
        } else if ("pluginmessaging".equals(method)) {
            String channel = forwardingConfig.getString("pluginMessaging.channel", "NuVotifier");
            try {
                forwardingMethod = new BukkitPluginMessagingForwardingSink(this, channel, this);
                getLogger().info("Receiving votes over PluginMessaging channel '" + channel + "'.");
            } catch (RuntimeException e) {
                getLogger().log(Level.SEVERE,
                        "NuVotifier could not set up PluginMessaging for vote forwarding!", e);
            }
        } else {
            getLogger().severe(
                    "No vote forwarding method '" + method + "' known. Defaulting to noop implementation.");
        }
    }
}

From source file:com.vexsoftware.votifier.Votifier.java

License:Open Source License

@Mod.EventHandler
public void onInit(FMLInitializationEvent event) throws IOException {

    // Handle configuration.
    if (!getDataFolder().exists()) {
        getDataFolder().mkdir();//from w  w  w .j a v  a2s . c o  m
    }

    File config = new File(getDataFolder() + "/config.yml");
    ConfigurationLoader loader = YAMLConfigurationLoader.builder().setFile(config).build();
    ConfigurationNode cfg = loader.load();
    File rsaDirectory = new File(getDataFolder() + "/rsa");

    /*
     * Use IP address from server.properties as a default for
     * configurations. Do not use InetAddress.getLocalHost() as it most
     * likely will return the main server address instead of the address
     * assigned to the server.
     */
    String hostAddr = MinecraftServer.getServer().getHostname();
    if (hostAddr == null || hostAddr.length() == 0)
        hostAddr = "0.0.0.0";

    /*
     * Create configuration file if it does not exists; otherwise, load it
     */
    if (!config.exists()) {
        try {
            // First time run - do some initialization.
            LOG.info("Configuring Votifier for the first time...");

            // Initialize the configuration file.
            config.createNewFile();

            cfg.getNode("host").setValue(hostAddr);
            cfg.getNode("port").setValue(8192);
            cfg.getNode("debug").setValue(false);

            /*
             * Remind hosted server admins to be sure they have the right
             * port number.
             */
            LOG.info("------------------------------------------------------------------------------");
            LOG.info("Assigning Votifier to listen on port 8192. If you are hosting Forge on a");
            LOG.info("shared server please check with your hosting provider to verify that this port");
            LOG.info("is available for your use. Chances are that your hosting provider will assign");
            LOG.info("a different port, which you need to specify in config.yml");
            LOG.info("------------------------------------------------------------------------------");

            String token = TokenUtil.newToken();
            ConfigurationNode tokenSection = cfg.getNode("tokens");
            tokenSection.getNode("default").setValue(token);
            LOG.info("Your default Votifier token is " + token + ".");
            LOG.info("You will need to provide this token when you submit your server to a voting");
            LOG.info("list.");
            LOG.info("------------------------------------------------------------------------------");

            loader.save(cfg);
        } catch (Exception ex) {
            LOG.log(Level.FATAL, "Error creating configuration file", ex);
            gracefulExit();
            return;
        }
    } else {
        // Load configuration.
        cfg = loader.load();
    }

    /*
     * Create RSA directory and keys if it does not exist; otherwise, read
     * keys.
     */
    try {
        if (!rsaDirectory.exists()) {
            rsaDirectory.mkdir();
            keyPair = RSAKeygen.generate(2048);
            RSAIO.save(rsaDirectory, keyPair);
        } else {
            keyPair = RSAIO.load(rsaDirectory);
        }
    } catch (Exception ex) {
        LOG.fatal("Error reading configuration file or RSA tokens", ex);
        gracefulExit();
        return;
    }

    // Load Votifier tokens.
    ConfigurationNode tokenSection = cfg.getNode("tokens");

    if (tokenSection != null) {
        Map<Object, ? extends ConfigurationNode> websites = tokenSection.getChildrenMap();
        for (Map.Entry<Object, ? extends ConfigurationNode> website : websites.entrySet()) {
            tokens.put((String) website.getKey(), KeyCreator.createKeyFrom(website.getValue().getString()));
            LOG.info("Loaded token for website: " + website.getKey());
        }
    } else {
        LOG.warn("No websites are listed in your configuration.");
    }

    // Initialize the receiver.
    String host = cfg.getNode("host").getString(hostAddr);
    int port = cfg.getNode("port").getInt(8192);
    debug = cfg.getNode("debug").getBoolean(false);
    if (debug)
        LOG.info("DEBUG mode enabled!");

    serverGroup = new NioEventLoopGroup(1);

    new ServerBootstrap().channel(NioServerSocketChannel.class).group(serverGroup)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel channel) throws Exception {
                    channel.attr(VotifierSession.KEY).set(new VotifierSession());
                    channel.pipeline().addLast("greetingHandler", new VotifierGreetingHandler());
                    channel.pipeline().addLast("protocolDifferentiator", new VotifierProtocolDifferentiator());
                    channel.pipeline().addLast("voteHandler", new VoteInboundHandler());
                }
            }).bind(host, port).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        serverChannel = future.channel();
                        LOG.info("Votifier enabled.");
                    } else {
                        LOG.fatal("Votifier was not able to bind to " + future.channel().localAddress(),
                                future.cause());
                    }
                }
            });
}