/** @tests java.net.ServerSocket#bind(java.net.SocketAddress,int) */
  public void test_bindLjava_net_SocketAddressI() throws IOException {
    class mySocketAddress extends SocketAddress {

      public mySocketAddress() {}
    }

    // create servers socket, bind it and then validate basic state
    ServerSocket theSocket = new ServerSocket();
    InetSocketAddress theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
    theSocket.bind(theAddress, 5);
    int portNumber = theSocket.getLocalPort();
    assertTrue(
        "Returned incorrect InetSocketAddress(2):"
            + theSocket.getLocalSocketAddress().toString()
            + "Expected: "
            + (new InetSocketAddress(InetAddress.getLocalHost(), portNumber)).toString(),
        theSocket
            .getLocalSocketAddress()
            .equals(new InetSocketAddress(InetAddress.getLocalHost(), portNumber)));
    assertTrue("Server socket not bound when it should be:", theSocket.isBound());

    // now make sure that it is actually bound and listening on the
    // address we provided
    SocketAddress localAddress = theSocket.getLocalSocketAddress();
    Socket clientSocket = new Socket();
    clientSocket.connect(localAddress);
    Socket servSock = theSocket.accept();

    assertTrue(clientSocket.getRemoteSocketAddress().equals(localAddress));
    theSocket.close();
    servSock.close();
    clientSocket.close();

    // validate we can specify null for the address in the bind and all
    // goes ok
    theSocket = new ServerSocket();
    theSocket.bind(null, 5);
    theSocket.close();

    // Address that we have already bound to
    theSocket = new ServerSocket();
    ServerSocket theSocket2 = new ServerSocket();
    try {
      theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
      theSocket.bind(theAddress, 5);
      SocketAddress inuseAddress = theSocket.getLocalSocketAddress();
      theSocket2.bind(inuseAddress, 5);
      fail("No exception binding to address that is not available");
    } catch (IOException ex) {
      // expected
    }
    theSocket.close();
    theSocket2.close();

    // validate we get ioException when we try to bind to address we
    // cannot bind to
    theSocket = new ServerSocket();
    try {
      theSocket.bind(
          new InetSocketAddress(
              InetAddress.getByAddress(Support_Configuration.nonLocalAddressBytes), 0),
          5);
      fail("No exception was thrown when binding to bad address");
    } catch (IOException ex) {
    }
    theSocket.close();

    // now validate case where we pass in an unsupported subclass of
    // SocketAddress
    theSocket = new ServerSocket();
    try {
      theSocket.bind(new mySocketAddress(), 5);
      fail("Binding using unsupported SocketAddress subclass should have thrown exception");
    } catch (IllegalArgumentException ex) {
    }
    theSocket.close();

    // now validate that backlog is respected. We have to do a test that
    // checks if it is a least a certain number as some platforms make
    // it higher than we request. Unfortunately non-server versions of
    // windows artificially limit the backlog to 5 and 5 is the
    // historical default so it is not a great test.
    theSocket = new ServerSocket();
    theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
    theSocket.bind(theAddress, 4);
    localAddress = theSocket.getLocalSocketAddress();
    Socket theSockets[] = new Socket[4];
    int i = 0;
    try {
      for (i = 0; i < 4; i++) {
        theSockets[i] = new Socket();
        theSockets[i].connect(localAddress);
      }
    } catch (ConnectException ex) {
      fail("Backlog does not seem to be respected in bind:" + i + ":" + ex.toString());
    }

    for (i = 0; i < 4; i++) {
      theSockets[i].close();
    }

    theSocket.close();
    servSock.close();
  }
Exemplo n.º 2
0
  /*
   * Method for sending request and accepting response
   *
   * Input: methodName = first level method name (i.e. GetAttributeList, RegisterDevice)
   * 		  reqName = second level method name (i.e. GetAttrListRequest, RegisterDeviceRequest)
   *        propertyList = the list of pairs of properties for this request
   * Output: responding SoapObject can be converted to specific request object for further use
   */
  private Object sendRequest(
      MethodEnum methodName,
      RequestEnum reqName,
      ArrayList<DataParam> propertyList,
      String ns,
      String url) {
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    SoapObject req1 = new SoapObject(ns, methodName.toString());
    SoapObject req2 = new SoapObject(ns, reqName.toString());
    SoapObject response = null;
    SoapTypeWrapper soapWrap = null;

    for (int i = 0; i < propertyList.size(); i++) {
      // parse attribute list for bookjob request only
      if (propertyList.get(i).name.equalsIgnoreCase("attributelist")) {
        if (GlobalVar.logEnable) {
          Log.d(TAG, propertyList.get(i).name + " :: " + propertyList.get(i).value);
        }

        String[] tokens = propertyList.get(i).value.split(",");

        for (int j = 0; j < tokens.length; j++) {
          SoapObject attrSoap = new SoapObject("", "attributelist");
          attrSoap.addProperty("attrShortName", tokens[j]);
          req2.addSoapObject(attrSoap);
        }
      } else if (propertyList.get(i).name.equalsIgnoreCase("zipCode")) {
        if (GlobalVar.logEnable) {
          Log.d(TAG, propertyList.get(i).name + " :: " + propertyList.get(i).value);
        }
        // TL-301
        PropertyInfo pi = new PropertyInfo();
        pi.setNamespace(ns);
        pi.setType(PropertyInfo.STRING_CLASS);
        pi.setName(propertyList.get(i).name);
        pi.setValue(propertyList.get(i).value);
        req1.addProperty(pi);
      } else {
        req2.addProperty(propertyList.get(i).name, propertyList.get(i).value);
      }
    }

    req1.addSoapObject(req2);
    envelope.setOutputSoapObject(req1);
    envelope.implicitTypes = true;
    envelope.setAddAdornments(false);

    try {
      HttpTransportSE ht = new HttpTransportSE(url);
      ht.debug = true;

      if (!methodName.equals(MethodEnum.RegDev)) {
        ht.call(ns + methodName, envelope);
      } else {
        ht.call("", envelope);
      }

      if (GlobalVar.logEnable) {
        Log.v(TAG + "-request", ht.requestDump);

        int len = ht.responseDump.length();
        for (int ix = 0; ix < len; ix += 4000) {
          if (ix + 4000 < len) {
            Log.v(TAG + "-response", ht.responseDump.substring(ix, ix + 4000));
          } else {
            Log.v(TAG + "-response", ht.responseDump.substring(ix, len));
          }
        }
      }

      if (envelope.getResponse() instanceof SoapPrimitive) {
        return envelope.getResponse();
      } else {
        response = (SoapObject) envelope.getResponse();
        soapWrap = new SoapTypeWrapper(response, methodName);

        return soapWrap;
      }
    } catch (ConnectException ce) {
      if (GlobalVar.logEnable) {
        Log.v(TAG + "-ConnectError", ce.toString());
      }

      return GlobalVar.CONNECTION_ERROR;
    } catch (Exception e) {
      if (GlobalVar.logEnable) {
        Log.v(TAG + "-Error", e.toString());
      }

      return GlobalVar.GENERIC_ERROR;
    }
  }
  /**
   * Starts the debugger. The method stops the current debugging (if any) and takes information from
   * the provided info (containing the class to start and arguments to pass it and name of class to
   * stop debugging in) and starts new debugging session.
   *
   * @param info debugger info about class to start
   * @exception DebuggerException if an error occures during the start of the debugger
   */
  public void startDebugger(DebuggerInfo info) throws DebuggerException {
    debuggerInfo = info;
    if (remoteDebugger != null) finishDebugger();
    // S ystem.out.println("startDebugger " + info); // NOI18N
    // RemoteDebugging support
    hostName = null;
    password = null;
    boolean local = true;
    if (info instanceof ReconnectDebuggerInfo) {
      ReconnectDebuggerInfo rdi = (ReconnectDebuggerInfo) info;
      hostName = rdi.getHostName();
      password = rdi.getPassword();
      local = false;
    } else if (info instanceof RemoteDebuggerInfo) {
      hostName = ((RemoteDebuggerInfo) info).getHostName();
      password = ((RemoteDebuggerInfo) info).getPassword();
      local = false;
    }
    boolean stopOnMain = info.getStopClassName() != null;
    stopOnMainFlag = stopOnMain;
    // S ystem.out.println ("ToolsDebugger.startDebugger " + info.getStopClassName ()); // NOI18N
    // T hread.dumpStack ();

    synchronizer = new RequestSynchronizer();

    // open output window ...
    super.startDebugger(info);

    // start & init remote debugger ................................................
    //    process = null;
    if (local) {
      // create process & read password for local debugging

      // create starting string & NbProcessDescriptor
      NbProcessDescriptor debugerProcess;
      if (info instanceof ProcessDebuggerInfo)
        debugerProcess = ((ProcessDebuggerInfo) info).getDebuggerProcess();
      else debugerProcess = ProcessDebuggerType.DEFAULT_DEBUGGER_PROCESS;
      HashMap map;
      if (info instanceof ToolsDebugger10Info) {
        map =
            Utils.processDebuggerInfo(
                info,
                "-debug", // NOI18N
                "sun.tools.debug.EmptyApp" // NOI18N
                );
        map.put(ToolsDebugger10Type.JAVA_HOME_SWITCH, ((ToolsDebugger10Info) info).getJavaHome());
      } else {
        if (info instanceof ToolsDebugger11Info) {
          String javaHome11 = ((ToolsDebugger11Info) info).getJavaHome();
          if ((javaHome11 == null) || (javaHome11.trim().length() == 0)) {
            finishDebugger();
            throw new DebuggerException(bundle.getString("EXC_JDK11_home_is_not_set"));
          }
          map =
              Utils.processDebuggerInfo(
                  info,
                  "-debug -nojit", // NOI18N
                  "sun.tools.debug.EmptyApp" // NOI18N
                  );
          map.put(ToolsDebugger11Type.JAVA_HOME_SWITCH, javaHome11);
        } else {
          map =
              Utils.processDebuggerInfo(
                  info,
                  "-Xdebug", // NOI18N
                  "sun.tools.agent.EmptyApp" // NOI18N
                  );
        }
      }
      MapFormat format = new MapFormat(map);
      String s =
          format.format(
              debugerProcess.getProcessName() + " " + debugerProcess.getArguments() // NOI18N
              );
      println(s, ERR_OUT);

      // start process & read password ......................................
      try {
        process = debugerProcess.exec(format);
        BufferedReader bufferedreader =
            new BufferedReader(new InputStreamReader(process.getInputStream()));
        password = bufferedreader.readLine();
        showOutput(process, ERR_OUT, ERR_OUT);
        connectInput(process);
      } catch (java.lang.Exception e) {
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_While_create_debuggee"))
                .format(
                    new Object[] {format.format(debugerProcess.getProcessName()), e.toString()}),
            e);
      }
      if (password == null) {
        // no reply
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_While_connect_to_debuggee"))
                .format(new Object[] {format.format(debugerProcess.getProcessName())}));
      }
      if (password.indexOf("=") < 0) { // NOI18N
        // unexpected reply
        println(bundle.getString("CTL_Unexpected_reply") + ": " + password, ERR_OUT);
        showOutput(process, ERR_OUT + STD_OUT, ERR_OUT);
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_Unecpected_debugger_reply"))
                .format(new Object[] {password}));
      }
      password = password.substring(password.indexOf("=") + 1); // NOI18N
      println(bundle.getString("CTL_Password") + ": " + password, ERR_OUT);
      hostName = "127.0.0.1"; // NOI18N
    } // end of local debugging specific
    else if (info instanceof ReconnectDebuggerInfo) {
      println(bundle.getString("CTL_Reconnecting"), ERR_OUT | STD_OUT);
    } else
      println(bundle.getString("CTL_Connecting_to") + ": " + hostName + ":" + password, ERR_OUT);

    // start RemoteDebugger ...................................................
    try {
      remoteDebugger =
          new RemoteDebugger(
              hostName,
              password.length() < 1 ? null : password,
              new ToolsCallback(this),
              isShowMessages());
    } catch (java.net.ConnectException e) {
      finishDebugger();
      throw new DebuggerException(
          new MessageFormat(bundle.getString("EXC_Cannot_connect_to_debuggee"))
              .format(new Object[] {e.toString()}),
          e);
    } catch (Throwable e) {
      if (e instanceof ThreadDeath) throw (ThreadDeath) e;
      // e.printStackTrace ();
      finishDebugger();
      throw new DebuggerException(
          new MessageFormat(bundle.getString("EXC_Cannot_connect_to_debuggee"))
              .format(new Object[] {e.toString()}),
          e);
    }

    // create arguments for main class ...............................................
    mainClassName = info.getClassName();
    RemoteClass cls;
    String[] args = null;
    if ((mainClassName != null) && (mainClassName.length() > 0)) {
      String[] infoArgs = info.getArguments();
      args = new String[infoArgs.length + 1];
      args[0] = mainClassName;
      System.arraycopy(infoArgs, 0, args, 1, infoArgs.length);
      // args[0] = name of class
      // args[...] = parameters

      // find main class .........................................................
      try {
        cls = remoteDebugger.findClass(mainClassName);
      } catch (Throwable e) {
        if (e instanceof ThreadDeath) throw (ThreadDeath) e;
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_Cannot_find_class"))
                .format(new Object[] {mainClassName, e.toString()}),
            e);
      }
      if (cls == null) {
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_Cannot_find_class"))
                .format(new Object[] {mainClassName, new ClassNotFoundException().toString()}));
      }
    }

    // set breakpoint on stop class method ...............................................
    if (stopOnMain) {
      RemoteClass stopClass = null;
      try {
        stopClass = remoteDebugger.findClass(stopClassName = info.getStopClassName());
      } catch (Throwable e) {
        if (e instanceof ThreadDeath) throw (ThreadDeath) e;
        println(
            bundle.getString("MSG_Exc_while_finding_class") + stopClassName + '\n' + e, ERR_OUT);
      }
      if (stopClass == null) {
        println(bundle.getString("CTL_No_such_class") + ": " + stopClassName, ERR_OUT);
      } else {
        try {
          RemoteField[] rf = stopClass.getMethods();
          int i, k = rf.length;
          Type t = Type.tMethod(Type.tVoid, new Type[] {Type.tArray(Type.tString)});
          Type startT = Type.tMethod(Type.tVoid);
          RemoteField startM = null;
          RemoteField initM = null;
          RemoteField constM = null;
          for (i = 0; i < k; i++) {
            if (rf[i].getName().equals("main")
                && // NOI18N
                rf[i].getType().equals(t)) break;
            else if (rf[i].getName().equals("start")
                && // NOI18N
                rf[i].getType().equals(startT)) startM = rf[i];
            else if (rf[i].getName().equals("init")
                && // NOI18N
                rf[i].getType().equals(startT)) initM = rf[i];
            else if (rf[i].getName().equals("<init>")
                && // NOI18N
                rf[i].getType().equals(startT)) constM = rf[i];
          }
          if (i < k) // [PENDING] stop on non main too !!!!!!!!!!!!!!!!!!!!!
          stopClass.setBreakpointMethod(rf[i]); // have main
          else if (initM != null) stopClass.setBreakpointMethod(initM);
          else if (startM != null) stopClass.setBreakpointMethod(startM);
          else if (constM != null) stopClass.setBreakpointMethod(constM);

          // S ystem.out.println ("Stop: " + (i <k) + " " + initM +" " + startM +" " + constM); //
          // NOI18N
          /*          pendingBreakpoints = new RemoteField [1];
          pendingBreakpoints [0] = rf[i];
          pendingBreakpointsClass = stopClass;*/
        } catch (Throwable e) {
          if (e instanceof ThreadDeath) throw (ThreadDeath) e;
          println(bundle.getString("MSG_Exc_while_setting_breakpoint") + '\n' + e, ERR_OUT);
        }
      }
    } // stopOnMain

    setBreakpoints();
    updateWatches();
    println(bundle.getString("CTL_Debugger_running"), STL_OUT);
    setDebuggerState(DEBUGGER_RUNNING);

    // run debugged class ...............................................
    if (args != null) {
      RemoteThreadGroup rtg = null;
      try {
        rtg = remoteDebugger.run(args.length, args);
        //        threadGroup.setRemoteThreadGroup (rtg);
      } catch (Throwable e) {
        if (e instanceof ThreadDeath) throw (ThreadDeath) e;
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_While_calling_run"))
                .format(new Object[] {mainClassName, e.toString()}),
            e);
      }
      if (rtg == null) {
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_While_calling_run"))
                .format(
                    new Object[] {
                      mainClassName, "" // NOI18N
                    }));
      }
    }

    // start refresh thread .................................................
    if (debuggerThread != null) debuggerThread.stop();
    debuggerThread =
        new Thread(
            new Runnable() {
              public void run() {
                for (; ; ) {
                  try {
                    Thread.sleep(5000);
                  } catch (InterruptedException ex) {
                  }
                  if (getState() == DEBUGGER_RUNNING)
                    try {
                      threadGroup.threadChanged();

                    } catch (Throwable e) {
                      if (e instanceof ThreadDeath) throw (ThreadDeath) e;
                      if (e instanceof java.net.SocketException) {
                        debuggerThread = null;
                        try {
                          finishDebugger();
                        } catch (Throwable ee) {
                          if (ee instanceof ThreadDeath) throw (ThreadDeath) ee;
                        }
                        Thread.currentThread().stop();
                      }
                    }
                }
              }
            },
            "Debugger refresh thread"); // NOI18N
    debuggerThread.setPriority(Thread.MIN_PRIORITY);
    debuggerThread.start();
  }