/*
 * Copyright (c) 2005 JetBrains s.r.o. All Rights Reserved.
 */
package com.intellij.ide;

import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import org.apache.xmlrpc.WebServer;
import org.jetbrains.annotations.NonNls;

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;

/**
 * @author mike
 */
public class XmlRpcServerImpl implements XmlRpcServer, ApplicationComponent {
  private static final Logger LOG = Logger.getInstance("#com.intellij.ide.XmlRpcServerImpl");
  public static final int PORT_NUMBER = 63342;
  private WebServer myWebServer;

  @NonNls
  public String getComponentName() {
    return "XmlRpcServer";
  }

  public void initComponent() {
    if (!checkPort()) return;

    try {
      myWebServer = new WebServer(PORT_NUMBER);
      myWebServer.start();
    }
    catch (Exception e) {
      LOG.error(e);
      myWebServer = null;
    }
  }

  private static boolean checkPort() {
    ServerSocket socket = null;

    try {
      socket = new ServerSocket(PORT_NUMBER);
    }
    catch (BindException e) {
      return false;
    }
    catch (IOException e) {
      LOG.error(e);
      return false;
    }
    finally {
      if (socket != null) {
        try {
          socket.close();
        }
        catch (IOException e) {
          LOG.error(e);
          return false;
        }
      }
    }

    return true;
  }

  public void disposeComponent() {
    if (myWebServer != null) {
      myWebServer.shutdown();
    }
  }

  public void addHandler(String name, Object handler) {
    if (myWebServer != null) {
      myWebServer.addHandler(name, handler);
    }
  }

  public void removeHandler(String name) {
    if (myWebServer != null) {
      myWebServer.removeHandler(name);
    }
  }
}

@@ -638,16 +638,86 @@
 bServer;
+%0A  @NonNls private static final String PROPERTY_RPC_PORT = %22rpc.port%22;
 %0A%0A  @Non
@@ -896,27 +896,31 @@
 bServer(
-PORT_NUMBER
+getPortNumber()
 );%0A     
@@ -1030,16 +1030,203 @@
  %7D%0A  %7D%0A%0A
+  private static int getPortNumber() %7B%0A    if (System.getProperty(PROPERTY_RPC_PORT) != null) return Integer.parseInt(System.getProperty(PROPERTY_RPC_PORT));%0A    return PORT_NUMBER;%0A  %7D%0A%0A
   privat
@@ -1331,27 +1331,31 @@
 rSocket(
-PORT_NUMBER
+getPortNumber()
 );%0A    %7D
@@ -1890,32 +1890,32 @@
 rver != null) %7B%0A
-
       myWebServe
@@ -1941,32 +1941,129 @@
 handler);%0A    %7D%0A
+    else %7B%0A      LOG.info(%22Handler not registered because XML-RPC server is not running%22);%0A    %7D%0A
   %7D%0A%0A  public vo

include jdom.jar in DevKit IDEA jars; setting for XML-RPC port number