Example usage for io.netty.util ResourceLeakDetector setLevel

List of usage examples for io.netty.util ResourceLeakDetector setLevel

Introduction

In this page you can find the example usage for io.netty.util ResourceLeakDetector setLevel.

Prototype

public static void setLevel(Level level) 

Source Link

Document

Sets the resource leak detection level.

Usage

From source file:jgnash.engine.FileTransferTest.java

License:Open Source License

@Test
public void encryptedNetworkedTest() throws Exception {

    final char[] password = new char[] { 'p', 'a', 's', 's', 'w', 'o', 'r', 'd' };
    final int port = 5300;

    //System.setProperty(EncryptionManager.ENCRYPTION_FLAG, "true");
    //System.setProperty("ssl", "true");

    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID);

    String testFile = null;/*from w  ww .jav  a2  s. c  o  m*/

    try {
        File temp = Files.createTempFile("jpa-test-e", "." + JpaH2DataStore.FILE_EXT).toFile();
        Assert.assertTrue(temp.delete());
        temp.deleteOnExit();
        testFile = temp.getAbsolutePath();
    } catch (final IOException e) {
        Logger.getLogger(FileTransferTest.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
        fail();
    }

    // Start an engine and close so we have a populated file
    EngineFactory.bootLocalEngine(testFile, EngineFactory.DEFAULT, password, DataStoreType.H2_DATABASE);
    EngineFactory.closeEngine(EngineFactory.DEFAULT);

    final JpaNetworkServer networkServer = new JpaNetworkServer();

    final String serverFile = testFile;

    System.out.println("starting server");
    new StartServerThread(networkServer, serverFile, port, password).start();

    Thread.sleep(4000);

    try {
        Engine e = EngineFactory.bootClientEngine("localhost", port, password, EngineFactory.DEFAULT);

        Account account = new Account(AccountType.CASH, e.getDefaultCurrency());
        account.setName("test");
        e.addAccount(e.getRootAccount(), account);

        Path tempAttachment = Paths.get(Object.class.getResource("/jgnash-logo.png").toURI());
        assertTrue(Files.exists(tempAttachment));

        assertTrue(e.addAttachment(tempAttachment, true)); // push a copy of the attachment

        Thread.sleep(4000); // wait for the transfer to finish, it may have been pushed into the background

        Path newPath = Paths.get(AttachmentUtils.getAttachmentDirectory(Paths.get(testFile)) + File.separator
                + tempAttachment.getFileName());
        newPath.toFile().deleteOnExit();

        // Verify copy has occurred
        assertEquals(tempAttachment.toFile().length(), newPath.toFile().length()); // same length?
        assertNotEquals(tempAttachment.toString(), newPath.toString()); // different files?

        final Path attachmentPath = AttachmentUtils.getAttachmentDirectory(Paths.get(testFile));
        assertNotNull(attachmentPath);

        // Create a new temp file in the directory
        tempAttachment = Files.createTempFile(attachmentPath, "tempfile2-", ".txt");
        tempAttachment.toFile().deleteOnExit();

        //write it
        try (BufferedWriter bw = Files.newBufferedWriter(tempAttachment, Charset.defaultCharset())) {
            bw.write("This is the temporary file content 2.");
        }

        Future<Path> pathFuture = e.getAttachment(tempAttachment.getFileName().toString());

        Path remoteTemp = pathFuture.get();

        assertTrue(Files.exists(remoteTemp));
        assertNotEquals(remoteTemp.toString(), tempAttachment.toString());

        EngineFactory.closeEngine(EngineFactory.DEFAULT);
    } catch (final Exception e) {
        Logger.getLogger(FileTransferTest.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
        fail();
    }

}

From source file:jgnash.engine.FileTransferTest.java

License:Open Source License

@Test
public void networkedTest() throws Exception {
    final char[] password = new char[] {};
    final int port = 5400;

    //System.setProperty(EncryptionManager.ENCRYPTION_FLAG, "false");
    //System.setProperty("ssl", "false");

    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID);

    String testFile = null;/* w w w  .j a v  a2s.  c  om*/

    try {
        File temp = Files.createTempFile("jpa-test", "." + JpaHsqlDataStore.FILE_EXT).toFile();
        Assert.assertTrue(temp.delete());
        temp.deleteOnExit();
        testFile = temp.getAbsolutePath();
    } catch (final IOException e) {
        Logger.getLogger(FileTransferTest.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
        fail();
    }

    // Start an engine and close so we have a populated file
    EngineFactory.bootLocalEngine(testFile, EngineFactory.DEFAULT, password, DataStoreType.HSQL_DATABASE);
    EngineFactory.closeEngine(EngineFactory.DEFAULT);

    final JpaNetworkServer networkServer = new JpaNetworkServer();

    final String serverFile = testFile;

    Logger.getLogger(FileTransferTest.class.getName()).info("Starting Server");
    new StartServerThread(networkServer, serverFile, port, password).start();

    Thread.sleep(4000);

    try {
        Engine e = EngineFactory.bootClientEngine("localhost", port, password, EngineFactory.DEFAULT);

        Account account = new Account(AccountType.CASH, e.getDefaultCurrency());
        account.setName("test");
        e.addAccount(e.getRootAccount(), account);

        Path tempAttachment = Paths.get(Object.class.getResource("/jgnash-logo.png").toURI());
        assertTrue(Files.exists(tempAttachment));

        assertTrue(e.addAttachment(tempAttachment, true)); // push a copy of the attachment

        Thread.sleep(4000); // wait for transfer to finish

        Path newPath = Paths.get(AttachmentUtils.getAttachmentDirectory(Paths.get(testFile)) + File.separator
                + tempAttachment.getFileName());
        newPath.toFile().deleteOnExit();

        // Verify copy has occurred
        assertEquals(tempAttachment.toFile().length(), newPath.toFile().length()); // same length?
        assertNotEquals(tempAttachment.toString(), newPath.toString()); // different files?

        // Test that move is working
        Path moveFile = Files.createTempFile("jgnash", "test");

        try (final BufferedWriter bw = Files.newBufferedWriter(moveFile, Charset.defaultCharset())) {
            bw.write("This is the temporary file content 3.");
        }

        assertTrue(e.addAttachment(moveFile, false));
        assertFalse(Files.exists(moveFile));

        final Path attachmentPath = AttachmentUtils.getAttachmentDirectory(Paths.get(testFile));
        assertNotNull(attachmentPath);

        // Create a new temp file in the directory
        tempAttachment = Files.createTempFile(attachmentPath, "tempfile2-", ".txt");
        tempAttachment.toFile().deleteOnExit();

        try (final BufferedWriter bw = Files.newBufferedWriter(tempAttachment, Charset.defaultCharset())) {
            bw.write("This is the temporary file content 2.");
        }

        Future<Path> pathFuture = e.getAttachment(tempAttachment.getFileName().toString());

        Path remoteTemp = pathFuture.get();

        assertTrue(Files.exists(remoteTemp));
        assertNotEquals(remoteTemp.toString(), tempAttachment.toString());

        EngineFactory.closeEngine(EngineFactory.DEFAULT);
    } catch (Exception e) {
        Logger.getLogger(FileTransferTest.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
        fail();
    }

}

From source file:org.apache.bookkeeper.common.allocator.impl.ByteBufAllocatorImpl.java

License:Apache License

ByteBufAllocatorImpl(ByteBufAllocator pooledAllocator, ByteBufAllocator unpooledAllocator,
        PoolingPolicy poolingPolicy, int poolingConcurrency, OutOfMemoryPolicy outOfMemoryPolicy,
        Consumer<OutOfMemoryError> outOfMemoryListener, LeakDetectionPolicy leakDetectionPolicy) {
    super(poolingPolicy == PoolingPolicy.PooledDirect /* preferDirect */);

    this.poolingPolicy = poolingPolicy;
    this.outOfMemoryPolicy = outOfMemoryPolicy;
    if (outOfMemoryListener == null) {
        this.outOfMemoryListener = (v) -> {
            log.error("Unable to allocate memory", v);
        };// ww  w  . ja va2  s.  c  o m
    } else {
        this.outOfMemoryListener = outOfMemoryListener;
    }

    if (poolingPolicy == PoolingPolicy.PooledDirect) {
        if (pooledAllocator == null) {
            if (poolingConcurrency == PooledByteBufAllocator.defaultNumDirectArena()) {
                // If all the parameters are the same as in the default Netty pool,
                // just reuse the static instance as the underlying allocator.
                this.pooledAllocator = PooledByteBufAllocator.DEFAULT;
            } else {
                this.pooledAllocator = new PooledByteBufAllocator(true /* preferDirect */,
                        poolingConcurrency /* nHeapArena */, poolingConcurrency /* nDirectArena */,
                        PooledByteBufAllocator.defaultPageSize(), PooledByteBufAllocator.defaultMaxOrder(),
                        PooledByteBufAllocator.defaultTinyCacheSize(),
                        PooledByteBufAllocator.defaultSmallCacheSize(),
                        PooledByteBufAllocator.defaultNormalCacheSize(),
                        PooledByteBufAllocator.defaultUseCacheForAllThreads());
            }
        } else {
            this.pooledAllocator = pooledAllocator;
        }
    } else {
        this.pooledAllocator = null;
    }

    this.unpooledAllocator = (unpooledAllocator != null) ? unpooledAllocator : UnpooledByteBufAllocator.DEFAULT;

    // The setting is static in Netty, so it will actually affect all
    // allocators
    switch (leakDetectionPolicy) {
    case Disabled:
        if (log.isDebugEnabled()) {
            log.debug("Disable Netty allocator leak detector");
        }
        ResourceLeakDetector.setLevel(Level.DISABLED);
        break;

    case Simple:
        log.info("Setting Netty allocator leak detector to Simple");
        ResourceLeakDetector.setLevel(Level.SIMPLE);
        break;

    case Advanced:
        log.info("Setting Netty allocator leak detector to Advanced");
        ResourceLeakDetector.setLevel(Level.ADVANCED);
        break;

    case Paranoid:
        log.info("Setting Netty allocator leak detector to Paranoid");
        ResourceLeakDetector.setLevel(Level.PARANOID);
        break;
    }
}

From source file:org.apache.spark.network.netty.NettyTransportContext.java

License:Apache License

public NettyTransportContext(TransportConf conf, RpcHandler rpcHandler, boolean closeIdleConnections) {
    ResourceLeakDetector.setLevel(Level.DISABLED);
    this.conf = conf;
    this.rpcHandler = rpcHandler;
    this.encoder = new MessageEncoder();
    this.decoder = new MessageDecoder();
    this.closeIdleConnections = closeIdleConnections;
}

From source file:org.apache.zookeeper.test.TestByteBufAllocator.java

License:Apache License

/**
 * Get the singleton testing allocator.//  w  w w . ja  v a 2  s  .c  o  m
 * @return the singleton allocator, creating it if one does not exist.
 */
public static TestByteBufAllocator getInstance() {
    TestByteBufAllocator result = INSTANCE.get();
    if (result == null) {
        ResourceLeakDetector.Level oldLevel = ResourceLeakDetector.getLevel();
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID);
        INSTANCE.compareAndSet(null, new TestByteBufAllocator(oldLevel));
        result = INSTANCE.get();
    }
    return result;
}

From source file:org.apache.zookeeper.test.TestByteBufAllocator.java

License:Apache License

private void checkInstanceForLeaks() {
    try {/*from  w w  w .j  a  va  2 s .  c o m*/
        long referencedBuffersCount = 0;
        synchronized (this) {
            referencedBuffersCount = trackedBuffers.stream().filter(byteBuf -> byteBuf.refCnt() > 0).count();
            // Make tracked buffers eligible for GC
            trackedBuffers.clear();
        }
        // Throw an error if there were any leaked buffers
        if (referencedBuffersCount > 0) {
            // Trigger a GC. This will hopefully (but not necessarily) print
            // details about detected leaks to standard error before the error
            // is thrown.
            System.gc();
            throw new AssertionError("Found a netty ByteBuf leak!");
        }
    } finally {
        ResourceLeakDetector.setLevel(oldLevel);
    }
}

From source file:org.diorite.impl.CoreMain.java

License:Open Source License

public static InitResult init(final OptionSet options, final boolean client) {
    CoreMain.client = client;/*  w w w.  j  a  va2  s  .  c  o m*/
    if (options.has("version")) {
        return InitResult.VERSION;
    }
    if (options.has("?")) {
        return InitResult.HELP;
    }
    final String path = new File(".").getAbsolutePath();
    if (path.contains("!") || path.contains("+")) {
        System.err.println(
                "Cannot run server in a directory with ! or + in the pathname. Please rename the affected folders and try again.");
        return InitResult.STOP;
    }
    try {
        CoreMain.enabledDebug = options.has("debug");
        CoreMain.debug("===> Debug is enabled! <===");
        try {
            final String lvl = options.valueOf("rld").toString();
            if (lvl.length() == 1) {
                ResourceLeakDetector
                        .setLevel(ResourceLeakDetector.Level.values()[DioriteMathUtils.asInt(lvl, 0)]);
            } else {
                ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(lvl));
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
        if (options.has("noconsole")) {
            CoreMain.consoleEnabled = false;
        }
        int maxPermGen = 0;
        for (final String s : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
            if (s.startsWith("-XX:MaxPermSize")) {
                maxPermGen = DioriteMathUtils.asInt(PERM_GEN_PAT.matcher(s).replaceAll(""), 0);
                maxPermGen <<= 10 * "kmg".indexOf(Character.toLowerCase(s.charAt(s.length() - 1)));
            }
        }
        if ((Float.parseFloat(System.getProperty("java.class.version")) < JAVA_8) && (maxPermGen < MB_128)) {
            System.out.println(
                    "Warning, your max perm gen size is not set or less than 128mb. It is recommended you restart Java with the following argument: -XX:MaxPermSize=128M");
        }
        System.out.println("Starting server, please wait...");

        registerNbt();
        // register all packet classes.
        RegisterPackets.init();

        // TODO: load "magic values"
        // never remove this line (Material.values), it's needed even if it don't do anything for you.
        // it will force load all material classes, loading class of one material before "Material" is loaded will throw error.
        Material.values();
        System.out.println("Registered " + Material.getBlockMaterialsCount() + " ("
                + Material.getAllBlockMaterialsCount() + " with sub-types) diorite blocks.");
        System.out.println("Registered " + Material.getItemMaterialsCount() + " ("
                + Material.getAllItemMaterialsCount() + " with sub-types) diorite items.");
        System.out.println("Registered " + Material.getMaterialsCount() + " (" + Material.getAllMaterialsCount()
                + " with sub-types) diorite blocks and items.");
    } catch (final Throwable t) {
        t.printStackTrace();
    }
    return InitResult.RUN;
}

From source file:org.thingsboard.server.transport.mqtt.MqttTransportService.java

License:Apache License

@PostConstruct
public void init() throws Exception {
    log.info("Setting resource leak detector level to {}", leakDetectorLevel);
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

    log.info("Starting MQTT transport...");
    bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
    workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new MqttTransportServerInitializer(context));

    serverChannel = b.bind(host, port).sync().channel();
    log.info("Mqtt transport started!");
}