Esempio n. 1
0
 public static void main(String[] args) {
   try {
     getConnectionParameters(args);
     getInputParameters(args);
     if (help) {
       printUsage();
       return;
     }
     connect();
     ColdMigration.coldMigration();
   } catch (IllegalArgumentException e) {
     printUsage();
   } catch (SOAPFaultException sfe) {
     printSoapFaultException(sfe);
   } catch (Exception e) {
     System.out.println("Exception encountered " + e);
     e.printStackTrace();
   } finally {
     try {
       disconnect();
     } catch (SOAPFaultException sfe) {
       printSoapFaultException(sfe);
     } catch (Exception e) {
       System.out.println("Failed to disconnect - " + e.getMessage());
       e.printStackTrace();
     }
   }
 }
Esempio n. 2
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");
    }
  }
Esempio n. 3
0
  private static char[] readResponseData(InputStream stream, String encoding) {
    BufferedReader in = null;
    char[] data = null;
    try {
      StringBuffer buf = new StringBuffer();
      data = new char[1024];

      in = new BufferedReader(new InputStreamReader(stream, encoding));
      int charsRead;
      while ((charsRead = in.read(data)) != -1) {
        buf.append(data, 0, charsRead);
      }
      data = new char[buf.length()];
      buf.getChars(0, data.length, data, 0);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        in.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return data != null ? data : null;
  }
Esempio n. 4
0
 public void run() throws Exception {
   Thread[] threads = new Thread[THREADS];
   for (int i = 0; i < THREADS; i++) {
     try {
       threads[i] = new Thread(peerFactory.newClient(this), "Client " + i);
     } catch (Exception e) {
       e.printStackTrace();
       return;
     }
     threads[i].start();
   }
   try {
     for (int i = 0; i < THREADS; i++) {
       threads[i].join();
     }
   } catch (InterruptedException e) {
     setFailed();
     e.printStackTrace();
   }
   if (failed) {
     throw new Exception("*** Test '" + peerFactory.getName() + "' failed ***");
   } else {
     System.out.println("Test '" + peerFactory.getName() + "' completed successfully");
   }
 }
Esempio n. 5
0
  /**
   * @param p_address
   * @param p_acceptQueueSize
   * @return
   * @exception IOException
   */
  protected ServerSocket newServerSocket(InetAddrPort p_address, int p_acceptQueueSize)
      throws IOException {
    SSLServerSocketFactory factory = null;
    SSLServerSocket socket = null;

    try {
      factory = createFactory();

      if (p_address == null) {
        socket = (SSLServerSocket) factory.createServerSocket(0, p_acceptQueueSize);
      } else {
        socket =
            (SSLServerSocket)
                factory.createServerSocket(
                    p_address.getPort(), p_acceptQueueSize, p_address.getInetAddress());
      }

      socket.setNeedClientAuth(_needClientAuth);
      log.info("JsseListener.needClientAuth=" + _needClientAuth);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      log.warn(LogSupport.EXCEPTION, e);
      throw new IOException("Could not create JsseListener: " + e.toString());
    }
    return socket;
  }
Esempio n. 6
0
  /**
   * @param datacenterName The name of the Datacenter
   * @return ManagedObjectReference to the Datacenter
   */
  private static ManagedObjectReference getDatacenterByName(String datacenterName) {
    ManagedObjectReference retVal = null;
    ManagedObjectReference rootFolder = serviceContent.getRootFolder();
    ManagedObjectReference propCollector = serviceContent.getPropertyCollector();
    try {
      TraversalSpec tSpec = getDatacenterTraversalSpec();
      // Create Property Spec
      PropertySpec propertySpec = new PropertySpec();
      propertySpec.setAll(Boolean.FALSE);
      propertySpec.getPathSet().add("name");
      propertySpec.setType("Datacenter");

      // Now create Object Spec
      ObjectSpec objectSpec = new ObjectSpec();
      objectSpec.setObj(rootFolder);
      objectSpec.setSkip(Boolean.TRUE);
      objectSpec.getSelectSet().add(tSpec);

      // Create PropertyFilterSpec using the PropertySpec and ObjectPec
      // created above.
      PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
      propertyFilterSpec.getPropSet().add(propertySpec);
      propertyFilterSpec.getObjectSet().add(objectSpec);

      List<PropertyFilterSpec> listpfs = new ArrayList<PropertyFilterSpec>(1);
      listpfs.add(propertyFilterSpec);
      List<ObjectContent> listobjcont = retrievePropertiesAllObjects(listpfs);

      if (listobjcont != null) {
        for (ObjectContent oc : listobjcont) {
          ManagedObjectReference mr = oc.getObj();
          String dcnm = null;
          List<DynamicProperty> dps = oc.getPropSet();
          if (dps != null) {
            // Since there is only one property PropertySpec pathset
            // this array contains only one value
            for (DynamicProperty dp : dps) {
              dcnm = (String) dp.getVal();
            }
          }
          // This is done outside of the previous for loop to break
          // out of the loop as soon as the required datacenter is found.
          if (dcnm != null && dcnm.equals(datacenterName)) {
            retVal = mr;
            break;
          }
        }
      }
    } catch (SOAPFaultException sfe) {
      printSoapFaultException(sfe);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return retVal;
  }
 protected TrustAllSslSocketFactory() {
   TrustManager[] trustAllCerts = {new DummyTrustManager()};
   SSLSocketFactory factory = null;
   try {
     SSLContext sc = SSLContext.getInstance("SSL");
     sc.init(null, trustAllCerts, new SecureRandom());
     factory = sc.getSocketFactory();
   } catch (Exception e) {
     e.printStackTrace();
   }
   this.sslSocketFactory = factory;
 }
 /**
  * Creates an "accept-all" SSLSocketFactory - ssl sockets will accept ANY certificate sent to them
  * - thus effectively just securing the communications. This could be set in a HttpsURLConnection
  * using HttpsURLConnection.setSSLSocketFactory(.....)
  *
  * @return SSLSocketFactory
  */
 public static SSLSocketFactory createSSLSocketFactory() {
   SSLSocketFactory sslsocketfactory = null;
   TrustManager[] trustAllCerts = {new DummyTrustManager()};
   try {
     SSLContext sc = SSLContext.getInstance("SSL");
     sc.init(null, trustAllCerts, new java.security.SecureRandom());
     sslsocketfactory = sc.getSocketFactory();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return sslsocketfactory;
 }
Esempio n. 9
0
 private SSLContext createEasySSLContext() {
   try {
     SSLContext e = SSLContext.getInstance("SSL");
     e.init(
         (KeyManager[]) null,
         new TrustManager[] {BaseHttpSSLSocketFactory.MyX509TrustManager.manger},
         (SecureRandom) null);
     return e;
   } catch (Exception var2) {
     var2.printStackTrace();
     return null;
   }
 }
Esempio n. 10
0
 public static String doPostOnSSL(String url, String data, Map<String, String> headers) {
   try {
     URL requestUrl = new URL(url);
     HttpURLConnection connection = createConnection(requestUrl, headers);
     if (null == connection) {
       throw new Exception("创建联接失败");
     } else {
       String result = getRequest(connection, data, ENCODING);
       return result;
     }
   } catch (Exception e) {
     throw new RuntimeException(e.getMessage());
   }
 }
Esempio n. 11
0
  /**
   * Get the MOR of the Virtual Machine by its name.
   *
   * @param vmName The name of the Virtual Machine
   * @return The Managed Object reference for this VM
   */
  private static ManagedObjectReference getVmByVMname(String vmname) {
    ManagedObjectReference retVal = null;
    try {
      TraversalSpec tSpec = getVMTraversalSpec();
      // Create Property Spec
      PropertySpec propertySpec = new PropertySpec();
      propertySpec.setAll(Boolean.FALSE);
      propertySpec.getPathSet().add("name");
      propertySpec.setType("VirtualMachine");

      // Now create Object Spec
      ObjectSpec objectSpec = new ObjectSpec();
      objectSpec.setObj(rootRef);
      objectSpec.setSkip(Boolean.TRUE);
      objectSpec.getSelectSet().add(tSpec);

      // Create PropertyFilterSpec using the PropertySpec and ObjectPec
      // created above.
      PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
      propertyFilterSpec.getPropSet().add(propertySpec);
      propertyFilterSpec.getObjectSet().add(objectSpec);

      List<PropertyFilterSpec> listpfs = new ArrayList<PropertyFilterSpec>(1);
      listpfs.add(propertyFilterSpec);
      List<ObjectContent> listobjcont = retrievePropertiesAllObjects(listpfs);

      if (listobjcont != null) {
        for (ObjectContent oc : listobjcont) {
          ManagedObjectReference mr = oc.getObj();
          String vmnm = null;
          List<DynamicProperty> dps = oc.getPropSet();
          if (dps != null) {
            for (DynamicProperty dp : dps) {
              vmnm = (String) dp.getVal();
            }
          }
          if (vmnm != null && vmnm.equals(vmname)) {
            retVal = mr;
            break;
          }
        }
      }
    } catch (SOAPFaultException sfe) {
      printSoapFaultException(sfe);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return retVal;
  }
Esempio n. 12
0
 private RegexpPool getDontProxy() {
   RegexpPool dontProxy = new RegexpPool();
   String rawList =
       (String) AccessController.doPrivileged(new GetPropertyAction("http.nonProxyHosts"));
   if (rawList != null) {
     java.util.StringTokenizer st = new java.util.StringTokenizer(rawList, "|", false);
     try {
       while (st.hasMoreTokens()) {
         dontProxy.add(st.nextToken().toLowerCase(), new Boolean(true));
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return dontProxy;
 }
Esempio n. 13
0
 private void sendExceptionMsg(int what, Exception e) {
   e.printStackTrace();
   Message msg = Message.obtain();
   msg.obj = e;
   msg.what = what;
   queryHandler.sendMessage(msg);
 }
Esempio n. 14
0
  public static int freeSpaceOnSd() {
    int freeSize = 0;

    if (hasStorage()) {
      StatFs statFs = new StatFs(Persistence.APP_FOLDER_ON_SD);

      try {
        long nBlocSize = statFs.getBlockSize();
        long nAvailaBlock = statFs.getAvailableBlocks();
        freeSize = (int) (nBlocSize * nAvailaBlock / 1024 / 1024);

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return freeSize;
  }
Esempio n. 15
0
  /*
   * 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();
    DataOutputStream out = new DataOutputStream(sslSocket.getOutputStream());

    try {
      // get path to class file from header
      DataInputStream in = new DataInputStream(sslSocket.getInputStream());
      String path = getPath(in);
      // retrieve bytecodes
      byte[] bytecodes = getBytes(path);
      // send bytecodes in response (assumes HTTP/1.0 or later)
      try {
        out.writeBytes("HTTP/1.0 200 OK\r\n");
        out.writeBytes("Content-Length: " + bytecodes.length + "\r\n");
        out.writeBytes("Content-Type: text/html\r\n\r\n");
        out.write(bytecodes);
        out.flush();
      } catch (IOException ie) {
        ie.printStackTrace();
        return;
      }

    } catch (Exception e) {
      e.printStackTrace();
      // write out error response
      out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n");
      out.writeBytes("Content-Type: text/html\r\n\r\n");
      out.flush();
    } finally {
      // close the socket
      System.out.println("Server closing socket");
      sslSocket.close();
      serverReady = false;
    }
  }
Esempio n. 16
0
    public void run() {
      try {
        URL url = new URL(protocol + "://localhost:" + port + "/test1/" + f);
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        if (urlc instanceof HttpsURLConnection) {
          HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
          urlcs.setHostnameVerifier(
              new HostnameVerifier() {
                public boolean verify(String s, SSLSession s1) {
                  return true;
                }
              });
          urlcs.setSSLSocketFactory(ctx.getSocketFactory());
        }
        byte[] buf = new byte[4096];

        if (fixedLen) {
          urlc.setRequestProperty("XFixed", "yes");
        }
        InputStream is = urlc.getInputStream();
        File temp = File.createTempFile("Test1", null);
        temp.deleteOnExit();
        OutputStream fout = new BufferedOutputStream(new FileOutputStream(temp));
        int c, count = 0;
        while ((c = is.read(buf)) != -1) {
          count += c;
          fout.write(buf, 0, c);
        }
        is.close();
        fout.close();

        if (count != size) {
          throw new RuntimeException("wrong amount of data returned");
        }
        String orig = root + "/" + f;
        compare(new File(orig), temp);
        temp.delete();
      } catch (Exception e) {
        e.printStackTrace();
        fail = true;
      }
    }
Esempio n. 17
0
 public final void run() {
   while (true) {
     TestParameters params = cipherTest.getTest();
     if (params == null) {
       // no more tests
       break;
     }
     if (params.isEnabled() == false) {
       System.out.println("Skipping disabled test " + params);
       continue;
     }
     try {
       runTest(params);
       System.out.println("Passed " + params);
     } catch (Exception e) {
       cipherTest.setFailed();
       System.out.println("** Failed " + params + "**");
       e.printStackTrace();
     }
   }
 }
Esempio n. 18
0
  private static String getRequest(HttpURLConnection connection, String data, String encoding) {
    PrintStream out = null;
    InputStream in = null;
    StringBuilder sb = new StringBuilder(1024);
    String result = "";
    try {
      connection.connect();
      out = new PrintStream(connection.getOutputStream(), false, encoding);
      out.print(data);
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      out.close();
    }

    try {
      if (200 == connection.getResponseCode()) {
        in = connection.getInputStream();
        sb.append(IOUtils.toString(in, encoding));
      } else {
        in = connection.getErrorStream();
        sb.append(IOUtils.toString(in, encoding));
      }
      result = sb.toString();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      if (null != connection) {
        connection.disconnect();
      }
    }

    return result;
  }
Esempio n. 19
0
  public static void main(String[] args) {
    System.out.println("CanModerate Client Tools 1.0");

    try {

      System.out.println("version: " + CanModerateService.getVersion().version);
      System.out.println("server date: " + CanModerateService.getVersion().date);
      System.out.println("--------");
      System.out.println("Open connection with Oauth keys");
      RefreshTokenRequest refreshTokenRequest = new RefreshTokenRequest();
      // fill outh parameters
      refreshTokenRequest.grant_type = "refresh_token";
      refreshTokenRequest.client_id = "BBRALWUMGRRTNZIEQRWOQFET";
      refreshTokenRequest.client_secret = "432526176353";
      refreshTokenRequest.refresh_token = "84d0a86d-2354-416f-a249-e5451848b643";
      RefreshTokenResponse refreshTokenResponse =
          CanModerateService.refreshToken(refreshTokenRequest);

      System.out.println("Access token: " + refreshTokenResponse.access_token);

      MessageRequest message = new MessageRequest();
      message.clientIp = "10.0.0.1";
      message.trackingId = UUID.randomUUID().toString();

      message.message = "test message";

      MessageResponse messageResponse =
          CanModerateService.validateMessage(refreshTokenResponse.access_token, message);
      System.out.println("Response trackingId: " + messageResponse.trackingId);
      for (MessageResult result : messageResponse.results) {
        System.out.println("Result: " + result.result + " type: " + result.vcType);
      }

    } catch (Exception e) {
      System.out.print("Error: ");
      System.out.println(e.getMessage());
    }
  }
Esempio n. 20
0
  /*
  If you don't specify a trust store, and you haven't set system properties, the system will try to use either a file
  called jsssecacerts or cacerts in the JDK/JRE security directory.
  You can override this by specifying the javax.echo.ssl.trustStore system property

  If you don't specify a key store, and don't specify a system property no key store will be used
  You can override this by specifying the javax.echo.ssl.keyStore system property
   */
  public SSLContext createContext(
      VertxInternal vertx,
      final String ksPath,
      final String ksPassword,
      final String tsPath,
      final String tsPassword,
      final boolean trustAll) {
    try {
      SSLContext context = SSLContext.getInstance("TLS");
      KeyManager[] keyMgrs = ksPath == null ? null : getKeyMgrs(vertx, ksPath, ksPassword);
      TrustManager[] trustMgrs;
      if (trustAll) {
        trustMgrs = new TrustManager[] {createTrustAllTrustManager()};
      } else {
        trustMgrs = tsPath == null ? null : getTrustMgrs(vertx, tsPath, tsPassword);
      }
      context.init(keyMgrs, trustMgrs, new SecureRandom());
      return context;
    } catch (Exception e) {
      // TODO better logging
      log.error("Failed to create context", e);
      throw new RuntimeException(e.getMessage());
    }
  }
Esempio n. 21
0
  /**
   * Uses the new RetrievePropertiesEx method to emulate the now deprecated RetrieveProperties
   * method.
   *
   * @param listpfs
   * @return list of object content
   * @throws Exception
   */
  private static List<ObjectContent> retrievePropertiesAllObjects(List<PropertyFilterSpec> listpfs)
      throws Exception {

    RetrieveOptions propObjectRetrieveOpts = new RetrieveOptions();

    List<ObjectContent> listobjcontent = new ArrayList<ObjectContent>();

    try {
      RetrieveResult rslts =
          vimPort.retrievePropertiesEx(propCollectorRef, listpfs, propObjectRetrieveOpts);
      if (rslts != null && rslts.getObjects() != null && !rslts.getObjects().isEmpty()) {
        listobjcontent.addAll(rslts.getObjects());
      }
      String token = null;
      if (rslts != null && rslts.getToken() != null) {
        token = rslts.getToken();
      }
      while (token != null && !token.isEmpty()) {
        rslts = vimPort.continueRetrievePropertiesEx(propCollectorRef, token);
        token = null;
        if (rslts != null) {
          token = rslts.getToken();
          if (rslts.getObjects() != null && !rslts.getObjects().isEmpty()) {
            listobjcontent.addAll(rslts.getObjects());
          }
        }
      }
    } catch (SOAPFaultException sfe) {
      printSoapFaultException(sfe);
    } catch (Exception e) {
      System.out.println(" : Failed Getting Contents");
      e.printStackTrace();
    }

    return listobjcontent;
  }
Esempio n. 22
0
        private void doRetryableAlert(Exception e, String msg) {
          AlertDialog.Builder dialog = new AlertDialog.Builder(SelectAccount.this);
          dialog.setTitle(msg);
          String dispMsg = msg + "\n\n" + e.getMessage();
          dialog.setMessage(dispMsg);
          dialog.setPositiveButton(
              "Retry",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  requestAccountList();
                }
              });
          dialog.setNegativeButton("Cancel", emptyClickListener);

          AlertDialog dlg = dialog.create();
          dlg.show();
        }
Esempio n. 23
0
  /*
   * The previous caller failed for some reason, report back the
   * Exception.  We won't worry about Error's.
   *
   * Locked by SSLEngine.this.
   */
  void checkThrown() throws SSLException {
    synchronized (thrownLock) {
      if (thrown != null) {

        String msg = thrown.getMessage();

        if (msg == null) {
          msg = "Delegated task threw Exception/Error";
        }

        /*
         * See what the underlying type of exception is.  We should
         * throw the same thing.  Chain thrown to the new exception.
         */
        Exception e = thrown;
        thrown = null;

        if (e instanceof RuntimeException) {
          throw (RuntimeException) new RuntimeException(msg).initCause(e);
        } else if (e instanceof SSLHandshakeException) {
          throw (SSLHandshakeException) new SSLHandshakeException(msg).initCause(e);
        } else if (e instanceof SSLKeyException) {
          throw (SSLKeyException) new SSLKeyException(msg).initCause(e);
        } else if (e instanceof SSLPeerUnverifiedException) {
          throw (SSLPeerUnverifiedException) new SSLPeerUnverifiedException(msg).initCause(e);
        } else if (e instanceof SSLProtocolException) {
          throw (SSLProtocolException) new SSLProtocolException(msg).initCause(e);
        } else {
          /*
           * If it's SSLException or any other Exception,
           * we'll wrap it in an SSLException.
           */
          throw (SSLException) new SSLException(msg).initCause(e);
        }
      }
    }
  }
Esempio n. 24
0
  public String checkVAPIConnection(String url, boolean requireAuth, String user, String password)
      throws Exception {

    String textOut = null;
    try {

      System.out.println("Trying to connect with vManager vAPI " + url);
      String input = "{}";

      String apiURL = url + "/rest/sessions/count";

      HttpURLConnection conn =
          getVAPIConnection(
              apiURL, requireAuth, user, password, "POST", false, "", 0, null, null, 0, 0, false);
      OutputStream os = null;
      try {
        os = conn.getOutputStream();
      } catch (java.net.UnknownHostException e) {

        throw new Exception("Failed to connect to host " + e.getMessage() + ".  Host is unknown.");
      }
      os.write(input.getBytes());
      os.flush();

      if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        String reason = "";
        if (conn.getResponseCode() == 503)
          reason = "vAPI process failed to connect to remote vManager server.";
        if (conn.getResponseCode() == 401) reason = "Authentication Error";
        if (conn.getResponseCode() == 412)
          reason = "vAPI requires vManager 'Integration Server' license.";
        String errorMessage =
            "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")";

        return errorMessage;
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      StringBuilder result = new StringBuilder();
      String output;

      while ((output = br.readLine()) != null) {
        result.append(output);
      }

      conn.disconnect();

      JSONObject tmp = JSONObject.fromObject(result.toString());

      textOut =
          " The current number of sessions held on this vManager server are: "
              + tmp.getString("count");

    } catch (Exception e) {

      String errorMessage = "Failed : HTTP error: " + e.getMessage();

      if (e.getMessage().indexOf("Unexpected end of file from server") > -1) {
        errorMessage =
            errorMessage
                + " (from Incisive 14.2 onward the connection is secured.  Verify your url is https://)";
      }

      System.out.println(errorMessage);
      textOut = errorMessage;
    }

    return textOut;
  }
  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());
    }
  }
Esempio n. 26
0
  /**
   * Wait for values.
   *
   * @param objmor the object mor
   * @param filterProps the filter props
   * @param endWaitProps the end wait props
   * @param expectedVals the expected vals
   * @return the object[]
   * @throws RemoteException the remote exception
   * @throws Exception the exception
   */
  private static Object[] waitForValues(
      ManagedObjectReference objmor,
      String[] filterProps,
      String[] endWaitProps,
      Object[][] expectedVals)
      throws RemoteException, Exception {
    // version string is initially null
    String version = "";
    Object[] endVals = new Object[endWaitProps.length];
    Object[] filterVals = new Object[filterProps.length];

    PropertyFilterSpec spec = new PropertyFilterSpec();

    spec.getObjectSet().add(new ObjectSpec());

    spec.getObjectSet().get(0).setObj(objmor);

    spec.getPropSet().addAll(Arrays.asList(new PropertySpec[] {new PropertySpec()}));

    spec.getPropSet().get(0).getPathSet().addAll(Arrays.asList(filterProps));

    spec.getPropSet().get(0).setType(objmor.getType());

    spec.getObjectSet().get(0).setSkip(Boolean.FALSE);

    ManagedObjectReference filterSpecRef = vimPort.createFilter(propCollectorRef, spec, true);

    boolean reached = false;

    UpdateSet updateset = null;
    PropertyFilterUpdate[] filtupary = null;
    PropertyFilterUpdate filtup = null;
    ObjectUpdate[] objupary = null;
    ObjectUpdate objup = null;
    PropertyChange[] propchgary = null;
    PropertyChange propchg = null;
    while (!reached) {
      boolean retry = true;
      while (retry) {
        try {
          updateset = vimPort.waitForUpdates(propCollectorRef, version);
          retry = false;
        } catch (SOAPFaultException sfe) {
          printSoapFaultException(sfe);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (updateset != null) {
        version = updateset.getVersion();
      }
      if (updateset == null || updateset.getFilterSet() == null) {
        continue;
      }
      List<PropertyFilterUpdate> listprfup = updateset.getFilterSet();
      filtupary = listprfup.toArray(new PropertyFilterUpdate[listprfup.size()]);
      filtup = null;
      for (int fi = 0; fi < filtupary.length; fi++) {
        filtup = filtupary[fi];
        List<ObjectUpdate> listobjup = filtup.getObjectSet();
        objupary = listobjup.toArray(new ObjectUpdate[listobjup.size()]);
        objup = null;
        propchgary = null;
        for (int oi = 0; oi < objupary.length; oi++) {
          objup = objupary[oi];
          if (objup.getKind() == ObjectUpdateKind.MODIFY
              || objup.getKind() == ObjectUpdateKind.ENTER
              || objup.getKind() == ObjectUpdateKind.LEAVE) {
            List<PropertyChange> listchset = objup.getChangeSet();
            propchgary = listchset.toArray(new PropertyChange[listchset.size()]);
            for (int ci = 0; ci < propchgary.length; ci++) {
              propchg = propchgary[ci];
              updateValues(endWaitProps, endVals, propchg);
              updateValues(filterProps, filterVals, propchg);
            }
          }
        }
      }
      Object expctdval = null;
      // Check if the expected values have been reached and exit the loop if done.
      // Also exit the WaitForUpdates loop if this is the case.
      for (int chgi = 0; chgi < endVals.length && !reached; chgi++) {
        for (int vali = 0; vali < expectedVals[chgi].length && !reached; vali++) {
          expctdval = expectedVals[chgi][vali];
          reached = expctdval.equals(endVals[chgi]) || reached;
        }
      }
    }

    // Destroy the filter when we are done.
    vimPort.destroyPropertyFilter(filterSpecRef);
    return filterVals;
  }
Esempio n. 27
0
  public static void main(String[] args) throws Exception {
    String host = null;
    int port = -1;
    for (int i = 0; i < args.length; i++) {
      System.out.println("args[" + i + "] = " + args[i]);
    }
    if (args.length < 2) {
      System.out.println("USAGE: java client host port");
      System.exit(-1);
    }
    try {
        /* get input parameters */
      host = args[0];
      port = Integer.parseInt(args[1]);
    } catch (IllegalArgumentException e) {
      System.out.println("USAGE: java client host port");
      System.exit(-1);
    }

    try {
        /* set up a key manager for client authentication */
      SSLSocketFactory factory = null;
      try {
        KeyStore ks = KeyStore.getInstance("JKS");
        KeyStore ts = KeyStore.getInstance("JKS");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        SSLContext ctx = SSLContext.getInstance("TLS");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter keystore: ");
        String keystoreName = br.readLine();
        Console cons = System.console();

        if (cons != null) {
          password = cons.readPassword("%s", "Password: "******"Cannot find a console to read password from. Eclipse CANNOT fork a terminal child process.");
        }

        ks.load(new FileInputStream("keystores/" + keystoreName), password); // keystore
        // password
        // (storepass)
        char[] cliTrustPW = "password".toCharArray();
        ts.load(new FileInputStream("clienttruststore"), cliTrustPW); // truststore
        // password
        // (storepass);
        kmf.init(ks, password); // user password (keypass)
        tmf.init(ts); // keystore can be used as truststore here
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        factory = ctx.getSocketFactory();
      } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
      }

      SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
      System.out.println("Handshake socket: " + socket + "\n");

      /*
       * send http request
       *
       * See SSLSocketClient.java for more information about why there is
       * a forced handshake here when using PrintWriters.
       */
      socket.startHandshake();

      SSLSession session = socket.getSession();
      X509Certificate cert = (X509Certificate) session.getPeerCertificateChain()[0];
      System.out.println("Server DN: " + cert.getSubjectDN().getName());
      System.out.println("Handshake socket: " + socket);
      System.out.println("Secure connection.");
      System.out.println("Issuer DN: " + cert.getIssuerDN().getName());
      System.out.println("Serial N: " + cert.getSerialNumber().toString());

      read = new BufferedReader(new InputStreamReader(System.in));
      serverMsg = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      out = new PrintWriter(socket.getOutputStream(), true);
      ois = new ObjectInputStream(socket.getInputStream());
      records = new ArrayList<Record>();

      boolean isLoggedIn = false;
      boolean isDone = false;

      isLoggedIn = waitForLoginData();

      if (!isLoggedIn) {
        System.out.println(
            "This certificate does not have a user. \n Press the RETURN key to exit.");
        System.console().readLine();

        out.close();
        read.close();
        socket.close();
        return;
      }

      boolean accessDenied = false;

      while (!isDone) {

        if (accessDenied) {
          System.out.println(
              "Access denied, or no such record exists! \n Type 'help' for commands.");
        }

        System.out.print(user.getUsername() + " commands>");
        msg = read.readLine();
        fetchRecords();
        splitMsg = msg.split("\\s+");

        try {
          if (msg.equalsIgnoreCase("quit")) {
            break;
          } else if (msg.equalsIgnoreCase("help")) {
            printHelp();
          } else if (splitMsg[0].equalsIgnoreCase("records")) {
            printRecords();
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("edit") && (accessDenied = hasPermissions(msg))) {
            editRecord(splitMsg[1]);
            fetchRecords();
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("read") && (accessDenied = hasPermissions(msg))) {
            printRecord(splitMsg[1]);
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("delete")
              && (accessDenied = hasPermissions(msg))) {
            for (Record r : records) {
              if (r.getId() == Long.parseLong(splitMsg[1])) {
                r.delete(user);
                accessDenied = false;
              }
            }
            fetchRecords();
          } else if (splitMsg[0].equalsIgnoreCase("create")
              && (accessDenied = hasPermissions(msg))) {
            createRecord();
            fetchRecords();
            accessDenied = false;
          } else {
            accessDenied = true;
          }
        } catch (Exception e) {
          accessDenied = true;
        }
      }

      ois.close();
      out.close();
      read.close();
      socket.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 28
0
  public String executeAPI(
      String jSON,
      String apiUrl,
      String url,
      boolean requireAuth,
      String user,
      String password,
      String requestMethod,
      BuildListener listener,
      boolean dynamicUserId,
      String buildID,
      int buildNumber,
      String workPlacePath,
      int connConnTimeOut,
      int connReadTimeout,
      boolean advConfig)
      throws Exception {

    try {

      boolean notInTestMode = true;
      if (listener == null) {
        notInTestMode = false;
      }

      String apiURL = url + "/rest" + apiUrl;

      if (notInTestMode) {
        listener
            .getLogger()
            .print("vManager vAPI - Trying to call vAPI '" + "/rest" + apiUrl + "'\n");
      }
      String input = jSON;
      HttpURLConnection conn =
          getVAPIConnection(
              apiURL,
              requireAuth,
              user,
              password,
              requestMethod,
              dynamicUserId,
              buildID,
              buildNumber,
              workPlacePath,
              listener,
              connConnTimeOut,
              connReadTimeout,
              advConfig);

      if ("PUT".equals(requestMethod) || "POST".equals(requestMethod)) {
        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();
      }

      if (conn.getResponseCode() != HttpURLConnection.HTTP_OK
          && conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT
          && conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED
          && conn.getResponseCode() != HttpURLConnection.HTTP_CREATED
          && conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL
          && conn.getResponseCode() != HttpURLConnection.HTTP_RESET) {
        String reason = "";
        if (conn.getResponseCode() == 503)
          reason = "vAPI process failed to connect to remote vManager server.";
        if (conn.getResponseCode() == 401) reason = "Authentication Error";
        if (conn.getResponseCode() == 415)
          reason =
              "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.  Check if you selected the right request method (GET/POST/DELETE/PUT).";
        if (conn.getResponseCode() == 405)
          reason =
              "The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.  Check if you selected the right request method (GET/POST/DELETE/PUT).";
        if (conn.getResponseCode() == 412)
          reason = "vAPI requires vManager 'Integration Server' license.";
        String errorMessage =
            "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")\n";
        if (notInTestMode) {
          listener.getLogger().print(errorMessage);
        }

        System.out.println(errorMessage);
        return errorMessage;
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      StringBuilder result = new StringBuilder();
      String output;
      while ((output = br.readLine()) != null) {
        result.append(output);
      }

      conn.disconnect();

      // Flush the output into workspace
      String fileOutput =
          workPlacePath + File.separator + buildNumber + "." + buildID + ".vapi.output";

      FileWriter writer = new FileWriter(fileOutput);

      writer.append(result.toString());
      writer.flush();
      writer.close();

      String textOut = "API Call Success: Output was saved into: " + fileOutput + "\n";

      if (notInTestMode) {
        listener.getLogger().print(textOut);
      } else {

        System.out.println(textOut);
      }

      return "success";

    } catch (Exception e) {
      listener.getLogger().print("Filed: Error: " + e.getMessage());
      return e.getMessage();
    }
  }