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 #2
0
  /** Creates a new URL to use as the basis of a connection. */
  public MsgRpcImpl(
      String username, String password, String host, int port, boolean ssl, boolean debugf)
      throws MalformedURLException {
    if (ssl) { // Install the all-trusting trust manager & HostnameVerifier
      try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(
            null,
            new TrustManager[] {
              new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                  return null;
                }

                public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {}

                public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {}
              }
            },
            new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(
            new HostnameVerifier() {
              public boolean verify(String string, SSLSession ssls) {
                return true;
              }
            });
      } catch (Exception e) {
      }
      u = new URL("https", host, port, "/api/1.0/");
    } else {
      u = new URL("http", host, port, "/api/1.0/");
    }

    /* login to msf server */
    Object[] params = new Object[] {username, password};
    Map results = exec("auth.login", params);

    /* save the temp token (lasts for 5 minutes of inactivity) */
    rpcToken = results.get("token").toString();

    /* generate a non-expiring token and use that */
    params = new Object[] {rpcToken};
    results = exec("auth.token_generate", params);
    rpcToken = results.get("token").toString();
  }
Example #3
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 {

    /*
     * 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;
    }
  }
Example #4
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 #5
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 {
    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

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

    if (!(urlc instanceof javax.net.ssl.HttpsURLConnection)) {
      throw new Exception("URLConnection ! instanceof javax.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());
      Certificate[] certs = ((HttpsURLConnection) urlc).getServerCertificates();
      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");
  }
Example #6
0
  /**
   * Establishes session with the virtual center server.
   *
   * @throws Exception the exception
   */
  private static void connect() throws Exception {
    HostnameVerifier hv =
        new HostnameVerifier() {
          public boolean verify(String urlHostName, SSLSession session) {
            return true;
          }
        };
    trustAllHttpsCertificates();
    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    SVC_INST_REF.setType(SVC_INST_NAME);
    SVC_INST_REF.setValue(SVC_INST_NAME);

    vimService = new VimService();
    vimPort = vimService.getVimPort();
    Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext();

    ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
    ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);

    serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
    boolean isVCApi = checkApiType(serviceContent);
    if (!isVCApi) {
      System.out.println("Virtual Center is not supported");
      System.exit(0);
    }
    headers =
        (Map)
            ((BindingProvider) vimPort)
                .getResponseContext()
                .get(MessageContext.HTTP_RESPONSE_HEADERS);
    vimPort.login(serviceContent.getSessionManager(), userName, password, null);
    isConnected = true;
    rootRef = serviceContent.getRootFolder();
    propCollectorRef = serviceContent.getPropertyCollector();
  }
  protected HttpURLConnection connect(String url) throws Exception {
    HttpMessageContext context = HttpMessageContext.getInstance();
    context.Debug("GNHttpConnection [connect] connect");
    URLConnection uc = null;
    /*
    synchronized(context)
    {
      Properties prop = System.getProperties();*/
    /*NSL20070112
    if(isUsingProxy())
    {
      prop.setProperty("proxySet", "true" );
      prop.setProperty("proxyHost", getConfig_http_proxy_url());
      prop.setProperty("proxyPort", getConfig_http_proxy_port());

      prop.setProperty("http.proxySet","true");
      prop.setProperty("http.proxyHost",getConfig_http_proxy_url());
      prop.setProperty("http.proxyPort",getConfig_http_proxy_port());
      prop.setProperty("https.proxyHost", getConfig_http_proxy_url());
      prop.setProperty("https.proxyPort", getConfig_http_proxy_port());
    }
    else
    {
      prop.remove("proxySet");
      prop.remove("proxyHost");
      prop.remove("proxyPort");

      prop.remove("http.proxySet");
      prop.remove("http.proxyHost");
      prop.remove("http.proxyPort");
      prop.remove("https.proxyHost");
      prop.remove("https.proxyPort");
    }
    Authenticator.setDefault(new AuthImpl());
    */
    /*NSL20070507 No need to change the JVM property
    if(!HttpMessageContext.emptyString(keyStoreFile))
    {
      prop.put("javax.net.ssl.keyStore", keyStoreFile);
      prop.put("javax.net.ssl.keyStorePassword", JavaKeyStoreHandler.getTrustStorePassword(keyStorePassword));
    }
    if (!HttpMessageContext.emptyString(trustStoreFile))
    {
        prop.put("javax.net.ssl.trustStore", trustStoreFile);
        prop.put("javax.net.ssl.trustStorePassword", trustStorePassword);
    }*/
    /*NSL20070112
    context.Debug("GNHttpConnection [connect]" + "Connecting URL(" + url + ") timeout[" + timeout +" s]");
    myURLobject = new URL(url);
    uc = myURLobject.openConnection();
    */
    /*}*/

    context.Debug(
        "GNHttpConnection [connect]" + "Connecting URL(" + url + ") timeout[" + timeout + " s]");
    try {
      myURLobject = new URL(url);
      List<Proxy> proxyList = findProxy(myURLobject.toURI());
      if (proxyList != null && !proxyList.isEmpty()) {
        for (Proxy proxy : proxyList) {
          try {
            uc = myURLobject.openConnection(proxy);
            break;
          } catch (Exception ex) {
          }
        }
      }
      if (uc == null) {
        uc = myURLobject.openConnection();
      }
    } catch (MalformedURLException ex) {
      context.Warn("GNHttpConnection [connect] Malformed URL: " + url, ex);
    } catch (URISyntaxException ex) {
      context.Warn("GNHttpConnection [connect] Invalid URI: " + myURLobject, ex);
    }

    connection = (HttpURLConnection) uc;
    context.Debug("GNHttpConnection [connect] Connection created");
    if (connection instanceof HttpsURLConnection) {
      context.Debug("GNHttpConnection [connect] Https Connection");
      HttpsURLConnection https = (HttpsURLConnection) connection;
      // SSLSocketFactory factory = null;
      SSLSocketFactory factory = getSSLSocketFactory(); // NSL20070507
      if (!authenticateServer) {
        // factory = new NoAuthSSLSocketFactory( https.getSSLSocketFactory() );
        factory = new NoAuthSSLSocketFactory(factory); // NSL20070507
      }

      if (factory != null) {
        https.setSSLSocketFactory(factory);
      }

      if (!verifyServerHostname) {
        https.setHostnameVerifier(new NoVerificationHostnameVerifier());
      }
    }
    return connection;
  }