Search in sources :

Example 71 with Logger

use of java.util.logging.Logger in project jmonkeyengine by jMonkeyEngine.

the class TestChatServer method main.

public static void main(String... args) throws Exception {
    // Increate the logging level for networking...
    System.out.println("Setting logging to max");
    Logger networkLog = Logger.getLogger("com.jme3.network");
    networkLog.setLevel(Level.FINEST);
    // And we have to tell JUL's handler also   
    // turn up logging in a very convoluted way
    Logger rootLog = Logger.getLogger("");
    if (rootLog.getHandlers().length > 0) {
        rootLog.getHandlers()[0].setLevel(Level.FINEST);
    }
    TestChatServer chatServer = new TestChatServer();
    chatServer.start();
    System.out.println("Waiting for connections on port:" + PORT);
    // Keep running basically forever
    while (chatServer.isRunning) {
        synchronized (chatServer) {
            chatServer.wait();
        }
    }
}
Also used : Logger(java.util.logging.Logger)

Example 72 with Logger

use of java.util.logging.Logger in project jna by java-native-access.

the class Kernel32NamedPipeTest method testMultiThreadedNamedPipe.

@Test
public void testMultiThreadedNamedPipe() {
    final String pipeName = "\\\\.\\pipe\\" + getCurrentTestName();
    final Logger logger = Logger.getLogger(getClass().getName());
    final int MAX_BUFFER_SIZE = 1024;
    ExecutorService executors = Executors.newFixedThreadPool(2);
    try {
        Future<?> server = executors.submit(new Runnable() {

            @Override
            public void run() {
                // based on https://msdn.microsoft.com/en-us/library/windows/desktop/aa365588(v=vs.85).aspx
                HANDLE hNamedPipe = assertValidHandle("CreateNamedPipe", Kernel32.INSTANCE.CreateNamedPipe(pipeName, // dwOpenMode
                WinBase.PIPE_ACCESS_DUPLEX, // dwPipeMode
                WinBase.PIPE_TYPE_MESSAGE | WinBase.PIPE_READMODE_MESSAGE | WinBase.PIPE_WAIT, // nMaxInstances,
                1, // nOutBufferSize,
                MAX_BUFFER_SIZE, // nInBufferSize,
                MAX_BUFFER_SIZE, // nDefaultTimeOut,
                (int) TimeUnit.SECONDS.toMillis(30L), // lpSecurityAttributes
                null));
                try {
                    logger.info("Await client connection");
                    assertCallSucceeded("ConnectNamedPipe", Kernel32.INSTANCE.ConnectNamedPipe(hNamedPipe, null));
                    logger.info("Client connected");
                    byte[] readBuffer = new byte[MAX_BUFFER_SIZE];
                    IntByReference lpNumberOfBytesRead = new IntByReference(0);
                    assertCallSucceeded("ReadFile", Kernel32.INSTANCE.ReadFile(hNamedPipe, readBuffer, readBuffer.length, lpNumberOfBytesRead, null));
                    int readSize = lpNumberOfBytesRead.getValue();
                    logger.info("Received client data - length=" + readSize);
                    assertTrue("No data receieved from client", readSize > 0);
                    IntByReference lpNumberOfBytesWritten = new IntByReference(0);
                    assertCallSucceeded("WriteFile", Kernel32.INSTANCE.WriteFile(hNamedPipe, readBuffer, readSize, lpNumberOfBytesWritten, null));
                    logger.info("Echoed client data - length=" + lpNumberOfBytesWritten.getValue());
                    assertEquals("Mismatched write buffer size", readSize, lpNumberOfBytesWritten.getValue());
                    // Flush the pipe to allow the client to read the pipe's contents before disconnecting
                    assertCallSucceeded("FlushFileBuffers", Kernel32.INSTANCE.FlushFileBuffers(hNamedPipe));
                    logger.info("Disconnecting");
                    assertCallSucceeded("DisconnectNamedPipe", Kernel32.INSTANCE.DisconnectNamedPipe(hNamedPipe));
                    logger.info("Disconnected");
                } finally {
                    // clean up
                    assertCallSucceeded("Named pipe handle close", Kernel32.INSTANCE.CloseHandle(hNamedPipe));
                }
            }
        });
        logger.info("Started server - handle=" + server);
        Future<?> client = executors.submit(new Runnable() {

            @Override
            public void run() {
                // based on https://msdn.microsoft.com/en-us/library/windows/desktop/aa365592(v=vs.85).aspx
                assertCallSucceeded("WaitNamedPipe", Kernel32.INSTANCE.WaitNamedPipe(pipeName, (int) TimeUnit.SECONDS.toMillis(15L)));
                logger.info("Connected to server");
                HANDLE hPipe = assertValidHandle("CreateNamedPipe", Kernel32.INSTANCE.CreateFile(pipeName, WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, // no sharing
                0, // default security attributes
                null, // opens existing pipe
                WinNT.OPEN_EXISTING, // default attributes
                0, // no template file
                null));
                try {
                    IntByReference lpMode = new IntByReference(WinBase.PIPE_READMODE_MESSAGE);
                    assertCallSucceeded("SetNamedPipeHandleState", Kernel32.INSTANCE.SetNamedPipeHandleState(hPipe, lpMode, null, null));
                    String expMessage = Thread.currentThread().getName() + " says hello";
                    byte[] expData = expMessage.getBytes();
                    IntByReference lpNumberOfBytesWritten = new IntByReference(0);
                    assertCallSucceeded("WriteFile", Kernel32.INSTANCE.WriteFile(hPipe, expData, expData.length, lpNumberOfBytesWritten, null));
                    logger.info("Sent hello message");
                    assertEquals("Mismatched write buffer size", expData.length, lpNumberOfBytesWritten.getValue());
                    byte[] readBuffer = new byte[MAX_BUFFER_SIZE];
                    IntByReference lpNumberOfBytesRead = new IntByReference(0);
                    assertCallSucceeded("ReadFile", Kernel32.INSTANCE.ReadFile(hPipe, readBuffer, readBuffer.length, lpNumberOfBytesRead, null));
                    int readSize = lpNumberOfBytesRead.getValue();
                    logger.info("Received server data - length=" + readSize);
                    assertTrue("No data receieved from server", readSize > 0);
                    String actMessage = new String(readBuffer, 0, readSize);
                    assertEquals("Mismatched server data", expMessage, actMessage);
                } finally {
                    // clean up
                    assertCallSucceeded("Named pipe handle close", Kernel32.INSTANCE.CloseHandle(hPipe));
                }
            }
        });
        logger.info("Started client - handle=" + client);
        for (Future<?> f : Arrays.asList(client, server)) {
            try {
                f.get(30L, TimeUnit.SECONDS);
                logger.info("Finished " + f);
            } catch (Exception e) {
                logger.warning(e.getClass().getSimpleName() + " while await completion of " + f + ": " + e.getMessage());
            }
        }
    } finally {
        executors.shutdownNow();
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) ExecutorService(java.util.concurrent.ExecutorService) Logger(java.util.logging.Logger) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE) Test(org.junit.Test)

Example 73 with Logger

use of java.util.logging.Logger in project MSEC by Tencent.

the class SendCmdsToAgentAndRun method doSendCmdsToAgentAndRun.

private String doSendCmdsToAgentAndRun(SendCmdsToAgentAndRunRequest request, StringBuffer outputFileName) {
    Socket socket = new Socket();
    Logger logger = Logger.getLogger("remote_shell");
    try {
        File file = new File(request.getLocalFileFullName());
        //����ִ�к���������ļ�������
        String outFileName = String.format("/tmp/output_%d.txt", (int) (Math.random() * Integer.MAX_VALUE));
        outputFileName.delete(0, outputFileName.length());
        outputFileName.append(outFileName);
        //�������ļ�����ǩ��
        String signature = "";
        if (Main.privateKey != null) {
            signature = geneSignature(request.getLocalFileFullName());
        }
        socket.connect(new InetSocketAddress(request.getRemoteServerIP(), 9981), 1000);
        String s = "{\"handleClass\":\"SendCmdsToAgentAndRun\", \"requestBody\":{" + "\"cmdFileLength\":" + String.format("%d", file.length()) + ", \"outputFileName\":\"" + outFileName + "\"" + ", \"signature\":\"" + signature + "\"" + "}}";
        s = Tools.getLengthField(s.length()) + s;
        socket.getOutputStream().write(s.getBytes());
        logger.info(String.format("write json complete.%s", s));
        //send file content
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] buf = new byte[10240];
        int total_len = 0;
        while (true) {
            int len = fileInputStream.read(buf);
            if (len <= 0) {
                break;
            }
            total_len += len;
            socket.getOutputStream().write(buf, 0, len);
        }
        logger.info(String.format("write file bytes number:%d", total_len));
        socket.shutdownOutput();
        ;
        //recv the response
        // length field 10bytes
        total_len = 0;
        while (total_len < 10) {
            int len = socket.getInputStream().read(buf, total_len, 10 - total_len);
            if (len <= 0) {
                return "recv response failed!";
            }
            total_len += len;
        }
        int jsonLen = new Integer(new String(buf, 0, total_len).trim()).intValue();
        if (jsonLen < 2) {
            return "response json string empty";
        }
        logger.info(String.format("response json string len:%d", jsonLen));
        total_len = 0;
        while (jsonLen < buf.length && total_len < jsonLen) {
            int len = socket.getInputStream().read(buf, total_len, jsonLen - total_len);
            if (len <= 0) {
                break;
            }
            total_len += len;
        }
        logger.info(String.format("read agent response bytes number:%d", total_len));
        String jsonStr = new String(buf, 0, total_len);
        JSONObject jsonObject = new JSONObject(jsonStr);
        String message = jsonObject.getString("message");
        int status = jsonObject.getInt("status");
        if (status == 0) {
            return "success";
        } else {
            return message;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return e.toString();
    }
}
Also used : JSONObject(org.json.JSONObject) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) Logger(java.util.logging.Logger) File(java.io.File) Socket(java.net.Socket) FileInputStream(java.io.FileInputStream)

Example 74 with Logger

use of java.util.logging.Logger in project MSEC by Tencent.

the class SendCmdsToAgentAndRun method exec.

public SendCmdsToAgentAndRunResponse exec(SendCmdsToAgentAndRunRequest request) {
    Logger logger = Logger.getLogger("remote_shell");
    logger.setLevel(Level.ALL);
    logger.info(String.format("I will send cmd to agent, [%s][%s]", request.getLocalFileFullName(), request.getRemoteServerIP()));
    StringBuffer sb = new StringBuffer();
    String result = doSendCmdsToAgentAndRun(request, sb);
    if (result.equals("success")) {
        logger.info(String.format("output file name: %s", sb.toString()));
        SendCmdsToAgentAndRunResponse response = new SendCmdsToAgentAndRunResponse();
        response.setMessage("success");
        response.setOutputFileName(sb.toString());
        response.setStatus(0);
        return response;
    } else {
        SendCmdsToAgentAndRunResponse response = new SendCmdsToAgentAndRunResponse();
        response.setMessage(result);
        response.setStatus(100);
        return response;
    }
}
Also used : SendCmdsToAgentAndRunResponse(comm_with_client.response.SendCmdsToAgentAndRunResponse) Logger(java.util.logging.Logger)

Example 75 with Logger

use of java.util.logging.Logger in project android_frameworks_base by ParanoidAndroid.

the class CookiesTest method testCookiesAreNotLogged.

/**
     * Test that we don't log potentially sensitive cookie values.
     * http://b/3095990
     */
public void testCookiesAreNotLogged() throws IOException, URISyntaxException {
    // enqueue an HTTP response with a cookie that will be rejected
    server.enqueue(new MockResponse().addHeader("Set-Cookie: password=secret; Domain=fake.domain"));
    server.play();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Logger logger = Logger.getLogger("org.apache.http");
    StreamHandler handler = new StreamHandler(out, new SimpleFormatter());
    logger.addHandler(handler);
    try {
        HttpClient client = new DefaultHttpClient();
        client.execute(new HttpGet(server.getUrl("/").toURI()));
        handler.close();
        String log = out.toString("UTF-8");
        assertTrue(log, log.contains("password"));
        assertTrue(log, log.contains("fake.domain"));
        assertFalse(log, log.contains("secret"));
    } finally {
        logger.removeHandler(handler);
    }
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) StreamHandler(java.util.logging.StreamHandler) SimpleFormatter(java.util.logging.SimpleFormatter) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Logger(java.util.logging.Logger) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Aggregations

Logger (java.util.logging.Logger)499 Test (org.junit.Test)70 LogRecord (java.util.logging.LogRecord)60 ActionReport (org.glassfish.api.ActionReport)56 Handler (java.util.logging.Handler)52 IOException (java.io.IOException)37 File (java.io.File)36 Level (java.util.logging.Level)25 ArrayList (java.util.ArrayList)22 ConsoleHandler (java.util.logging.ConsoleHandler)19 Properties (java.util.Properties)15 SimpleFormatter (java.util.logging.SimpleFormatter)15 Config (com.sun.enterprise.config.serverbeans.Config)14 HashMap (java.util.HashMap)14 Map (java.util.Map)12 ByteArrayOutputStream (java.io.ByteArrayOutputStream)11 ResourceBundle (java.util.ResourceBundle)11 LogManager (java.util.logging.LogManager)11 ExtendedDeploymentContext (org.glassfish.internal.deployment.ExtendedDeploymentContext)11 BlockingQueueHandler (fish.payara.nucleus.notification.BlockingQueueHandler)10