Beispiel #1
1
  /**
   * Start this server. If we manage an own HttpServer, then the HttpServer will be started as well.
   */
  public void start() {
    // URL as configured takes precedence
    String configUrl =
        NetworkUtil.replaceExpression(config.getJolokiaConfig().get(ConfigKey.DISCOVERY_AGENT_URL));
    jolokiaHttpHandler.start(
        lazy, configUrl != null ? configUrl : url, config.getAuthenticator() != null);

    if (httpServer != null) {
      // Starting our own server in an own thread group with a fixed name
      // so that the cleanup thread can recognize it.
      ThreadGroup threadGroup = new ThreadGroup("jolokia");
      threadGroup.setDaemon(false);

      Thread starterThread =
          new Thread(
              threadGroup,
              new Runnable() {
                @Override
                public void run() {
                  httpServer.start();
                }
              });
      starterThread.start();
      cleaner = new CleanupThread(httpServer, threadGroup);
      cleaner.start();
    }
  }
Beispiel #2
1
 @Override
 /** {@inheritDoc} */
 public Thread newThread(Runnable r) {
   Thread t = new Thread(r);
   t.setDaemon(true);
   return t;
 }
Beispiel #3
0
  @Override
  public void run() {
    try {
      preSetup();
      while (!shutdown) {
        try {
          LOGGER.debug("|| waiting for connections...\n");
          final Socket socket = serverSocket.accept();

          ConnectionHandler ch = new ConnectionHandler(socket);
          Thread t = new Thread(ch);
          t.start();
        } catch (Exception ex) {
          LOGGER.debug(ex.getLocalizedMessage(), ex);
        }
      }
    } catch (IOException ex) {
      LOGGER.debug(ex.getLocalizedMessage(), ex);
    } finally {
      try {
        if (serverSocket != null) {
          serverSocket.close();
          serverSocket = null;
        }
      } catch (IOException e) {

      }
      LOGGER.info("|| shutdown complete");
    }
  }
Beispiel #4
0
  /*
   * Primary constructor, used to drive remainder of the test.
   *
   * Fork off the other side, then do your work.
   */
  JavaxHTTPSConnection() throws Exception {
    if (separateServerThread) {
      startServer(true);
      startClient(false);
    } else {
      startClient(true);
      startServer(false);
    }

    /*
     * Wait for other side to close down.
     */
    if (separateServerThread) {
      serverThread.join();
    } else {
      clientThread.join();
    }

    /*
     * When we get here, the test is pretty much over.
     *
     * If the main thread excepted, that propagates back
     * immediately.  If the other thread threw an exception, we
     * should report back.
     */
    if (serverException != null) {
      System.out.print("Server Exception:");
      throw serverException;
    }
    if (clientException != null) {
      System.out.print("Client Exception:");
      throw clientException;
    }
  }
Beispiel #5
0
  public SSLResult fingerprint() throws IOException, FingerprintError {

    SSLConfigCollector scc;

    scc = new SSLConfigCollector(host, port, si);
    scc.setCertValidator(cv);

    startDate = new Date();

    sslSupport = SSLResult.UNKNOWN;

    // If a delay is set, wait some time, except for
    // the first request
    if (!initial && (delay > 0)) {
      if (Debug.get(Debug.Delay)) {
        System.err.println("Delaying request.");
      }
      try {
        Thread.sleep(delay);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
    initial = false;

    try {
      scc.probe();
      sslSupport = SSLResult.SUPPORTED;
      sslSupportReason = null;
    } catch (NoSSLException e) {
      // This exception is thrown when the protocol support
      // for ssl is not available
      sslSupport = SSLResult.UNSUPPORTED;
      sslSupportReason = e.toString();
    } catch (FingerprintException e) {
      sslSupport = SSLResult.UNSUPPORTED;
      sslSupportReason = e.toString();
    } catch (IOException e) {
      sslSupport = SSLResult.UNKNOWN;
      sslSupportReason = e.toString();
    }
    endDate = new Date();

    protos = scc.getSupportedProtos();

    ProbeResult pres =
        new ProbeResult(
            host,
            port,
            startDate,
            endDate,
            sslSupport,
            sslSupportReason,
            scc.getServerCertificates(),
            scc.serverCertificateVerifies(),
            scc.serverCertNameMatch());

    pres.setProtosResult(protos);
    return pres;
  }
Beispiel #6
0
 void startServer(boolean newThread) throws Exception {
   if (newThread) {
     serverThread =
         new Thread() {
           public void run() {
             try {
               doServerSide();
             } catch (Exception e) {
               /*
                * Our server thread just died.
                *
                * Release the client, if not active already...
                */
               System.err.println("Server died...");
               System.err.println(e);
               serverReady = true;
               serverException = e;
             }
           }
         };
     serverThread.start();
   } else {
     doServerSide();
   }
 }
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort);

    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    for (int i = 0; i < 10; i++) {
      sslOS.write(280);
      sslOS.flush();
      sslIS.read();
    }

    for (int i = 0; i < 10; i++) {
      sslOS.write(280);
      sslOS.flush();
      sslIS.read();
    }

    sslSocket.close();
  }
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    // Send HTTP POST request to server
    URL url = new URL("https://localhost:" + serverPort);

    HttpsURLConnection.setDefaultHostnameVerifier(new NameVerifier());
    HttpsURLConnection http = (HttpsURLConnection) url.openConnection();
    http.setDoOutput(true);

    http.setRequestMethod("POST");
    PrintStream ps = new PrintStream(http.getOutputStream());
    try {
      ps.println(postMsg);
      ps.flush();
      if (http.getResponseCode() != 200) {
        throw new RuntimeException("test Failed");
      }
    } finally {
      ps.close();
      http.disconnect();
      closeReady = true;
    }
  }
Beispiel #9
0
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {
    // create SSLEngine.
    SSLEngine ssle = createSSLEngine(true);

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    // Create a non-blocking socket channel.
    SocketChannel sc = SocketChannel.open();
    sc.configureBlocking(false);
    InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), serverPort);
    sc.connect(isa);

    // Complete connection.
    while (!sc.finishConnect()) {
      // waiting for the connection completed.
    }

    // handshaking
    handshaking(ssle, sc, null);

    // send out application data
    deliver(ssle, sc);

    // receive application data
    receive(ssle, sc);

    // close the socket channel.
    sc.close();
  }
  /*
   * Primary constructor, used to drive remainder of the test.
   *
   * Fork off the other side, then do your work.
   */
  InvalidateServerSessionRenegotiate() throws Exception {
    if (separateServerThread) {
      startServer(true);
      startClient(false);
    } else {
      startClient(true);
      startServer(false);
    }

    /*
     * Wait for other side to close down.
     */
    if (separateServerThread) {
      serverThread.join();
    } else {
      clientThread.join();
    }

    /*
     * When we get here, the test is pretty much over.
     *
     * If the main thread excepted, that propagates back
     * immediately.  If the other thread threw an exception, we
     * should report back.
     */
    if (serverException != null) {
      System.out.print("Server Exception:");
      throw serverException;
    }
    if (clientException != null) {
      System.out.print("Client Exception:");
      throw clientException;
    }

    /*
     * Give the Handshaker Thread a chance to run
     */
    Thread.sleep(1000);

    synchronized (this) {
      if (handshakesCompleted != 2) {
        throw new Exception("Didn't see 2 handshake completed events.");
      }
    }
  }
  void requestAccountList() {
    prog =
        ProgressDialog.show(
            this,
            null,
            getString(R.string.account_list_progress),
            false,
            true,
            new DialogInterface.OnCancelListener() {
              public void onCancel(DialogInterface dialog) {
                cancel();
              }
            });

    queryThread = new Thread(this, "Requestor Thread");
    queryThread.setDaemon(true);
    queryThread.start();
  }
Beispiel #12
0
  public static void main(PeerFactory peerFactory, KeyStore keyStore, String[] args)
      throws Exception {

    long time = System.currentTimeMillis();
    String relPath;
    if ((args != null) && (args.length > 0) && args[0].equals("sh")) {
      relPath = pathToStoresSH;
    } else {
      relPath = pathToStores;
    }
    PATH = new File(System.getProperty("test.src", "."), relPath);
    CipherTest.peerFactory = peerFactory;
    System.out.print("Initializing test '" + peerFactory.getName() + "'...");
    //      secureRandom = new SecureRandom();
    //      secureRandom.nextInt();
    //      trustStore = readKeyStore(trustStoreFile);
    CipherTest.keyStore = keyStore;
    //      keyStore = readKeyStore(keyStoreFile);
    KeyManagerFactory keyFactory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyFactory.init(keyStore, "test12".toCharArray());
    keyManager = (X509ExtendedKeyManager) keyFactory.getKeyManagers()[0];

    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    trustManager = (X509TrustManager) tmf.getTrustManagers()[0];

    //      trustManager = new AlwaysTrustManager();
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager}, null);
    SSLContext.setDefault(context);

    CipherTest cipherTest = new CipherTest(peerFactory);
    Thread serverThread = new Thread(peerFactory.newServer(cipherTest), "Server");
    serverThread.setDaemon(true);
    serverThread.start();
    System.out.println("Done");
    cipherTest.run();
    time = System.currentTimeMillis() - time;
    System.out.println("Done. (" + time + " ms)");
  }
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    /*
     * See if an unknown keystore actually gets checked ok.
     */
    System.out.println("==============");
    System.out.println("Starting test0");
    KeyStore uks = KeyStore.getInstance("JKS");
    SSLContext ctx = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

    uks.load(new FileInputStream(unknownFilename), cpasswd);
    kmf.init(uks, cpasswd);

    TrustManager[] tms = new TrustManager[] {new MyJavaxX509TrustManager()};

    ctx.init(kmf.getKeyManagers(), tms, null);

    SSLSocketFactory sslsf = (SSLSocketFactory) ctx.getSocketFactory();

    System.out.println("Trying first socket " + serverPort);
    SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort);

    doTest(sslSocket);

    /*
     * Now try the other way.
     */
    com.sun.net.ssl.SSLContext ctx1 = com.sun.net.ssl.SSLContext.getInstance("TLS");
    com.sun.net.ssl.KeyManagerFactory kmf1 =
        com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");
    kmf1.init(uks, cpasswd);

    com.sun.net.ssl.TrustManager[] tms1 =
        new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()};

    ctx1.init(kmf1.getKeyManagers(), tms1, null);

    sslsf = (SSLSocketFactory) ctx1.getSocketFactory();

    System.out.println("Trying second socket " + serverPort1);
    sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort1);

    doTest(sslSocket);
    System.out.println("Completed test1");
  }
Beispiel #14
0
  public static void main(String[] args) throws Exception {

    if (args.length == 5 && args[4].equalsIgnoreCase("BC")) {
      Security.removeProvider("SunPKCS11-NSS");
      Security.removeProvider("SunEC");
      Security.insertProviderAt(new BouncyCastleProvider(), 1);
      System.out.println("Using BC provider");
    }
    for (Provider p : Security.getProviders()) {
      System.out.println(p);
    }
    System.setProperty("java.security.debug", "ssl");
    String path;
    String password;
    String protocol;
    int port;

    if (args.length == 4 || args.length == 5) {
      path = args[0];
      password = args[1];
      protocol = args[2];
      port = Integer.parseInt(args[3]);
    } else if (args.length == 0) {
      path = PATH_TO_JKS;
      password = JKS_PASSWORD;
      protocol = PROTOCOL;
      port = PORT;
    } else {
      System.out.println(
          "Usage (run with): java -jar [name].jar [jks-path] "
              + "[password] [protocol] [port] \n (set [protocol] to TLS)");
      return;
    }

    KeyStore keyStore = readKeyStore(path, password);
    TLSServer server = new TLSServer(keyStore, password, protocol, port);
    Thread t = new Thread(server);
    t.start();
  }
  private static TrustManager[] createTrustManagers() throws GeneralSecurityException, IOException {
    InputStream keyStoreStream =
        Thread.currentThread().getContextClassLoader().getResourceAsStream("ssltest-keystore.jks");
    char[] keyStorePassword = "******".toCharArray();
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(keyStoreStream, keyStorePassword);
    assert (ks.size() > 0);

    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    return tmf.getTrustManagers();
  }
  private static KeyManager[] createKeyManagers() throws GeneralSecurityException, IOException {
    InputStream keyStoreStream =
        Thread.currentThread().getContextClassLoader().getResourceAsStream("ssltest-cacerts.jks");
    char[] keyStorePassword = "******".toCharArray();
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(keyStoreStream, keyStorePassword);
    assert (ks.size() > 0);

    // Set up key manager factory to use our key store
    char[] certificatePassword = "******".toCharArray();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, certificatePassword);

    // Initialize the SSLContext to work with our key managers.
    return kmf.getKeyManagers();
  }
  public static File getClasspathFile(String file) throws FileNotFoundException {
    ClassLoader cl = null;
    try {
      cl = Thread.currentThread().getContextClassLoader();
    } catch (Throwable ex) {
    }
    if (cl == null) {
      cl = TestUtils.class.getClassLoader();
    }
    URL resourceUrl = cl.getResource(file);

    try {
      return new File(new URI(resourceUrl.toString()).getSchemeSpecificPart());
    } catch (URISyntaxException e) {
      throw new FileNotFoundException(file);
    }
  }
Beispiel #18
0
 void startClient(boolean newThread) throws Exception {
   if (newThread) {
     clientThread =
         new Thread() {
           public void run() {
             try {
               doClientSide();
             } catch (Exception e) {
               /*
                * Our client thread just died.
                */
               System.err.println("Client died...");
               clientException = e;
             }
           }
         };
     clientThread.start();
   } else {
     doClientSide();
   }
 }
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);
    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    try {
      InputStream sslIS = sslSocket.getInputStream();
      OutputStream sslOS = sslSocket.getOutputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(sslIS));
      PrintStream ps = new PrintStream(sslOS);

      // process HTTP POST request from client
      System.out.println("status line: " + br.readLine());
      String msg = null;
      while ((msg = br.readLine()) != null && msg.length() > 0) ;

      msg = br.readLine();
      if (msg.equals(postMsg)) {
        ps.println("HTTP/1.1 200 OK\n\n");
      } else {
        ps.println("HTTP/1.1 500 Not OK\n\n");
      }
      ps.flush();

      // close the socket
      while (!closeReady) {
        Thread.sleep(50);
      }
    } finally {
      sslSocket.close();
      sslServerSocket.close();
    }
  }
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {
    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    HttpsURLConnection.setDefaultHostnameVerifier(new NameVerifier());

    URL url = new URL("https://" + "localhost:" + serverPort + "/etc/hosts");
    URLConnection urlc = url.openConnection();

    if (!(urlc instanceof com.sun.net.ssl.HttpsURLConnection)) {
      throw new Exception("URLConnection ! instanceof " + "com.sun.net.ssl.HttpsURLConnection");
    }

    BufferedReader in = null;
    try {
      in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
      String inputLine;
      System.out.print("Client reading... ");
      while ((inputLine = in.readLine()) != null) System.out.println(inputLine);

      System.out.println("Cipher Suite: " + ((HttpsURLConnection) urlc).getCipherSuite());
      X509Certificate[] certs = ((HttpsURLConnection) urlc).getServerCertificateChain();
      for (int i = 0; i < certs.length; i++) {
        System.out.println(certs[0]);
      }

      in.close();
    } catch (SSLException e) {
      if (in != null) in.close();
      throw e;
    }
    System.out.println("Client reports:  SUCCESS");
  }
 private void handshake() throws IOException {
   if (handshakeCompleted) {
     return;
   }
   if (DEBUG) {
     log("Starting handshake...");
   }
   synchronized (this) {
     if (handshakeCompleted) {
       if (DEBUG) {
         log("Handshake already completed...");
       }
       return;
     }
     int counter = 0;
     if (DEBUG) {
       log("Begin handshake");
     }
     sslEngine.beginHandshake();
     writeInternal(emptyBuffer);
     while (counter++ < 250
         && sslEngineResult.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.FINISHED) {
       if (DEBUG) {
         log("Handshake status: " + sslEngineResult.getHandshakeStatus());
       }
       if (sslEngineResult.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
         if (DEBUG) {
           log("Begin UNWRAP");
         }
         netInBuffer.clear();
         while (socketChannel.read(netInBuffer) < 1) {
           try {
             if (DEBUG) {
               log("Spinning on channel read...");
             }
             Thread.sleep(50);
           } catch (InterruptedException e) {
             throw new IOException(e);
           }
         }
         netInBuffer.flip();
         unwrap(netInBuffer);
         if (DEBUG) {
           log("Done UNWRAP: " + sslEngineResult.getHandshakeStatus());
         }
         if (sslEngineResult.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.FINISHED) {
           emptyBuffer.clear();
           writeInternal(emptyBuffer);
           if (DEBUG) {
             log("Done WRAP after UNWRAP: " + sslEngineResult.getHandshakeStatus());
           }
         }
       } else if (sslEngineResult.getHandshakeStatus()
           == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
         if (DEBUG) {
           log("Begin WRAP");
         }
         emptyBuffer.clear();
         writeInternal(emptyBuffer);
         if (DEBUG) {
           log("Done WRAP: " + sslEngineResult.getHandshakeStatus());
         }
       } else {
         try {
           if (DEBUG) {
             log("Sleeping... Status: " + sslEngineResult.getHandshakeStatus());
           }
           Thread.sleep(500);
         } catch (InterruptedException e) {
           throw new IOException(e);
         }
       }
     }
     if (sslEngineResult.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.FINISHED) {
       throw new SSLHandshakeException(
           "SSL handshake failed after "
               + counter
               + " trials! -> "
               + sslEngineResult.getHandshakeStatus());
     }
     if (DEBUG) {
       log("Handshake completed!");
     }
     in.clear();
     in.flip();
     handshakeCompleted = true;
   }
 }
Beispiel #22
0
 public Thread newThread(Runnable r) {
   Thread t = DEFAULT.newThread(r);
   t.setDaemon(true);
   return t;
 }
  @Override
  public void run() {
    _init();
    Thread thread = Thread.currentThread();
    thread.setName("ExcellerisController" + "[" + thread.getId() + "]");

    logger.debug("Running [" + thread.getName() + "]");

    Node rootTag = null;
    String messageCount = null;
    String messageFormat = null;
    String messageVersion = null;
    // NamedNodeMap nodemap = null;
    // Document response = null;
    // Node code = null;
    String ackReturnCode = null;
    setLastFileCount(0);

    if (hostLogin()) {

      try {
        // fetch data
        logger.info("Fetching Excelleris labs from " + FETCH);
        getLabConnection().fetch(FETCH);
      } catch (SocketTimeoutException e) {
        handleError(
            "Connection timeout occured while attempting to fetch lab files. Check internet connectivity. ",
            e,
            ERROR);
      } catch (IOException e) {
        handleError("Expedius has failed to fetch lab files. Contact support. ", e, ERROR);
      } /*catch (ParserConfigurationException e) {
        	handleError("There was a problem with parsing the server response while fetching lab files.", e, ERROR);
        }  */ finally {
        // for maintenance.
        close();
      }

      // save data
      if (getLabConnection().getResponseCode() == HttpsURLConnection.HTTP_OK) {

        if (getLabConnection().hasResponse()) {

          rootTag = getDocumentHandler().getRoot();

          if (NODE_HL7MESSAGES.equalsIgnoreCase(rootTag.getNodeName())) {
            messageCount = getDocumentHandler().getNodeAttributeValue(NODE_MESSAGECOUNT, rootTag);
            messageFormat = getDocumentHandler().getNodeAttributeValue(NODE_MESSAGEFORMAT, rootTag);
            messageVersion = getDocumentHandler().getNodeAttributeValue(NODE_VERSION, rootTag);

            logger.info(NODE_MESSAGECOUNT + ": " + messageCount);
            logger.info(NODE_MESSAGEFORMAT + ": " + messageFormat);
            logger.info(NODE_VERSION + ": " + messageVersion);
          }
        }

        if (getLastFileCount() > 0) {
          getLabHandler().setLabType(EXCELLERIS_LAB_TYPE);
          super.processResults(getDocumentHandler().getDocument(), labType);
        }
      }

      //						response = getLabConnection().getResponse();
      //						rootTag = response.getDocumentElement();
      //
      //						if(rootTag.getNodeName().equalsIgnoreCase(NODE_HL7MESSAGES)) {
      //
      //							nodemap = rootTag.getAttributes();
      //
      //							if(nodemap.getLength() > 0) {
      //
      //								messageCount = nodemap.getNamedItem(NODE_MESSAGECOUNT).getNodeValue();
      //								messageFormat = nodemap.getNamedItem(NODE_MESSAGEFORMAT).getNodeValue();
      //								messageVersion = nodemap.getNamedItem(NODE_VERSION).getNodeValue();
      //
      //								logger.info(NODE_MESSAGECOUNT + ": " + messageCount);
      //								logger.info(NODE_MESSAGEFORMAT + ": " + messageFormat);
      //								logger.info(NODE_VERSION + ": " + messageVersion);
      //
      //								if(messageCount != null) {
      //									setLastFileCount(Integer.parseInt(messageCount));
      //									logger.info( messageCount + " Excelleris labs downloaded");
      //								}
      //
      //							}
      //
      //						} else {
      //							logger.error("Error: No, or incorrect, content from server. Root Tag:
      // "+rootTag.toString());
      //						}
      //					}

      // }

      // CAUTION - disable acknowledge for testing. You will loose all your test labs.
      if ((ACKNOWLEDGE_DOWNLOADS.equalsIgnoreCase("true"))
          && (getLabHandler().getResponseCode() == HttpsURLConnection.HTTP_OK)) {
        try {
          getLabConnection().acknowledge(ACKNOWLEDGE);
        } catch (SocketTimeoutException e) {
          handleError(
              "Connection timeout occured while attempting to fetch lab files. Check internet connectivity. ",
              e,
              ERROR);
        } catch (IOException e) {
          handleError("Expedius has failed to fetch lab files. Contact support. ", e, ERROR);
        }

        if (getLabConnection().hasResponse()) {

          ackReturnCode =
              getDocumentHandler()
                  .getNodeAttributeValue(NODE_RETURNCODE, getDocumentHandler().getRoot());

          if (ACK_RETURN_CODE.equalsIgnoreCase(ackReturnCode)) {
            logger.info("All Labs Acknowledged: " + ackReturnCode);
          } else {
            handleError(
                "Expedius has failed to acknowledge the last lab download. "
                    + "This could result in multiple copies of the same lab. Excelleris server acknowledge return code was "
                    + ackReturnCode
                    + "If this error does not resolve in 24 hours, contact support.",
                null,
                DISMISSABLE_ERROR);
          }
        }
      }
      //
      //							rootTag = getLabConnection().getResponse().getDocumentElement();
      //							nodemap = rootTag.getAttributes();
      //
      //							if(nodemap.getLength() > 0) {
      //
      //								code = nodemap.getNamedItem(NODE_RETURNCODE);
      //
      //								if(Integer.parseInt(code.getNodeValue().toString()) == 0) {
      //
      //								} else {
      //									logger.error(rootTag.toString() + " Invalid response code");
      //								}
      //
      //							} else {
      //
      //							}
      //						}
      //
      //					} else {
      //
      //					}
      //
      //				} else {
      //					logger.info("Acknowledge not enabled. This lab file will be downloaded again.");
      //				}

      // catch all server response codes.
      processServerResponse(getLabConnection().getResponseCode());

      //			} catch (SocketTimeoutException e) {
      //				handleError("Connection timeout occured while attempting to fetch lab files. Check
      // internet connectivity. ", e, ERROR);
      //			} catch (IOException e) {
      //				handleError("Expedius has failed to fetch lab files. Contact support. ", e, ERROR);
      //			} catch (ParserConfigurationException e) {
      //				handleError("There was a problem with parsing the server response while fetching lab
      // files.", e, ERROR);
      //			}  finally {
      //				close();
      //			}
    }
  }
  public void runSupport() {

    try {
      new URL(url_str); // determine if this is already a proper URL
    } catch (Throwable t) { // it's not

      //  			//check if the string is just a base32/hex-encoded torrent infohash
      //
      //  		String magnet_uri = UrlUtils.normaliseMagnetURI( url_str );
      //
      //  		if ( magnet_uri != null ){
      //
      //  			url_str = magnet_uri;
      //  		}
    }

    try {
      url = AddressUtils.adjustURL(new URL(url_str));

      String protocol = url.getProtocol().toLowerCase();

      // hack here - the magnet download process requires an additional paramter to cause it to
      // stall on error so the error can be reported

      //    	if ( protocol.equals( "magnet" ) || protocol.equals( "dht" )){
      //
      //    		url = AddressUtils.adjustURL( new URL(url_str+"&pause_on_error=true"));
      //    	}

      for (int i = 0; i < 2; i++) {
        try {

          //	      if ( protocol.equals("https")){
          //
          //	      	// see ConfigurationChecker for SSL client defaults
          //
          //	      	HttpsURLConnection ssl_con = (HttpsURLConnection)url.openConnection();
          //
          //	      	// allow for certs that contain IP addresses rather than dns names
          //
          //	      	ssl_con.setHostnameVerifier(
          //	      			new HostnameVerifier()
          //	      			{
          //	      				public boolean
          //	      				verify(
          //	      					String		host,
          //							SSLSession	session )
          //	      				{
          //	      					return( true );
          //	      				}
          //	      			});
          //
          //	      	con = ssl_con;
          //
          //	      }else{
          //
          con = (HttpURLConnection) url.openConnection();

          //	      }

          con.setRequestProperty(
              "User-Agent", Constants.AZUREUS_NAME + " " + Constants.AZUREUS_VERSION);

          if (referrer != null && referrer.length() > 0) {

            con.setRequestProperty("Referer", referrer);
          }

          if (request_properties != null) {

            Iterator it = request_properties.entrySet().iterator();

            while (it.hasNext()) {

              Map.Entry entry = (Map.Entry) it.next();

              String key = (String) entry.getKey();
              String value = (String) entry.getValue();

              // currently this code doesn't support gzip/deflate...

              if (!key.equalsIgnoreCase("Accept-Encoding")) {

                con.setRequestProperty(key, value);
              }
            }
          }

          this.con.connect();

          break;

          //      	}catch( SSLException e ){
          //
          //      		if ( i == 0 ){
          //
          //      			if ( SESecurityManager.installServerCertificates( url ) != null ){
          //
          //      				// certificate has been installed
          //
          //      				continue;	// retry with new certificate
          //      			}
          //      		}
          //
          //      		throw( e );
          //
        } catch (IOException e) {

          if (i == 0) {

            URL retry_url = UrlUtils.getIPV4Fallback(url);

            if (retry_url != null) {

              url = retry_url;

            } else {

              throw (e);
            }
          }
        }
      }

      int response = this.con.getResponseCode();
      if (!ignoreReponseCode) {
        if ((response != HttpURLConnection.HTTP_ACCEPTED)
            && (response != HttpURLConnection.HTTP_OK)) {
          this.error(response, Integer.toString(response) + ": " + this.con.getResponseMessage());
          return;
        }
      }

      /*
           Map headerFields = this.con.getHeaderFields();

           System.out.println("Header of download of " + url_str);
           for (Iterator iter = headerFields.keySet().iterator(); iter.hasNext();) {
      			String s = (String) iter.next();
      			System.out.println(s + ":" + headerFields.get(s));

      		}
      */
      filename = this.con.getHeaderField("Content-Disposition");
      if ((filename != null)
          && filename
              .toLowerCase()
              .matches(".*attachment.*")) // Some code to handle b0rked servers.
      while (filename.toLowerCase().charAt(0) != 'a') filename = filename.substring(1);
      if ((filename == null)
          || !filename.toLowerCase().startsWith("attachment")
          || (filename.indexOf('=') == -1)) {
        String tmp = this.url.getFile();
        if (tmp.length() == 0 || tmp.equals("/")) {
          filename = url.getHost();
        } else if (tmp.startsWith("?")) {

          // probably a magnet URI - use the hash
          // magnet:?xt=urn:sha1:VGC53ZWCUXUWVGX7LQPVZIYF4L6RXSU6

          String query = tmp.toUpperCase();

          int pos = query.indexOf("XT=URN:SHA1:");

          if (pos == -1) {

            pos = query.indexOf("XT=URN:BTIH:");
          }

          if (pos != -1) {

            pos += 12;

            int p2 = query.indexOf("&", pos);

            if (p2 == -1) {

              filename = query.substring(pos);

            } else {

              filename = query.substring(pos, p2);
            }
          } else {

            filename = "Torrent" + (long) (Math.random() * Long.MAX_VALUE);
          }

          filename += ".tmp";

        } else {
          if (tmp.lastIndexOf('/') != -1) tmp = tmp.substring(tmp.lastIndexOf('/') + 1);

          // remove any params in the url

          int param_pos = tmp.indexOf('?');

          if (param_pos != -1) {
            tmp = tmp.substring(0, param_pos);
          }

          filename = URLDecoder.decode(tmp, Constants.DEFAULT_ENCODING);
        }
      } else {
        filename = filename.substring(filename.indexOf('=') + 1);
        if (filename.startsWith("\"") && filename.endsWith("\""))
          filename = filename.substring(1, filename.lastIndexOf('\"'));

        filename = URLDecoder.decode(filename, Constants.DEFAULT_ENCODING);

        // not sure of this piece of logic here but I'm not changing it at the moment

        File temp = new File(filename);
        filename = temp.getName();
      }

      filename = FileUtil.convertOSSpecificChars(filename, false);

      //      directoryname =
      // COConfigurationManager.getDirectoryParameter("General_sDefaultTorrent_Directory");
      //      boolean useTorrentSave = COConfigurationManager.getBooleanParameter("Save Torrent
      // Files");
      directoryname = "D:\\Development\\testDownloads\\";
      boolean useTorrentSave = true;
      if (file_str != null) {
        // not completely sure about the whole logic in this block
        File temp = new File(file_str);

        // if we're not using a default torrent save dir
        if (!useTorrentSave || directoryname.length() == 0) {
          // if it's already a dir
          if (temp.isDirectory()) {
            // use it
            directoryname = temp.getCanonicalPath();
          }
          // it's a file
          else {
            // so use its parent dir
            directoryname = temp.getCanonicalFile().getParent();
          }
        }

        // if it's a file
        if (!temp.isDirectory()) {
          // set the file name
          filename = temp.getName();
        }
      }
      // what would happen here if directoryname == null and file_str == null??

      this.state = STATE_INIT;
      this.notifyListener();
    } catch (java.net.MalformedURLException e) {
      this.error(0, "Exception while parsing URL '" + url + "':" + e.getMessage());
    } catch (java.net.UnknownHostException e) {
      this.error(
          0,
          "Exception while initializing download of '"
              + url
              + "': Unknown Host '"
              + e.getMessage()
              + "'");
    } catch (java.io.IOException ioe) {
      this.error(0, "I/O Exception while initializing download of '" + url + "':" + ioe.toString());
    } catch (Throwable e) {
      this.error(0, "Exception while initializing download of '" + url + "':" + e.toString());
    }

    if (this.state == STATE_ERROR) {

      return;
    }

    try {
      final boolean status_reader_run[] = {true};

      this.state = STATE_START;

      notifyListener();

      this.state = STATE_DOWNLOADING;

      notifyListener();

      Thread status_reader =
          new AEThread("TorrentDownloader:statusreader") {
            public void runSupport() {
              boolean changed_status = false;

              while (true) {

                try {
                  Thread.sleep(100);

                  try {
                    this_mon.enter();

                    if (!status_reader_run[0]) {

                      break;
                    }
                  } finally {

                    this_mon.exit();
                  }

                  String s = con.getResponseMessage();

                  if (!s.equals(getStatus())) {

                    if (!s.toLowerCase().startsWith("error:")) {

                      if (s.toLowerCase().indexOf("alive") != -1) {

                        if (percentDone < 10) {

                          percentDone++;
                        }
                      }

                      int pos = s.indexOf('%');

                      if (pos != -1) {

                        int i;

                        for (i = pos - 1; i >= 0; i--) {

                          char c = s.charAt(i);

                          if (!Character.isDigit(c) && c != ' ') {

                            i++;

                            break;
                          }
                        }

                        try {
                          percentDone = Integer.parseInt(s.substring(i, pos).trim());

                        } catch (Throwable e) {

                        }
                      }

                      setStatus(s);

                    } else {

                      error(con.getResponseCode(), s.substring(6));
                    }

                    changed_status = true;
                  }

                } catch (Throwable e) {

                  break;
                }
              }

              if (changed_status) {

                setStatus("");
              }
            }
          };

      status_reader.setDaemon(true);

      status_reader.start();

      InputStream in;

      try {
        in = this.con.getInputStream();

      } catch (FileNotFoundException e) {
        if (ignoreReponseCode) {

          in = this.con.getErrorStream();
        } else {

          throw e;
        }

      } finally {

        try {
          this_mon.enter();

          status_reader_run[0] = false;

        } finally {

          this_mon.exit();
        }
      }

      // handle some servers that return gzip'd torrents even though we don't request it!

      String encoding = con.getHeaderField("content-encoding");

      if (encoding != null) {

        if (encoding.equalsIgnoreCase("gzip")) {

          in = new GZIPInputStream(in);

        } else if (encoding.equalsIgnoreCase("deflate")) {

          in = new InflaterInputStream(in);
        }
      }

      if (this.state != STATE_ERROR) {

        this.file = new File(this.directoryname, filename);

        boolean useTempFile = false;
        try {
          this.file.createNewFile();
          useTempFile = !this.file.exists();
        } catch (Throwable t) {
          useTempFile = true;
        }

        if (useTempFile) {
          this.file = File.createTempFile("AZU", ".torrent", new File(this.directoryname));
          this.file.createNewFile();
        }

        FileOutputStream fileout = new FileOutputStream(this.file, false);

        bufBytes = 0;

        int size = (int) UrlUtils.getContentLength(con);

        this.percentDone = -1;

        do {
          if (this.cancel) {
            break;
          }

          try {
            bufBytes = in.read(buf);

            this.readTotal += bufBytes;

            if (size != 0) {
              this.percentDone = (100 * this.readTotal) / size;
            }

            notifyListener();

          } catch (IOException e) {
          }

          if (bufBytes > 0) {
            fileout.write(buf, 0, bufBytes);
          }
        } while (bufBytes > 0);

        in.close();

        fileout.flush();

        fileout.close();

        if (this.cancel) {
          this.state = STATE_CANCELLED;
          if (deleteFileOnCancel) {
            this.cleanUpFile();
          }
        } else {
          if (this.readTotal <= 0) {
            this.error(0, "No data contained in '" + this.url.toString() + "'");
            return;
          }

          // if the file has come down with a not-so-useful name then we try to rename
          // it to something more useful

          try {
            if (!filename.toLowerCase().endsWith(".torrent")) {

              TOTorrent torrent = TorrentUtils.readFromFile(file, false);

              String name = TorrentUtils.getLocalisedName(torrent) + ".torrent";

              File new_file = new File(directoryname, name);

              if (file.renameTo(new_file)) {

                filename = name;

                file = new_file;
              }
            }
          } catch (Throwable e) {

            Debug.printStackTrace(e);
          }

          //	          TorrentUtils.setObtainedFrom( file, original_url );

          this.state = STATE_FINISHED;
        }
        this.notifyListener();
      }
    } catch (Exception e) {

      if (!cancel) {

        Debug.out("'" + this.directoryname + "' '" + filename + "'", e);
      }

      this.error(0, "Exception while downloading '" + this.url.toString() + "':" + e.getMessage());
    }
  }
Beispiel #25
0
 public static StackTraceElement getCallerStackTraceElement() {
   return Thread.currentThread().getStackTrace()[4];
 }