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(); } }
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; }
@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; }
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; }
public static void method1() { // 创建 JaxWsDynamicClientFactory 工厂实例 JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance(); // 创建客户端 Client client = factory.createClient("http://localhost:8080/CXFWebDemo/services/hello?wsdl"); Object[] result; QName qname; try { // 根据指定的命名空间(接口类包名)、方法名新建QName对象 qname = new QName("http://service.cxf.elgin.com/", "sayHello"); result = client.invoke(qname, "World"); System.out.println(result[0]); qname = new QName("http://service.cxf.elgin.com/", "getUserByName"); result = client.invoke(qname, "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; }
private Object sendDocument(org.dom4j.Document doc) throws Exception { Client client = getClient(); if (null != soapHeaders) { client.getRequestContext().put(org.apache.cxf.headers.Header.HEADER_LIST, soapHeaders); } Object[] result = client.invoke(operationName, DOM4JMarshaller.documentToSource(doc)); if (result != null) { org.dom4j.Document response = DOM4JMarshaller.sourceToDocument((Source) result[0]); if (enhancedResponse) { Map<String, Object> enhancedBody = new HashMap<String, Object>(); enhancedBody.put("payload", response); enhancedBody.put( CorrelationIDFeature.MESSAGE_CORRELATION_ID, client.getResponseContext().get(CorrelationIDFeature.MESSAGE_CORRELATION_ID)); return enhancedBody; } else { return response; } } return null; }
private Object sendDocument(org.dom4j.Document doc) throws Exception { Client client = createClient(); try { Object[] result = client.invoke(operationName, DOM4JMarshaller.documentToSource(doc)); if (result != null) { return DOM4JMarshaller.sourceToDocument((Source) result[0]); } } catch (org.apache.cxf.binding.soap.SoapFault e) { SOAPFault soapFault = ServiceHelper.createSoapFault(e); if (soapFault == null) { throw new WebServiceException(e); } SOAPFaultException exception = new SOAPFaultException(soapFault); if (e instanceof Fault && e.getCause() != null) { exception.initCause(e.getCause()); } else { exception.initCause(e); } throw exception; } finally { client.destroy(); } return null; }
public void executeWorkItem(WorkItem workItem, final WorkItemManager manager) { Object[] parameters = null; String interfaceRef = (String) workItem.getParameter("Interface"); String operationRef = (String) workItem.getParameter("Operation"); String endpointAddress = (String) workItem.getParameter("Endpoint"); if (workItem.getParameter("Parameter") instanceof Object[]) { parameters = (Object[]) workItem.getParameter("Parameter"); } else if (workItem.getParameter("Parameter") != null && workItem.getParameter("Parameter").getClass().isArray()) { int length = Array.getLength(workItem.getParameter("Parameter")); parameters = new Object[length]; for (int i = 0; i < length; i++) { parameters[i] = Array.get(workItem.getParameter("Parameter"), i); } } else { parameters = new Object[] {workItem.getParameter("Parameter")}; } String modeParam = (String) workItem.getParameter("Mode"); WSMode mode = WSMode.valueOf(modeParam == null ? "SYNC" : modeParam.toUpperCase()); try { Client client = getWSClient(workItem, interfaceRef); if (client == null) { throw new IllegalStateException( "Unable to create client for web service " + interfaceRef + " - " + operationRef); } // Override endpoint address if configured. if (endpointAddress != null && !"".equals(endpointAddress)) { client.getRequestContext().put(Message.ENDPOINT_ADDRESS, endpointAddress); } switch (mode) { case SYNC: Object[] result = client.invoke(operationRef, parameters); Map<String, Object> output = new HashMap<String, Object>(); if (result == null || result.length == 0) { output.put("Result", null); } else { output.put("Result", result[0]); } logger.debug( "Received sync response {} completeing work item {}", result, workItem.getId()); manager.completeWorkItem(workItem.getId(), output); break; case ASYNC: final ClientCallback callback = new ClientCallback(); final long workItemId = workItem.getId(); final String deploymentId = nonNull(((WorkItemImpl) workItem).getDeploymentId()); final long processInstanceId = workItem.getProcessInstanceId(); client.invoke(callback, operationRef, parameters); new Thread( new Runnable() { public void run() { try { Object[] result = callback.get(asyncTimeout, TimeUnit.SECONDS); Map<String, Object> output = new HashMap<String, Object>(); if (callback.isDone()) { if (result == null) { output.put("Result", null); } else { output.put("Result", result[0]); } } logger.debug( "Received async response {} completeing work item {}", result, workItemId); RuntimeManager manager = RuntimeManagerRegistry.get().getManager(deploymentId); if (manager != null) { RuntimeEngine engine = manager.getRuntimeEngine( ProcessInstanceIdContext.get(processInstanceId)); engine .getKieSession() .getWorkItemManager() .completeWorkItem(workItemId, output); manager.disposeRuntimeEngine(engine); } else { // in case there is no RuntimeManager available use available ksession, // as it might be used without runtime manager at all ksession.getWorkItemManager().completeWorkItem(workItemId, output); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "Error encountered while invoking ws operation asynchronously", e); } } }) .start(); break; case ONEWAY: ClientCallback callbackFF = new ClientCallback(); client.invoke(callbackFF, operationRef, parameters); logger.debug( "One way operation, not going to wait for response, completing work item {}", workItem.getId()); manager.completeWorkItem(workItem.getId(), new HashMap<String, Object>()); break; default: break; } } catch (Exception e) { handleException(e); } }
public void executeWorkItem(WorkItem workItem, final WorkItemManager manager) { String implementation = (String) workItem.getParameter("implementation"); if ("##WebService".equalsIgnoreCase(implementation)) { String interfaceRef = (String) workItem.getParameter("interfaceImplementationRef"); String operationRef = (String) workItem.getParameter("operationImplementationRef"); Object parameter = workItem.getParameter("Parameter"); WSMode mode = WSMode.valueOf( workItem.getParameter("mode") == null ? "SYNC" : ((String) workItem.getParameter("mode")).toUpperCase()); try { Client client = getWSClient(workItem, interfaceRef); if (client == null) { throw new IllegalStateException( "Unable to create client for web service " + interfaceRef + " - " + operationRef); } switch (mode) { case SYNC: Object[] result = client.invoke(operationRef, parameter); Map<String, Object> output = new HashMap<String, Object>(); if (result == null || result.length == 0) { output.put("Result", null); } else { output.put("Result", result[0]); } manager.completeWorkItem(workItem.getId(), output); break; case ASYNC: final ClientCallback callback = new ClientCallback(); final long workItemId = workItem.getId(); final String deploymentId = nonNull(((WorkItemImpl) workItem).getDeploymentId()); final long processInstanceId = workItem.getProcessInstanceId(); client.invoke(callback, operationRef, parameter); new Thread( new Runnable() { public void run() { try { Object[] result = callback.get(asyncTimeout, TimeUnit.SECONDS); Map<String, Object> output = new HashMap<String, Object>(); if (callback.isDone()) { if (result == null) { output.put("Result", null); } else { output.put("Result", result[0]); } } RuntimeManager manager = RuntimeManagerRegistry.get().getManager(deploymentId); if (manager != null) { RuntimeEngine engine = manager.getRuntimeEngine( ProcessInstanceIdContext.get(processInstanceId)); engine .getKieSession() .getWorkItemManager() .completeWorkItem(workItemId, output); manager.disposeRuntimeEngine(engine); } else { // in case there is no RuntimeManager available use available ksession, // as it might be used without runtime manager at all ksession.getWorkItemManager().completeWorkItem(workItemId, output); } } catch (Exception e) { logger.error( "Error encountered while invoking ws operation asynchronously ", e); } } }) .start(); break; case ONEWAY: ClientCallback callbackFF = new ClientCallback(); client.invoke(callbackFF, operationRef, parameter); manager.completeWorkItem(workItem.getId(), new HashMap<String, Object>()); break; default: break; } } catch (Exception e) { handleException(e, interfaceRef, operationRef, parameter.getClass().getName(), parameter); } } else { executeJavaWorkItem(workItem, manager); } }
public void executeWorkItem(WorkItem workItem, final WorkItemManager manager) { Object[] parameters = null; String interfaceRef = (String) workItem.getParameter("Interface"); String operationRef = (String) workItem.getParameter("Operation"); if (workItem.getParameter("Parameter") instanceof Object[]) { parameters = (Object[]) workItem.getParameter("Parameter"); } else if (workItem.getParameter("Parameter") != null && workItem.getParameter("Parameter").getClass().isArray()) { int length = Array.getLength(workItem.getParameter("Parameter")); parameters = new Object[length]; for (int i = 0; i < length; i++) { parameters[i] = Array.get(workItem.getParameter("Parameter"), i); } } else { parameters = new Object[] {workItem.getParameter("Parameter")}; } String modeParam = (String) workItem.getParameter("Mode"); WSMode mode = WSMode.valueOf(modeParam == null ? "SYNC" : modeParam.toUpperCase()); try { Client client = getWSClient(workItem, interfaceRef); if (client == null) { throw new IllegalStateException( "Unable to create client for web service " + interfaceRef + " - " + operationRef); } switch (mode) { case SYNC: Object[] result = client.invoke(operationRef, parameters); Map<String, Object> output = new HashMap<String, Object>(); if (result == null || result.length == 0) { output.put("Result", null); } else { output.put("Result", result[0]); } logger.debug( "Received sync response {} completeing work item {}", result, workItem.getId()); manager.completeWorkItem(workItem.getId(), output); break; case ASYNC: final ClientCallback callback = new ClientCallback(); final long workItemId = workItem.getId(); client.invoke(callback, operationRef, parameters); new Thread( new Runnable() { public void run() { try { Object[] result = callback.get(asyncTimeout, TimeUnit.SECONDS); Map<String, Object> output = new HashMap<String, Object>(); if (callback.isDone()) { if (result == null) { output.put("Result", null); } else { output.put("Result", result[0]); } } logger.debug( "Received async response {} completeing work item {}", result, workItemId); ksession.getWorkItemManager().completeWorkItem(workItemId, output); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "Error encountered while invoking ws operation asynchronously", e); } } }) .start(); break; case ONEWAY: ClientCallback callbackFF = new ClientCallback(); client.invoke(callbackFF, operationRef, parameters); logger.debug( "One way operation, not going to wait for response, completing work item {}", workItem.getId()); manager.completeWorkItem(workItem.getId(), new HashMap<String, Object>()); break; default: break; } } catch (Exception e) { handleException(e); } }