private JobPositionClient() { URL wsdl = JobPositionWS_Service.WSDL_LOCATION; try { wsdl = new URL("file:" + System.getProperty("wsdl.location") + "jobposition.wsdl"); } catch (MalformedURLException e) { log.error( "Errore URL JobPositionClient, using default url " + JobPositionWS_Service.WSDL_LOCATION.toString(), e); } log.info("USING: " + wsdl.toString()); JobPositionWS_Service client = new JobPositionWS_Service(wsdl, JobPositionWS_Service.SERVICE); this.port = client.getJobPositionWSSOAP(); String proxyServer = System.getProperty("jobposition.proxy.server"); if ((proxyServer != null) && (!("".equals(proxyServer)))) { Client cxf = ClientProxy.getClient(this.port); HTTPConduit http = (HTTPConduit) cxf.getConduit(); HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); httpClientPolicy.setProxyServer(proxyServer); httpClientPolicy.setProxyServerPort(8080); String proxyPort = System.getProperty("jobposition.proxy.port"); if ((proxyPort != null) && (!("".equals(proxyPort)))) { try { int portnum = Integer.parseInt(proxyPort); if (portnum > 0) httpClientPolicy.setProxyServerPort(portnum); } catch (RuntimeException re) { log.error("Error parsing ProxyPort: " + proxyPort); } } http.setClient(httpClientPolicy); } }
public static Webservices getProxy() { final JaxWsProxyFactoryBean proxyFactory = new JaxWsProxyFactoryBean(); proxyFactory.setServiceClass(Webservices.class); SettingsDataProvider settings = BeanProvider.getContextualReference(SettingsDataProvider.class); proxyFactory.setAddress(settings.getSetting("cmdbuild_url")); Object proxy = proxyFactory.create(); final Map<String, Object> outProps = new HashMap<String, Object>(); outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST); outProps.put(WSHandlerConstants.USER, settings.getSetting("cmdbuild_login")); outProps.put( WSHandlerConstants.PW_CALLBACK_REF, new ClientPasswordCallback(settings.getSetting("cmdbuild_pwd"))); final Client client = ClientProxy.getClient(proxy); final Endpoint cxfEndpoint = client.getEndpoint(); long timeout = 9000000000L; if (client != null) { HTTPConduit conduit = (HTTPConduit) client.getConduit(); HTTPClientPolicy policy = new HTTPClientPolicy(); policy.setConnectionTimeout(timeout); policy.setReceiveTimeout(timeout); conduit.setClient(policy); } cxfEndpoint.getOutInterceptors().add(new WSS4JOutInterceptorWOExpire(outProps)); return (Webservices) proxy; }
@Test public void testSaml1SignedSenderVouches() throws Exception { // Create + configure service Service service = createService(); WSSSecurityProperties inProperties = new WSSSecurityProperties(); Properties cryptoProperties = CryptoFactory.getProperties("insecurity.properties", this.getClass().getClassLoader()); inProperties.setSignatureVerificationCryptoProperties(cryptoProperties); WSS4JStaxInInterceptor inhandler = new WSS4JStaxInInterceptor(inProperties); service.getInInterceptors().add(inhandler); // Create + configure client Echo echo = createClientProxy(); Client client = ClientProxy.getClient(echo); client.getInInterceptors().add(new LoggingInInterceptor()); client.getOutInterceptors().add(new LoggingOutInterceptor()); Map<String, Object> properties = new HashMap<String, Object>(); properties.put(WSHandlerConstants.ACTION, WSHandlerConstants.SAML_TOKEN_SIGNED); properties.put(WSHandlerConstants.SAML_CALLBACK_REF, new SAML1CallbackHandler()); properties.put(WSHandlerConstants.SIG_KEY_ID, "DirectReference"); properties.put(WSHandlerConstants.USER, "alice"); properties.put(WSHandlerConstants.PW_CALLBACK_REF, new PasswordCallbackHandler()); properties.put(WSHandlerConstants.SIG_PROP_FILE, "alice.properties"); WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor(properties); client.getOutInterceptors().add(ohandler); assertEquals("test", echo.echo("test")); }
private String getInfo() { JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance(); // from wso2 // Client client // =factory.createClient("http://10.41.87.107:9764/services/PMWebService?wsdl"); Client client = factory.createClient("http://10.41.87.107:8280/pmservice/1.0.0?wsdl"); Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put("Content-Type", Arrays.asList("text/xml; charset=utf-8")); headers.put("Authorization", Arrays.asList(token)); client.getRequestContext().put(Message.PROTOCOL_HEADERS, headers); // from gis // Wrong Info: tns.StringArray cannot be cast to java.lang.String // Client client =factory.createClient("http://10.41.87.37:7789/snt?wsdl"); Object[] obj = null; try { // from wso2 obj = client.invoke("getPMInfo"); // from gis // obj = client.invoke("getAccidentDataforCamera"); } catch (Exception e) { e.printStackTrace(); } if (obj != null) return (String) obj[0]; return null; }
// In this test, the service is using the UsernameTokenInterceptor, but the // client is using the WSS4JOutInterceptor @org.junit.Test public void testPasswordHashedNoBindingReplay() throws Exception { SpringBusFactory bf = new SpringBusFactory(); URL busFile = UsernameTokenTest.class.getResource("client.xml"); Bus bus = bf.createBus(busFile.toString()); SpringBusFactory.setDefaultBus(bus); SpringBusFactory.setThreadDefaultBus(bus); URL wsdl = UsernameTokenTest.class.getResource("DoubleItUt.wsdl"); Service service = Service.create(wsdl, SERVICE_QNAME); QName portQName = new QName(NAMESPACE, "DoubleItDigestNoBindingPort"); DoubleItPortType utPort = service.getPort(portQName, DoubleItPortType.class); updateAddressPort(utPort, test.getPort()); if (!test.isStreaming() && PORT.equals(test.getPort())) { Client cxfClient = ClientProxy.getClient(utPort); SecurityHeaderCacheInterceptor cacheInterceptor = new SecurityHeaderCacheInterceptor(); cxfClient.getOutInterceptors().add(cacheInterceptor); // Make two invocations with the same UsernameToken utPort.doubleIt(25); try { utPort.doubleIt(25); fail("Failure expected on a replayed UsernameToken"); } catch (javax.xml.ws.soap.SOAPFaultException ex) { assertTrue(ex.getMessage().equals(WSSecurityException.UNIFIED_SECURITY_ERR)); } } ((java.io.Closeable) utPort).close(); bus.shutdown(true); }
@Test public void testSaml1() throws Exception { // Create + configure service Service service = createService(); WSSSecurityProperties inProperties = new WSSSecurityProperties(); inProperties.setValidateSamlSubjectConfirmation(false); WSS4JStaxInInterceptor inhandler = new WSS4JStaxInInterceptor(inProperties); service.getInInterceptors().add(inhandler); // Create + configure client Echo echo = createClientProxy(); Client client = ClientProxy.getClient(echo); client.getInInterceptors().add(new LoggingInInterceptor()); client.getOutInterceptors().add(new LoggingOutInterceptor()); Map<String, Object> properties = new HashMap<String, Object>(); properties.put(WSHandlerConstants.ACTION, WSHandlerConstants.SAML_TOKEN_UNSIGNED); properties.put(WSHandlerConstants.SAML_CALLBACK_REF, new SAML1CallbackHandler()); WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor(properties); client.getOutInterceptors().add(ohandler); assertEquals("test", echo.echo("test")); }
private static <T> T createClient( String port, Class<T> serviceClass, SchemaValidationType type, Feature... features) { JaxWsProxyFactoryBean clientFactory = new JaxWsProxyFactoryBean(); clientFactory.setServiceClass(serviceClass); clientFactory.setAddress(getAddress(port, serviceClass)); if (features != null) { clientFactory.getFeatures().addAll(Arrays.asList(features)); } @SuppressWarnings("unchecked") T newClient = (T) clientFactory.create(); Client proxy = ClientProxy.getClient(newClient); if (type != null) { proxy.getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED, type); } HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); // give me longer debug times HTTPClientPolicy clientPolicy = new HTTPClientPolicy(); clientPolicy.setConnectionTimeout(1000000); clientPolicy.setReceiveTimeout(1000000); conduit.setClient(clientPolicy); return newClient; }
private void setWSS4JOutInterceptor(Object service) { Client client = ClientProxy.getClient(service); Endpoint cxfEP = client.getEndpoint(); WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps); cxfEP.getOutInterceptors().add(wssOut); }
@Override protected void configureInterceptors(Client client) { super.configureInterceptors(client); client.getInInterceptors().add(new InPayloadExtractorInterceptor()); client.getInInterceptors().add(new InNamespaceMergeInterceptor()); client.getInInterceptors().add(new InPayloadInjectorInterceptor(0)); client.getEndpoint().getService().setDataBinding(new PlainXmlDataBinding()); }
@RequestMapping("/getTrafficJamData") @ResponseBody public String getTrafficJamDataforCamera(HttpServletRequest request, HttpServletResponse response) throws Exception { JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); // long time1 = System.currentTimeMillis(); // System.out.println("--------------当前毫秒数--------------" + System.currentTimeMillis()); Client client = dcf.createClient( "http://10.41.87.107:8280/eventdata/1.0.0?wsdl", new QName("tns", "CameraServer")); Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put("Content-Type", Arrays.asList("text/xml; charset=utf-8")); headers.put("Authorization", Arrays.asList(token)); client.getRequestContext().put(Message.PROTOCOL_HEADERS, headers); // long time3 = System.currentTimeMillis(); // System.out.println("-----------时间差1-------------" + (time3 - time1)); Object[] objs = client.invoke("getTrafficJamDataforCamera"); Object o = objs[0]; StringArray sa = (StringArray) o; System.out.println(sa.getString().toString()); // String trafficdata = "[{'info': 'jam', 'created': '2015-06-05T03:10:22.684944', 'lon': // '103.8', 'cameraId': '1', 'state': '0', 'location': 'dasdas', 'lat': '1.29', 'picTime': // '2015-06-11 13:11:34', 'id': '643'}, {'info': 'jam', 'created': '2015-06-05T04:54:04.025940', // 'lon': '103.82314', 'cameraId': '2', 'state': '0', 'location': 'deadfd', 'lat': '1.3', // 'picTime': '2015-06-10 13:11:34', 'id': '658'}, {'info': 'jam', 'created': // '2015-06-05T04:54:07.614366', 'lon': '103.82678', 'cameraId': '3', 'state': '0', 'location': // 'ewewq', 'lat': '1.285', 'picTime': '2015-05-11 12:11:34', 'id': '659'}, {'info': 'jam', // 'created': '2015-06-05T03:10:27.976846', 'lon': '103.84562', 'cameraId': '5', 'state': '0', // 'location': 'dsada', 'lat': '1.29645', 'picTime': '2015-07-11 13:11:34', 'id': '647'}, // {'info': 'jam', 'created': '2015-06-05T04:54:15.138686', 'lon': '103.83562', 'cameraId': 7, // 'state': '0', 'location': 'wwww', 'lat': '1.2978', 'picTime': '2015-08-11 13:11:34', 'id': // '663'}]"; String trafficdata = ""; trafficdata = sa.getString().toString().replace("\\\"", ""); // trafficdata.replace("\"", "'"); // trafficdata = trafficdata.replace("'", "\""); // System.out.println(gson.toJson(trafficdata).toString()); List<Traffic> traffics = new ArrayList<Traffic>(); JsonParser parser = new JsonParser(); JsonArray jsonArray = null; JsonElement je = parser.parse(trafficdata); jsonArray = je.getAsJsonArray(); System.out.println(jsonArray.toString()); for (int i = 0; i < jsonArray.size(); i++) { JsonElement jsonElement = jsonArray.get(i); JsonObject jsonObject = jsonElement.getAsJsonObject(); Traffic traffic = new Traffic(); traffic.setInfo(jsonObject.get("info").getAsString()); traffic.setLat(jsonObject.get("lat").getAsString()); traffic.setLocation(jsonObject.get("location").getAsString()); traffic.setLon(jsonObject.get("lon").getAsString()); traffics.add(traffic); } String trafficsstr = GsonUtil.objectToJson(traffics); System.out.println(trafficsstr); return trafficsstr; }
@PostConstruct public void init() { studyService = getService().getPort(StudyService.class); Client cl = ClientProxy.getClient(studyService); HTTPConduit httpConduit = (HTTPConduit) cl.getConduit(); httpConduit.getClient().setReceiveTimeout(getConfigurationService().getWebServiceTimeout()); httpConduit.getClient().setConnectionTimeout(0); httpConduit.getClient().setConnection(ConnectionType.CLOSE); }
public static String call(String wsdlUrl, String operationName, Object... params) throws Exception { Map<String, Object> traceMap = getTraceMapForLog(wsdlUrl, operationName, params); DynamicClientFactory dynamicClientFactory = JaxWsDynamicClientFactory.newInstance(); Client client = dynamicClientFactory.createClient(wsdlUrl); Object[] obj = client.invoke(operationName, params); String result = "" + obj[0]; return result; }
@Test public void testSaml2TokenHOK() throws Exception { // Create + configure service Service service = createService(); WSSSecurityProperties inProperties = new WSSSecurityProperties(); Properties cryptoProperties = CryptoFactory.getProperties("insecurity.properties", this.getClass().getClassLoader()); inProperties.setSignatureVerificationCryptoProperties(cryptoProperties); CustomStaxSamlValidator validator = new CustomStaxSamlValidator(); inProperties.addValidator(WSConstants.SAML_TOKEN, validator); inProperties.addValidator(WSConstants.SAML2_TOKEN, validator); WSS4JStaxInInterceptor inhandler = new WSS4JStaxInInterceptor(inProperties); service.getInInterceptors().add(inhandler); // Create + configure client Echo echo = createClientProxy(); Client client = ClientProxy.getClient(echo); client.getInInterceptors().add(new LoggingInInterceptor()); client.getOutInterceptors().add(new LoggingOutInterceptor()); Map<String, Object> properties = new HashMap<String, Object>(); properties.put(WSHandlerConstants.ACTION, WSHandlerConstants.SAML_TOKEN_SIGNED); SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler(); callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY); callbackHandler.setSignAssertion(true); properties.put(WSHandlerConstants.SAML_CALLBACK_REF, callbackHandler); properties.put(WSHandlerConstants.SIG_KEY_ID, "DirectReference"); properties.put(WSHandlerConstants.USER, "alice"); properties.put(WSHandlerConstants.PW_CALLBACK_REF, new PasswordCallbackHandler()); properties.put(WSHandlerConstants.SIG_PROP_FILE, "alice.properties"); WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor(properties); client.getOutInterceptors().add(ohandler); try { echo.echo("test"); fail("Failure expected on receiving sender vouches instead of HOK"); } catch (javax.xml.ws.soap.SOAPFaultException ex) { // expected } validator.setRequireSenderVouches(false); try { echo.echo("test"); fail("Failure expected on receiving a SAML 1.1 Token instead of SAML 2.0"); } catch (javax.xml.ws.soap.SOAPFaultException ex) { // expected } validator.setRequireSAML1Assertion(false); assertEquals("test", echo.echo("test")); }
private MetadataModelServicePortType getMMSSoapClient() throws GeneralSecurityException, IOException { MetadataModelServicePortType mmsPort = MMSSoapClientFactory.createSoapClient(MMS_URL); Client client = ClientProxy.getClient(mmsPort); client.getInInterceptors().add(new LoggingInInterceptor()); client.getOutInterceptors().add(new LoggingOutInterceptor()); return mmsPort; }
private void setupGreeter(String cfgResource, boolean useDecoupledEndpoint) throws NumberFormatException, MalformedURLException { SpringBusFactory bf = new SpringBusFactory(); controlBus = bf.createBus(); BusFactory.setDefaultBus(controlBus); ControlService cs = new ControlService(); control = cs.getControlPort(); updateAddressPort(control, PORT); assertTrue("Failed to start greeter", control.startGreeter(cfgResource)); greeterBus = bf.createBus(cfgResource); BusFactory.setDefaultBus(greeterBus); LOG.fine("Initialised greeter bus with configuration: " + cfgResource); if (null == comparator) { comparator = new PhaseComparator(); } if (null == inPhases) { inPhases = new ArrayList<Phase>(); inPhases.addAll(greeterBus.getExtension(PhaseManager.class).getInPhases()); Collections.sort(inPhases, comparator); } if (null == preLogicalPhase) { preLogicalPhase = getPhase(Phase.PRE_LOGICAL); } GreeterService gs = new GreeterService(); greeter = gs.getGreeterPort(); updateAddressPort(greeter, PORT); LOG.fine("Created greeter client."); if (!useDecoupledEndpoint) { return; } // programatically configure decoupled endpoint that is guaranteed to // be unique across all test cases decoupledEndpointPort++; decoupledEndpoint = "http://localhost:" + allocatePort("decoupled-" + decoupledEndpointPort) + "/decoupled_endpoint"; Client c = ClientProxy.getClient(greeter); HTTPConduit hc = (HTTPConduit) (c.getConduit()); HTTPClientPolicy cp = hc.getClient(); cp.setDecoupledEndpoint(decoupledEndpoint); LOG.fine("Using decoupled endpoint: " + cp.getDecoupledEndpoint()); }
private Client createClient() throws BusException, EndpointException { Client client = clientFactory.create(); final Service service = client.getEndpoint().getService(); service.setDataBinding(new SourceDataBinding()); final ServiceInfo si = service.getServiceInfos().get(0); ServiceHelper.addOperation(si, operationName, isRequestResponse); return client; }
public void configureService( String address, String pksFilename, String pksPassword, String trustPksFilename, String trustPksPassword) throws Exception { if (pksFilename != null && pksPassword != null && trustPksFilename != null && trustPksPassword != null) { System.setProperty("javax.net.ssl.keyStore", pksFilename); System.setProperty("javax.net.ssl.keyStorePassword", pksPassword); System.setProperty("javax.net.ssl.trustStore", trustPksFilename); System.setProperty("javax.net.ssl.trustStorePassword", trustPksPassword); } URL wsdlUrl = new URL(address + "?wsdl"); IoTaService service = new IoTaService(wsdlUrl); port = service.getPort(IoTaServicePortType.class); // turn off chunked transfer encoding Client client = ClientProxy.getClient(port); HTTPConduit httpConduit = (HTTPConduit) client.getConduit(); HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); httpClientPolicy.setAllowChunking(false); httpConduit.setClient(httpClientPolicy); if (pksFilename != null) { log.debug("Authenticating with certificate in file: " + pksFilename); if (!wsdlUrl.getProtocol().equalsIgnoreCase("https")) { throw new Exception("Authentication method requires the use of HTTPS"); } KeyStore keyStore = KeyStore.getInstance(pksFilename.endsWith(".p12") ? "PKCS12" : "JKS"); keyStore.load(new FileInputStream(new File(pksFilename)), pksPassword.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); keyManagerFactory.init(keyStore, pksPassword.toCharArray()); KeyStore trustStore = KeyStore.getInstance(trustPksFilename.endsWith(".p12") ? "PKCS12" : "JKS"); trustStore.load( new FileInputStream(new File(trustPksFilename)), trustPksPassword.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); trustManagerFactory.init(trustStore); TLSClientParameters tlscp = new TLSClientParameters(); tlscp.setSecureRandom(new SecureRandom()); tlscp.setKeyManagers(keyManagerFactory.getKeyManagers()); tlscp.setTrustManagers(trustManagerFactory.getTrustManagers()); httpConduit.setTlsClientParameters(tlscp); } }
void prepareRequest( String actionURI, String shellId, String messageId, HashMap<String, String> options) { // add SOAP headers List<Header> soapHeaders = getSOAPHeaders(actionURI, URI_RESOURCE_SHELL_CMD, shellId, messageId, options); Client proxy = ClientProxy.getClient(wsmanService); proxy.getRequestContext().put(Header.HEADER_LIST, soapHeaders); proxy.getRequestContext().put("SOAPAction", actionURI); transport.setupAuth(proxy); }
public void clientCreated(final Client client) { if (null == store || null == retransmissionQueue) { return; } String id = RMUtils.getEndpointIdentifier(client.getEndpoint(), getBus()); Collection<SourceSequence> sss = store.getSourceSequences(id /*, protocol*/); if (null == sss || 0 == sss.size()) { return; } LOG.log(Level.FINE, "Number of source sequences: {0}", sss.size()); recoverReliableEndpoint(client.getEndpoint(), client.getConduit() /*, protocol*/); }
public void excute() { URL wsdlURL = SBFIFATDImportAssetRetirmentSrv.WSDL_LOCATION; SBFIFATDImportAssetRetirmentSrv ss = new SBFIFATDImportAssetRetirmentSrv(wsdlURL, SERVICE_NAME); SBFIFAImportAssetRetirmentSrv port = ss.getSBFIFAImportAssetRetirmentSrvPort(); Client client = ClientProxy.getClient(port); HTTPConduit http = (HTTPConduit) client.getConduit(); HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); httpClientPolicy.setConnectionTimeout(1000000000); // 连接时间 httpClientPolicy.setReceiveTimeout(1000000000); // 接收时间 httpClientPolicy.setAllowChunking(false); http.setClient(httpClientPolicy); { System.out.println("Invoking process..."); ImportAssetRetirmentSrvRequest _process_payload = null; _process_payload = new ImportAssetRetirmentSrvRequest(); MsgHeader msgHeader = new MsgHeader(); _process_payload.setMsgHeader(msgHeader); ImportAssetRetirmentSrvInputCollection collection = new ImportAssetRetirmentSrvInputCollection(); if (srvInputItems != null) { for (int i = 0; i < srvInputItems.size(); i++) { ImportAssetRetirmentSrvInputItem inputItem = srvInputItems.get(i); collection.getImportAssetRetirmentSrvInputItem().add(inputItem); } } // 传递数据集到request中 _process_payload.setImportAssetRetirmentSrvInputCollection(collection); ImportAssetRetirmentSrvResponse _process__return = port.process(_process_payload); System.out.println( "process.result=" + _process__return.getErrorFlag() + "||" + _process__return.getErrorMessage()); returnMessage.setErrorFlag(StrUtil.nullToString(_process__return.getErrorFlag())); returnMessage.setErrorMessage(_process__return.getErrorMessage()); if (_process__return.getErrorFlag().equals("Y")) { responseItemList = _process__return.getResponseCollecion().getResponseItem(); System.out.println("结果Y: " + responseItemList); } else { errorItemList = _process__return.getErrorCollection().getErrorItem(); int s1 = errorItemList.size(); for (int i = 0; i < s1; i++) { System.out.println("结果N: " + errorItemList.get(0).getERRORMESSAGE()); } } } }
private <T> void configureWSSecurity(Dispatch<T> dispatch) { if (this.mcf.getAsSecurityType() == WSManagedConnectionFactory.SecurityType.WSSecurity) { Bus bus = BusFactory.getThreadDefaultBus(); BusFactory.setThreadDefaultBus(this.mcf.getBus()); try { Client client = ((DispatchImpl) dispatch).getClient(); Endpoint ep = client.getEndpoint(); // spring configuration file if (this.mcf.getOutInterceptors() != null) { for (Interceptor i : this.mcf.getOutInterceptors()) { ep.getOutInterceptors().add(i); } } // ws-security pass-thru from custom jaas domain Subject subject = ConnectionContext.getSubject(); if (subject != null) { WSSecurityCredential credential = ConnectionContext.getSecurityCredential(subject, WSSecurityCredential.class); if (credential != null) { if (credential.useSts()) { dispatch .getRequestContext() .put(SecurityConstants.STS_CLIENT, credential.buildStsClient(bus)); } if (credential.getSecurityHandler() == WSSecurityCredential.SecurityHandler.WSS4J) { ep.getOutInterceptors() .add(new WSS4JOutInterceptor(credential.getRequestPropterties())); ep.getInInterceptors() .add(new WSS4JInInterceptor(credential.getResponsePropterties())); } else if (credential.getSecurityHandler() == WSSecurityCredential.SecurityHandler.WSPOLICY) { dispatch.getRequestContext().putAll(credential.getRequestPropterties()); dispatch.getResponseContext().putAll(credential.getResponsePropterties()); } } // When properties are set on subject treat them as they can configure WS-Security HashMap<String, String> properties = ConnectionContext.getSecurityCredential(subject, HashMap.class); for (String key : properties.keySet()) { if (key.startsWith("ws-security.")) { // $NON-NLS-1$ ep.put(key, properties.get(key)); } } } } finally { BusFactory.setThreadDefaultBus(bus); } } }
@Override public void initialize(Client client, Bus bus) { checkZmqConfig(); Conduit conduit = client.getConduit(); if (!(conduit instanceof ZMQConduit)) { throw new ConfigurationException(new Message("ZMQCONFIGFEATURE_ONLY_ZMQ", LOG)); } Endpoint ep = client.getEndpoint(); changeTransportUriToZmq(ep); ZMQConduit zmqConduit = (ZMQConduit) conduit; zmqConduit.setZmqConfig(zmqConfig); super.initialize(client, bus); }
@Test public void testClientProxyFactory() { JaxWsProxyFactoryBean cf = new JaxWsProxyFactoryBean(); cf.setAddress("http://localhost:" + PORT + "/test"); cf.setServiceClass(Greeter.class); cf.setBus(getBus()); Configurer c = getBus().getExtension(Configurer.class); c.configureBean("client.proxyFactory", cf); Greeter greeter = (Greeter) cf.create(); Client client = ClientProxy.getClient(greeter); checkAddressInterceptors(client.getInInterceptors()); }
/** * This test ensures that the interceptor count is the same no matter how many times the decorator * is called on the constructor. */ @Test public void ensureInterceptorCountIsConstant() { CONNECTClient<TestServicePortType> client = createClient(); Client cxfClient = ClientProxy.getClient(client.getPort()); int numOutInterceptors = cxfClient.getOutInterceptors().size(); createClient(); createClient(); CONNECTClient<TestServicePortType> client2 = createClient(); Client cxfClient2 = ClientProxy.getClient(client2.getPort()); assertEquals(numOutInterceptors, cxfClient2.getOutInterceptors().size()); }
public static void method2() { JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance(); Client client = factory.createClient("http://localhost:8080/CXFWebDemo/services/hello?wsdl"); Object[] result; try { result = client.invoke("sayHello", "World"); System.out.println(result[0]); result = client.invoke("getUserByName", "Jack"); User user = (User) result[0]; System.out.println(user); } catch (Exception e) { e.printStackTrace(); } }
@RequestMapping("/getEeventData") @ResponseBody public String getEeventData(HttpServletRequest request, HttpServletResponse response) throws Exception { // Date date1 = new Date(); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // System.out.println("--------------当前时间---------" + sdf.format(date1)); // long time1 = System.currentTimeMillis(); // System.out.println("--------------当前毫秒数--------------" + System.currentTimeMillis()); if (client == null) { JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); client = dcf.createClient( "http://10.41.87.107:8280/eventdata/1.0.0?wsdl", new QName("tns", "EventService")); } Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put("Content-Type", Arrays.asList("text/xml; charset=utf-8")); headers.put("Authorization", Arrays.asList(token)); client.getRequestContext().put(Message.PROTOCOL_HEADERS, headers); Object[] objs = client.invoke("getEeventData"); // long time3 = System.currentTimeMillis(); // System.out.println("-----------时间差1-------------" + (time3 - time1)); Object o = objs[0]; StringArray sa = (StringArray) o; // Date date = new Date(); // long time2 = System.currentTimeMillis(); // System.out.println("--------------当前时间---------" + sdf.format(date)); // System.out.println("--------------当前毫秒数--------------" + System.currentTimeMillis()); // System.out.println("-----------时间差2-------------" + (time2 - time1)); Map<String, String> maps = GsonUtil.jsonToMap4String(sa.getString().get(0).toString().replace("'", "\"")); System.out.println(maps.toString()); String[] locates = maps.get("point").split(";"); List<Event> events = new ArrayList<Event>(); for (int i = 0; i < locates.length; i++) { Event event = new Event(); System.out.println(maps.get("detail")); event.setDesc(maps.get("detail")); event.setTime(maps.get("time")); String[] coordinate = locates[i].split("/"); event.setLat(coordinate[0]); event.setLon(coordinate[1]); event.setSite(coordinate[2]); events.add(event); } String data = GsonUtil.objectToJson(events); System.out.println(data); return data; }
public void init() { Bus oldbus = BusFactory.getThreadDefaultBus(); BusFactory.setThreadDefaultBus(bus); try { GreeterService service = new GreeterService(GreeterTargetBean.class.getResource("/wsdl/hello_world.wsdl")); greeter = service.getGreeterPort(); if (address != null) { ((BindingProvider) greeter) .getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, address); } client = ClientProxy.getClient(greeter); System.out.println("Greeter endpoint: " + client.getEndpoint().getEndpointInfo()); } catch (RuntimeException e) { e.printStackTrace(); throw e; } catch (Error e) { e.printStackTrace(); throw e; } finally { BusFactory.setThreadDefaultBus(oldbus); } }
public void connect(TokenHolder tokenHolder) { for (Class<? extends PublicInterface> interface1 : interfaces) { JaxWsProxyFactoryBean cpfb = new JaxWsProxyFactoryBean(); cpfb.setServiceClass(interface1); cpfb.setAddress(address + "/" + interface1.getSimpleName()); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("mtom-enabled", Boolean.TRUE); cpfb.setProperties(properties); PublicInterface serviceInterface = (PublicInterface) cpfb.create(); client = ClientProxy.getClient(serviceInterface); HTTPConduit http = (HTTPConduit) client.getConduit(); http.getClient().setConnectionTimeout(360000); http.getClient().setAllowChunking(false); http.getClient().setReceiveTimeout(320000); if (!useSoapHeaderSessions) { ((BindingProvider) serviceInterface) .getRequestContext() .put(BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE); } add(interface1.getName(), serviceInterface); } tokenHolder.registerTokenChangeListener(this); notifyOfConnect(); }
/** * This method verifies that the passed in client is configured for Ws-Security properly. * * @param client */ public void verifyWsSecurityProperties(CONNECTClient<?> client) { Client clientProxy = ClientProxy.getClient(client.getPort()); WSS4JOutInterceptor wss4jInterceptor = null; for (Interceptor<? extends Message> interceptor : clientProxy.getOutInterceptors()) { if (interceptor instanceof WSS4JOutInterceptor) { wss4jInterceptor = (WSS4JOutInterceptor) interceptor; break; } } assertNotNull(wss4jInterceptor); assertTrue(wss4jInterceptor.isAllowMTOM()); Map<String, Object> properties = wss4jInterceptor.getProperties(); new WsSecurityConfigFactoryTest().verifyWsSecurityProperties(properties); }
/** Configures SOAP interceptors for the given client. */ protected void configureInterceptors(Client client) { client.getInInterceptors().add(new Cxf3791WorkaroundInterceptor()); // WS-Addressing-related interceptors if (wsTransactionConfiguration.isAddressing()) { MustUnderstandDecoratorInterceptor interceptor = new MustUnderstandDecoratorInterceptor(); for (String nsUri : SoapUtils.WS_ADDRESSING_NS_URIS) { interceptor.addHeader(new QName(nsUri, "Action")); } client.getOutInterceptors().add(interceptor); MAPCodec mapCodec = new MAPCodec(); MAPAggregator mapAggregator = new MAPAggregator(); client.getInInterceptors().add(mapCodec); client.getInInterceptors().add(mapAggregator); client.getInFaultInterceptors().add(mapCodec); client.getInFaultInterceptors().add(mapAggregator); client.getOutInterceptors().add(mapCodec); client.getOutInterceptors().add(mapAggregator); client.getOutFaultInterceptors().add(mapCodec); client.getOutFaultInterceptors().add(mapAggregator); } if (wsTransactionConfiguration.isSwaOutSupport()) { client.getOutInterceptors().add(new ProvidedAttachmentOutInterceptor()); client.getOutInterceptors().add(new FixContentTypeOutInterceptor()); } InterceptorUtils.copyInterceptorsFromProvider(customInterceptors, client); }