Example #1
0
  public void close() {
    if (closed) {
      return;
    }
    closed = true;

    /* close the underlying connection if,
     * a) the streams not set up yet, no response can be sent, or
     * b) if the wrapper output stream is not set up, or
     * c) if the close of the input/outpu stream fails
     */
    try {
      if (uis_orig == null || uos == null) {
        connection.close();
        return;
      }
      if (!uos_orig.isWrapped()) {
        connection.close();
        return;
      }
      if (!uis_orig.isClosed()) {
        uis_orig.close();
      }
      uos.close();
    } catch (IOException e) {
      connection.close();
    }
  }
  public static String httsRequest(String url, String contentdata) {
    String str_return = "";
    SSLContext sc = null;
    try {
      sc = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {

      e.printStackTrace();
    }
    try {
      sc.init(
          null, new TrustManager[] {new TrustAnyTrustManager()}, new java.security.SecureRandom());
    } catch (KeyManagementException e) {

      e.printStackTrace();
    }
    URL console = null;
    try {
      console = new URL(url);
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    HttpsURLConnection conn;
    try {
      conn = (HttpsURLConnection) console.openConnection();
      conn.setRequestMethod("POST");
      conn.setSSLSocketFactory(sc.getSocketFactory());
      conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
      conn.setRequestProperty("Accept", "application/json");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      // contentdata="username=arcgis&password=arcgis123&client=requestip&f=json"
      String inpputs = contentdata;
      OutputStream os = conn.getOutputStream();
      os.write(inpputs.getBytes());
      os.close();
      conn.connect();
      InputStream is = conn.getInputStream();
      // // DataInputStream indata = new DataInputStream(is);
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      String ret = "";
      while (ret != null) {
        ret = reader.readLine();
        if (ret != null && !ret.trim().equals("")) {
          str_return = str_return + ret;
        }
      }
      is.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return str_return;
  }
Example #3
0
  /** Creates an XMLRPC call from the given method name and parameters and sends it */
  protected void writeCall(String methodName, Object[] args) throws Exception {
    huc = u.openConnection();
    huc.setDoOutput(true);
    huc.setDoInput(true);
    huc.setUseCaches(false);
    huc.setRequestProperty("Content-Type", "binary/message-pack");
    huc.setReadTimeout(0);
    OutputStream os = huc.getOutputStream();
    Packer pk = new Packer(os);

    pk.packArray(args.length + 1);
    pk.pack(methodName);
    for (Object o : args) pk.pack(o);
    os.close();
  }
Example #4
0
  private static void putVMFiles(String remoteFilePath, String localFilePath) throws Exception {
    String serviceUrl = url.substring(0, url.lastIndexOf("sdk") - 1);
    String httpUrl =
        serviceUrl + "/folder" + remoteFilePath + "?dcPath=" + datacenter + "&dsName=" + datastore;
    httpUrl = httpUrl.replaceAll("\\ ", "%20");
    System.out.println("Putting VM File " + httpUrl);
    URL fileURL = new URL(httpUrl);
    HttpURLConnection conn = (HttpURLConnection) fileURL.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setAllowUserInteraction(true);

    // Maintain session
    List cookies = (List) headers.get("Set-cookie");
    cookieValue = (String) cookies.get(0);
    StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";");
    cookieValue = tokenizer.nextToken();
    String path = "$" + tokenizer.nextToken();
    String cookie = "$Version=\"1\"; " + cookieValue + "; " + path;

    // set the cookie in the new request header
    Map map = new HashMap();
    map.put("Cookie", Collections.singletonList(cookie));
    ((BindingProvider) vimPort).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, map);

    conn.setRequestProperty("Cookie", cookie);
    conn.setRequestProperty("Content-Type", "application/octet-stream");
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Content-Length", "1024");
    long fileLen = new File(localFilePath).length();
    System.out.println("File size is: " + fileLen);
    conn.setChunkedStreamingMode((int) fileLen);
    OutputStream out = conn.getOutputStream();
    InputStream in = new BufferedInputStream(new FileInputStream(localFilePath));
    int bufLen = 9 * 1024;
    byte[] buf = new byte[bufLen];
    byte[] tmp = null;
    int len = 0;
    while ((len = in.read(buf, 0, bufLen)) != -1) {
      tmp = new byte[len];
      System.arraycopy(buf, 0, tmp, 0, len);
      out.write(tmp, 0, len);
    }
    in.close();
    out.close();
    conn.getResponseMessage();
    conn.disconnect();
  }
Example #5
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;
      }
    }
Example #6
0
  public static void main(String[] args) throws Exception {
    String host;
    int port;
    char[] passphrase;
    if ((args.length == 1) || (args.length == 2)) {
      String[] c = args[0].split(":");
      host = c[0];
      port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
      String p = (args.length == 1) ? "changeit" : args[1];
      passphrase = p.toCharArray();
    } else {
      System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
      return;
    }

    File file = new File("jssecacerts");
    if (file.isFile() == false) {
      char SEP = File.separatorChar;
      File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
      file = new File(dir, "jssecacerts");
      if (file.isFile() == false) {
        file = new File(dir, "cacerts");
      }
    }
    System.out.println("Loading KeyStore " + file + "...");
    KeyStore ks;
    InputStream in = new FileInputStream(file);
    ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(in, passphrase);

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] {tm}, null);
    SSLSocketFactory factory = context.getSocketFactory();

    System.out.println("Opening connection to " + host + ":" + port + "...");
    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
    socket.setSoTimeout(10000);
    try {
      System.out.println("Starting SSL handshake...");
      socket.startHandshake();
      socket.close();
      System.out.println();
      System.out.println("No errors, certificate is already trusted");
    } catch (SSLException e) {
      System.out.println();
      e.printStackTrace(System.out);
    }

    X509Certificate[] chain = tm.chain;
    if (chain == null) {
      System.out.println("Could not obtain server certificate chain");
      return;
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    System.out.println();
    System.out.println("Server sent " + chain.length + " certificate(s):");
    System.out.println();
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
      X509Certificate cert = chain[i];
      System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
      System.out.println("   Issuer  " + cert.getIssuerDN());
      sha1.update(cert.getEncoded());
      System.out.println("   sha1    " + toHexString(sha1.digest()));
      md5.update(cert.getEncoded());
      System.out.println("   md5     " + toHexString(md5.digest()));
      System.out.println();
    }

    System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
    String line = reader.readLine().trim();
    int k;
    try {
      k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
    } catch (NumberFormatException e) {
      System.out.println("KeyStore not changed");
      return;
    }

    X509Certificate cert = chain[k];
    String alias = host + "-" + (k + 1);
    ks.setCertificateEntry(alias, cert);

    OutputStream out = new FileOutputStream("jssecacerts");
    ks.store(out, passphrase);
    out.close();

    System.out.println();
    System.out.println(cert);
    System.out.println();
    System.out.println("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'");
  }
Example #7
0
 public void close() throws IOException {
   checkWrap();
   wrapped.close();
 }