Java Code Examples for org.apache.commons.httpclient.protocol.Protocol#registerProtocol()

The following examples show how to use org.apache.commons.httpclient.protocol.Protocol#registerProtocol() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DavGatewaySSLProtocolSocketFactory.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Register custom Socket Factory to let user accept or reject certificate
 */
public static void register() {
    String urlString = Settings.getProperty("davmail.url");
    try {
        URL url = new URL(urlString);
        String protocol = url.getProtocol();
        if ("https".equals(protocol)) {
            int port = url.getPort();
            if (port < 0) {
                port = HttpsURL.DEFAULT_PORT;
            }
            Protocol.registerProtocol(url.getProtocol(),
                    new Protocol(protocol, (ProtocolSocketFactory) new DavGatewaySSLProtocolSocketFactory(), port));
        }
    } catch (MalformedURLException e) {
        DavGatewayTray.error(new BundleMessage("LOG_INVALID_URL", urlString));
    }
}
 
Example 2
Source File: ServiceUtil.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
public static IService getService() throws MalformedURLException {
//		Service srvcModel = new ObjectServiceFactory().create(IService.class);
//		XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
//				.newInstance().getXFire());
//
//		IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
//		return srvc;
		
		ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();  
        Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);  
        Protocol.registerProtocol(HTTP_TYPE, protocol);  
        Service serviceModel = new ObjectServiceFactory().create(IService.class,  
        		SERVICE_NAME, SERVICE_NAMESPACE, null);  
        
    	IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);  
    	Client client = ((XFireProxy)Proxy.getInvocationHandler(service)).getClient();  
        client.addOutHandler(new DOMOutHandler());  
        client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);  
        client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");  
        client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0"); 
        
        return service;
	}
 
Example 3
Source File: ServiceUtil.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
public static IService getService() throws MalformedURLException {
//		Service srvcModel = new ObjectServiceFactory().create(IService.class);
//		XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
//				.newInstance().getXFire());
//
//		IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
//		return srvc;
		
		ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();  
        Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);  
        Protocol.registerProtocol(HTTP_TYPE, protocol);  
        Service serviceModel = new ObjectServiceFactory().create(IService.class,  
        		SERVICE_NAME, SERVICE_NAMESPACE, null);  
        
    	IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);  
    	Client client = ((XFireProxy)Proxy.getInvocationHandler(service)).getClient();  
        client.addOutHandler(new DOMOutHandler());  
        client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);  
        client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");  
        client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0"); 
        
        return service;
	}
 
Example 4
Source File: ServiceUtil.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
public static IService getService() throws MalformedURLException {
//		Service srvcModel = new ObjectServiceFactory().create(IService.class);
//		XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
//				.newInstance().getXFire());
//
//		IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
//		return srvc;
		
		ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();  
        Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);  
        Protocol.registerProtocol(HTTP_TYPE, protocol);  
        Service serviceModel = new ObjectServiceFactory().create(IService.class,  
        		SERVICE_NAME, SERVICE_NAMESPACE, null);  
        
    	IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);  
    	Client client = ((XFireProxy)Proxy.getInvocationHandler(service)).getClient();  
        client.addOutHandler(new DOMOutHandler());  
        client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);  
        client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");  
        client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0"); 
        
        return service;
	}
 
Example 5
Source File: ServiceUtil.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
public static IService getService() throws MalformedURLException {
//		Service srvcModel = new ObjectServiceFactory().create(IService.class);
//		XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
//				.newInstance().getXFire());
//
//		IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
//		return srvc;
		
		ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();  
        Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);  
        Protocol.registerProtocol(HTTP_TYPE, protocol);  
        Service serviceModel = new ObjectServiceFactory().create(IService.class,  
        		SERVICE_NAME, SERVICE_NAMESPACE, null);  
        
    	IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);  
    	Client client = ((XFireProxy)Proxy.getInvocationHandler(service)).getClient();  
        client.addOutHandler(new DOMOutHandler());  
        client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);  
        client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");  
        client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0"); 
        
        return service;
	}
 
Example 6
Source File: Manager.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private void createHttpClient() {
    Protocol protocol = Protocol.getProtocol("https");
    if (protocol == null) {
        // ZAP: Dont override an existing protocol - it causes problems with ZAP
        Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", easyhttps);
    }
    initialState = new HttpState();

    MultiThreadedHttpConnectionManager connectionManager =
            new MultiThreadedHttpConnectionManager();
    connectionManager.getParams().setDefaultMaxConnectionsPerHost(1000);
    connectionManager.getParams().setMaxTotalConnections(1000);

    // connectionManager.set

    httpclient = new HttpClient(connectionManager);
    // httpclient.

}
 
Example 7
Source File: HttpPerformer.java    From http4e with Apache License 2.0 6 votes vote down vote up
private void doSSL( HttpClient client, HostConfiguration hostConf, String host, int port){
   if (hostConf.getProtocol().isSecure()) {

      // System.setProperty("javax.net.ssl.trustStore", sslKeystore);
      // Protocol sslPprotocol = new Protocol("https", new
      // org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory(),
      // 443);
      // client.getHostConfiguration().setHost(host, 443, sslPprotocol);

      try {
         ProtocolSocketFactory factory = new InsecureSSLProtocolSocketFactory();
         Protocol https = new Protocol("https", factory, port);
         Protocol.registerProtocol("https", https);
         client.getHostConfiguration().setHost(host, port, https);

      } catch (GeneralSecurityException e) {
         throw new CoreException(CoreException.SSL, e);
      }
   }
}
 
Example 8
Source File: CertificadoService.java    From Java_Certificado with MIT License 6 votes vote down vote up
public static void inicializaCertificado(Certificado certificado, InputStream cacert) throws CertificadoException {

        Optional.ofNullable(certificado).orElseThrow(() -> new IllegalArgumentException("Certificado não pode ser nulo."));
        Optional.ofNullable(cacert).orElseThrow(() -> new IllegalArgumentException("Cacert não pode ser nulo."));

        try {

            KeyStore keyStore = getKeyStore(certificado);
            if (certificado.isAtivarProperties()) {
                CertificadoProperties.inicia(certificado, cacert);
            } else {
                SocketFactoryDinamico socketFactory = new SocketFactoryDinamico(keyStore,certificado.getNome(),certificado.getSenha(), cacert,
                        certificado.getSslProtocol());
                Protocol protocol = new Protocol("https", socketFactory, 443);
                Protocol.registerProtocol("https", protocol);
            }

        } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException | CertificateException | IOException e) {
            throw new CertificadoException(e.getMessage());
        }

    }
 
Example 9
Source File: HttpsCallerProcess.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("URL not set! Please give an URL as argument.");
        System.exit(-1);
    }

    try {
        String urlStrg = args[0];
        URL url = new URL(urlStrg);
        if (!HTTPS.equals(url.getProtocol())) {
            throw new IllegalArgumentException("Please choose https protocol! " + url);
        }

        Protocol.registerProtocol(
                HTTPS, new Protocol(HTTPS, (ProtocolSocketFactory) new SSLConnector(), 443));

        HttpMessage msg = accessURL(url);
        if (msg != null) {
            System.out.println(msg.getResponseHeader());
        }
        System.out.println("--- END of call -------------------------------------------------");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    System.out.close();
    System.err.close();
}
 
Example 10
Source File: ServiceUtilTest.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
public static IService getService() throws MalformedURLException {
	// Service srvcModel = new
	// ObjectServiceFactory().create(IService.class);
	// XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
	// .newInstance().getXFire());
	//
	// IService srvc = (IService) factory.create(srvcModel,
	// Constants.CONNECT_URL);
	// return srvc;

	ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
	Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);
	Protocol.registerProtocol(HTTP_TYPE, protocol);
	Service serviceModel = new ObjectServiceFactory().create(
			IService.class, SERVICE_NAME, SERVICE_NAMESPACE, null);

	IService service = (IService) new XFireProxyFactory().create(
			serviceModel, SERVICE_URL);
	Client client = ((XFireProxy) Proxy.getInvocationHandler(service))
			.getClient();
	client.addOutHandler(new DOMOutHandler());
	client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);
	client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE,
			"1");
	client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0");

	return service;
}
 
Example 11
Source File: HttpClientBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Builds an HTTP client with the given settings. Settings are NOT reset to their default values after a client has
 * been created.
 * 
 * @return the created client.
 */
public HttpClient buildClient() {
    if (httpsProtocolSocketFactory != null) {
        Protocol.registerProtocol("https", new Protocol("https", httpsProtocolSocketFactory, 443));
    }

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setAuthenticationPreemptive(isPreemptiveAuthentication());
    clientParams.setContentCharset(getContentCharSet());
    clientParams.setParameter(HttpClientParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(
            connectionRetryAttempts, false));

    HttpConnectionManagerParams connMgrParams = new HttpConnectionManagerParams();
    connMgrParams.setConnectionTimeout(getConnectionTimeout());
    connMgrParams.setDefaultMaxConnectionsPerHost(getMaxConnectionsPerHost());
    connMgrParams.setMaxTotalConnections(getMaxTotalConnections());
    connMgrParams.setReceiveBufferSize(getReceiveBufferSize());
    connMgrParams.setSendBufferSize(getSendBufferSize());
    connMgrParams.setTcpNoDelay(isTcpNoDelay());

    MultiThreadedHttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager();
    connMgr.setParams(connMgrParams);

    HttpClient httpClient = new HttpClient(clientParams, connMgr);

    if (proxyHost != null) {
        HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setProxy(proxyHost, proxyPort);
        httpClient.setHostConfiguration(hostConfig);

        if (proxyUsername != null) {
            AuthScope proxyAuthScope = new AuthScope(proxyHost, proxyPort);
            UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(proxyUsername,
                    proxyPassword);
            httpClient.getState().setProxyCredentials(proxyAuthScope, proxyCredentials);
        }
    }

    return httpClient;
}
 
Example 12
Source File: ChatRoomDecorator.java    From Spark with Apache License 2.0 5 votes vote down vote up
private void uploadFile(File file, UploadRequest response, ChatRoom room, Message.Type type)
{
    Log.warning("uploadFile request " + room.getRoomJid() + " " + response.putUrl);
    URLConnection urlconnection = null;

    try {
        PutMethod put = new PutMethod(response.putUrl);
        int port = put.getURI().getPort();
        if (port > 0)
        {
            Protocol.registerProtocol( "https", new Protocol( "https", new EasySSLProtocolSocketFactory(), port ) );
        }
        
        HttpClient client = new HttpClient();
        RequestEntity entity = new FileRequestEntity(file, "application/binary");
        put.setRequestEntity(entity);
        put.setRequestHeader("User-Agent", "Spark HttpFileUpload");
        client.executeMethod(put);

        int statusCode = put.getStatusCode();
        String responseBody = put.getResponseBodyAsString();

        Log.warning("uploadFile response " + statusCode + " " + responseBody);

        if ((statusCode >= 200) && (statusCode <= 202))
        {
            broadcastUploadUrl(room.getRoomJid(), response.getUrl, type);
        }

    } catch (Exception e) {
        Log.error("uploadFile error", e);
    }
}
 
Example 13
Source File: BigSwitchBcfApi.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public BigSwitchBcfApi() {
    _client = createHttpClient();
    _client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    try {
        // Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter
        Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), _port));
    } catch (IOException e) {
        S_LOGGER.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
    }
}
 
Example 14
Source File: NeutronRestApi.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
protected NeutronRestApi(final Class<? extends HttpMethodBase> httpClazz, final String protocol, final int port) {
    client = createHttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    this.httpClazz = httpClazz;

    try {
        // Cast to ProtocolSocketFactory to avoid the deprecated constructor
        // with the SecureProtocolSocketFactory parameter
        Protocol.registerProtocol(protocol, new Protocol(protocol, (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), HTTPS_PORT));
    } catch (IOException e) {
        s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
    }
}
 
Example 15
Source File: CrucibleSessionImpl.java    From Crucible4IDEA with MIT License 4 votes vote down vote up
private void initSSLCertPolicy() {
  EasySSLProtocolSocketFactory secureProtocolSocketFactory = new EasySSLProtocolSocketFactory();
  Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory)secureProtocolSocketFactory, 443));
}
 
Example 16
Source File: KylinClient.java    From Kylin with Apache License 2.0 4 votes vote down vote up
private void registerSsl() {
    Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new DefaultSslProtocolSocketFactory(), 443));
}
 
Example 17
Source File: PluginViewer.java    From Spark with Apache License 2.0 4 votes vote down vote up
private void loadAvailablePlugins()
 {
     availablePanel.removeAll();
     availablePanel.invalidate();
     availablePanel.validate();
     availablePanel.repaint();

     JLabel label = new JLabel( Res.getString( "message.loading.please.wait" ) );
     availablePanel.add( label );


     SwingWorker worker = new SwingWorker()
     {
         Collection<PublicPlugin> pluginList = null;

         @Override
public Object construct()
         {
             // Prepare HTTP post
             final GetMethod post = new GetMethod( retrieveListURL );

             // Get HTTP client
             Protocol.registerProtocol( "https", new Protocol( "https", new EasySSLProtocolSocketFactory(), 443 ) );
             final HttpClient httpclient = new HttpClient();

             if ( Default.getBoolean( "PLUGIN_REPOSITORY_USE_PROXY" ) )
             {
                 String proxyHost = System.getProperty( "http.proxyHost" );
                 String proxyPort = System.getProperty( "http.proxyPort" );
                 if ( ModelUtil.hasLength( proxyHost ) && ModelUtil.hasLength( proxyPort ) )
                 {
                     try
                     {
                         httpclient.getHostConfiguration().setProxy( proxyHost, Integer.parseInt( proxyPort ) );
                     }
                     catch ( NumberFormatException e )
                     {
                         Log.error( e );
                     }
                 }
             }

             // Execute request

             try
             {
                 int result = httpclient.executeMethod( post );
                 if ( result != 200 )
                 {
                     return null;
                 }

                 pluginList = getPluginList( post.getResponseBodyAsStream() );
             }
             catch ( Exception ex )
             {
                 // Nothing to do
             }
             return "ok";
         }

         @Override
public void finished()
         {
             final PluginManager pluginManager = PluginManager.getInstance();
             if ( pluginList == null )
             {
                 availablePanel.removeAll();
                 availablePanel.invalidate();
                 availablePanel.validate();
                 availablePanel.repaint();

                 UIManager.put( "OptionPane.okButtonText", Res.getString( "ok" ) );
                 JOptionPane.showMessageDialog( availablePanel, Res.getString( "message.plugins.not.available" ), Res.getString( "title.error" ), JOptionPane.ERROR_MESSAGE );
                 return;
             }
             Iterator<PublicPlugin> plugs = pluginList.iterator();
             availablePanel.removeAll();

             while ( plugs.hasNext() )
             {
                 PublicPlugin plugin = plugs.next();
                 if ( !pluginManager.isInstalled( plugin ) )
                 {
                     SparkPlugUI ui = new SparkPlugUI( plugin );
                     availablePanel.add( ui );
                     addSparkPlugUIListener( ui );
                 }
             }

             availablePanel.invalidate();
             availablePanel.validate();
             availablePanel.repaint();
         }
     };

     worker.start();
 }
 
Example 18
Source File: Http.java    From nutch-htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Configures the HTTP client
 */
private void configureClient() {

  // Set up an HTTPS socket factory that accepts self-signed certs.
  ProtocolSocketFactory factory = new SSLProtocolSocketFactory();
  Protocol https = new Protocol("https", factory, 443);
  Protocol.registerProtocol("https", https);

  HttpConnectionManagerParams params = connectionManager.getParams();
  params.setConnectionTimeout(timeout);
  params.setSoTimeout(timeout);
  params.setSendBufferSize(BUFFER_SIZE);
  params.setReceiveBufferSize(BUFFER_SIZE);
  params.setMaxTotalConnections(maxThreadsTotal);

  // executeMethod(HttpMethod) seems to ignore the connection timeout on the connection manager.
  // set it explicitly on the HttpClient.
  client.getParams().setConnectionManagerTimeout(timeout);

  HostConfiguration hostConf = client.getHostConfiguration();
  ArrayList<Header> headers = new ArrayList<Header>();
  // Set the User Agent in the header
  headers.add(new Header("User-Agent", userAgent));
  // prefer English
  headers.add(new Header("Accept-Language", acceptLanguage));
  // prefer UTF-8
  headers.add(new Header("Accept-Charset", "utf-8,ISO-8859-1;q=0.7,*;q=0.7"));
  // prefer understandable formats
  headers.add(new Header("Accept",
          "text/html,application/xml;q=0.9,application/xhtml+xml,text/xml;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"));
  // accept gzipped content
  headers.add(new Header("Accept-Encoding", "x-gzip, gzip, deflate"));
  hostConf.getParams().setParameter("http.default-headers", headers);

  // HTTP proxy server details
  if (useProxy) {
    hostConf.setProxy(proxyHost, proxyPort);

    if (proxyUsername.length() > 0) {

      AuthScope proxyAuthScope = getAuthScope(
          this.proxyHost, this.proxyPort, this.proxyRealm);

      NTCredentials proxyCredentials = new NTCredentials(
          this.proxyUsername, this.proxyPassword,
          Http.agentHost, this.proxyRealm);

      client.getState().setProxyCredentials(
          proxyAuthScope, proxyCredentials);
    }
  }

}
 
Example 19
Source File: UcsHttpClient.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public UcsHttpClient(String ip) {
    url = String.format("http://%s/nuova", ip);
    Protocol.registerProtocol("https", ucsHttpsProtocol);
}
 
Example 20
Source File: CommonsHttpTransportTests.java    From elasticsearch-hadoop with Apache License 2.0 4 votes vote down vote up
@After
public void reset() {
    Protocol.registerProtocol("https", original);
}