1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.log4j.net;
18  
19  import java.io.ByteArrayOutputStream;
20  import java.io.IOException;
21  import java.io.InputStream;
22  import java.net.Socket;
23  
24  import org.apache.log4j.Logger;
25  import org.apache.log4j.PatternLayout;
26  
27  import junit.framework.TestCase;
28  
29  public class TelnetAppenderTest extends TestCase {
30  
31    int port = 54353;
32    ByteArrayOutputStream bo = new ByteArrayOutputStream();
33  
34    public class ReadThread extends Thread {
35      public void run() {
36        try {
37          Socket s = new Socket("localhost", port);
38          InputStream i = s.getInputStream();
39          while (!Thread.interrupted()) {
40            int c = i.read();
41            if (c == -1)
42              break;
43            bo.write(c);
44          }
45          s.close();
46        } catch (IOException e) {
47          e.printStackTrace();
48        }
49      }
50    }
51  
52    public void testIt() throws Exception {
53      int oldActive = Thread.activeCount();
54      TelnetAppender ta = new TelnetAppender();
55      ta.setName("ta");
56      ta.setPort(port);
57      ta.setLayout(new PatternLayout("%p - %m"));
58      ta.activateOptions();
59      Logger l = Logger.getLogger("x");
60      l.addAppender(ta);
61      Thread t = new ReadThread();
62      t.start();
63      Thread.sleep(200);
64      l.info("hi");
65      Thread.sleep(1000);
66      ta.close();
67      Thread.sleep(200);
68      t.interrupt();
69      t.join();
70      String s = bo.toString();
71      assertTrue(s.endsWith("INFO - hi"));
72      if(System.getProperty("java.vendor").indexOf("Free") == -1) {
73          assertEquals(oldActive, Thread.activeCount());
74      }
75    }
76  
77  }