IllegalArgumentException in soap webservice WSDL invoking with cxf - spring
I use springboot 2.7.0 and cxf-spring-boot-starter-jaxws 3.2.5 to call webservice interface.
But I got error:
java.lang.IllegalArgumentException: Part {https://uni.weigaoholding.com/webservices}createOrUpdateOrgRequest should be of type https.uni_weigaoholding_com.webservices.CreateOrUpdateOrgRequest, not java.lang.String
My code as below :
public static final String URL = "https://uni.xxx.com/api/v1/hr-sync/ws/webservices.wsdl";
public static final String NAMESPACE_URL = "https://uni.xxx.com/webservices";
public static final String METHOD_NAME = "createOrUpdateOrg";
public static final String PARAM_STR = "<![CDATA[<orgs> <org> <orgCode>10012168</orgCode> <name>广西医药公司</name> <shortName>广西医药公司</shortName> <parentId>10012008</parentId> <level>4</level> <order></order> <status>1</status> </org> </orgs>]]>";
public static void main(String[] args) {
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
// 创建动态客户端, URL -> 接口地址
Client client = dcf.createClient(URL);
Endpoint endpoint = client.getEndpoint();
System.out.println("ns:"+endpoint.getService().getName().getNamespaceURI());
BindingInfo bindingInfo = endpoint.getEndpointInfo().getBinding();
bindingInfo.getOperations().stream().forEach(x-> System.out.println(x.getName().getLocalPart()));
// 创建QName, NAMESPACE_URL -> 命名空间,METHOD_NAME -> 方法名
QName qName = new QName(NAMESPACE_URL, METHOD_NAME);
try {
// 接口调用 PARAM_STR -> xml参数字符串
Object[] objects = client.invoke(qName, PARAM_STR);
// 返回的数据
System.out.println(objects[0].toString());
} catch (Exception e) {
e.printStackTrace();
}
}
If I use soapUI tools,it worked.like below:
Please someone tell me the code issue, where am i wrong?
Related
Loading value from json upon start up application
I want to load the values from json file upon the Spring Boot Application is started. My code for the Configuration File is like the below: #Configuration #Getter public class FedexAPIConfig { private final static String JSON_FILE = "/static/config/fedex-api-credentials.json"; private final boolean IS_PRODUCTION = false; private FedexAPICred apiCredentials; public FedexAPIConfig() { try (InputStream in = getClass().getResourceAsStream(JSON_FILE); BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { JSONObject json = new JSONObject(); // this.apiCredentials = new JSONObject(new JSONTokener(reader)); if (IS_PRODUCTION) { json = new JSONObject(new JSONTokener(reader)).getJSONObject("production"); } else { json = new JSONObject(new JSONTokener(reader)).getJSONObject("test"); } System.out.println(json.toString()); this.apiCredentials = FedexAPICred.builder() .url(json.optString("url")) .apiKey(json.optString("api_key")) .secretKey(json.optString("secret_key")) .build(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } and with this, when the application is in progress of startup, values are successfully printed on the console.Startup console log When I tried to call this value from other ordinary class, like the below:, it brings nothing but just throws NullPointerException... What are my faults and what shall I do? public class FedexOAuthTokenManager extends OAuthToken { private static final String VALIDATE_TOKEN_URL = "/oauth/token"; private static final String GRANT_TYPE_CLIENT = "client_credentials"; private static final String GRANT_TYPE_CSP = "csp_credentials"; #Autowired private FedexAPIConfig fedexApiConfig; #Autowired private Token token; #Override public void validateToken() { // This is the part where "fedexApiConfig" is null. FedexAPICred fedexApiCred = fedexApiConfig.getApiCredentials(); Response response = null; try { RequestBody body = new FormBody.Builder() .add("grant_type", GRANT_TYPE_CLIENT) .add("client_id", fedexApiCred.getApiKey()) .add("client_secret", fedexApiCred.getSecretKey()) .build(); response = new HttpClient().post(fedexApiCred.getUrl() + VALIDATE_TOKEN_URL, body); if (response.code() == 200) { JSONObject json = new JSONObject(response.body().string()); token.setAccessToken(json.optString("access_token")); token.setTokenType(json.optString("token_type")); token.setExpiredIn(json.optInt("expires_in")); token.setExpiredDateTime(LocalDateTime.now().plusSeconds(json.optInt("expires_in"))); token.setScope(json.optString("scope")); } } catch (IOException ioe) { ioe.printStackTrace(); } } } fedexApiConfg is null even though I autowired it in prior to call. And this FedexOAuthTokenManager is called from other #Component class by new FedexOAuthTokenManager()
Did you try like below? Step 1: Create one Configuration class like below public class DemoConfig implements ApplicationListener<ApplicationPreparedEvent> { #Override public void onApplicationEvent(ApplicationPreparedEvent event) { //Load the values from the JSON file and populate the application //properties dynamically ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment(); Properties props = new Properties(); props.put("spring.datasource.url", "<my value>"); //Add more properties environment.getPropertySources().addFirst(new PropertiesPropertySource("myProps", props)); } To listen to a context event, a bean should implement the ApplicationListener interface which has just one method onApplicationEvent().The ApplicationPreparedEvent is invoked very early in the lifecycle of the application Step 2: Customize in src/main/resources/META-INF/spring.factories org.springframework.context.ApplicationListener=com.example.demo.DemoConfig Step 3: #Value in spring boot is commonly used to inject the configuration values into the spring boot application. Access the properties as per your wish. #Value("${spring.datasource.url}") private String valueFromJSon; Try this sample first in your local machine and then modify your changes accordingly. Refer - https://www.baeldung.com/spring-value-annotation Refer - https://www.knowledgefactory.net/2021/02/aws-secret-manager-service-as.html
How to implement PayUmonney in Android & how to create a Hash key in local because I don't know how to create in server
public void PayuMonney(){ **JAVA this method i am using in my code but it's not done here i am use payumonney code given to Documentation https://payumobile.gitbook.io/sdk-integration/android/payucheckoutpro. i trying too much but the toast appear in "invalid Hash"** PayUPaymentParams.Builder builder = new PayUPaymentParams.Builder(); builder.setAmount(mAmount) .setIsProduction(true) .setProductInfo(mProductInfo) .setKey(mMerchantKey) .setPhone(mPhoneNumber) .setTransactionId(mTXNId) .setFirstName(mFirstName) .setEmail(mEmailId) .setSurl("https://www.payumoney.com/mobileapp/payumoney/success.php") .setFurl("https://www.payumoney.com/mobileapp/payumoney/failure.php"); **Optional can contain any additional PG params** PayUPaymentParams payUPaymentParams = builder.build(); ***here i am calling Payuminney checkout process Sample code*** PayUCheckoutPro.open( this, payUPaymentParams, new PayUCheckoutProListener() { #Override public void onPaymentSuccess(Object response) { //Cast response object to HashMap HashMap<String,Object> result = (HashMap<String, Object>) response; String payuResponse = (String)result.get(PayUCheckoutProConstants.CP_PAYU_RESPONSE); String merchantResponse = (String) result.get(PayUCheckoutProConstants.CP_MERCHANT_RESPONSE); } #Override public void onPaymentFailure(Object response) { //Cast response object to HashMap HashMap<String,Object> result = (HashMap<String, Object>) response; String payuResponse = (String)result.get(PayUCheckoutProConstants.CP_PAYU_RESPONSE); String merchantResponse = (String) result.get(PayUCheckoutProConstants.CP_MERCHANT_RESPONSE); } #Override public void onPaymentCancel(boolean isTxnInitiated) { } #Override public void onError(ErrorResponse errorResponse) { *//code give some error toast here i the onError fuction* String errorMessage = errorResponse.getErrorMessage(); Toast.makeText(FinalPlaceOrderActivity.this, errorMessage, Toast.LENGTH_SHORT).show(); } #Override public void setWebViewProperties(#Nullable WebView webView, #Nullable Object o) { *//For setting webview properties, if any. Check Customized Integration section for more details on this* } #Override public void generateHash(HashMap<String, String> valueMap, PayUHashGenerationListener hashGenerationListener) { String hashName = valueMap.get(PayUCheckoutProConstants.CP_HASH_NAME); String hashData = valueMap.get(PayUCheckoutProConstants.CP_HASH_STRING); if (!TextUtils.isEmpty(hashName) && !TextUtils.isEmpty(hashData)) { *//Do not generate a hash from local, it needs to be calculated from server-side only. Here, hashString contains hash created from your server side. //here i am call the server file where generate a hash* StringRequest OrderPlace = new StringRequest(Request.Method.POST, "url link", new Response.Listener() { #Override public void onResponse(String response) { //here i am get hash from the server System.out.println(response); String merchandHsh = response; HashMap<String, String> dataMap = new HashMap<>(); dataMap.put(hashName, merchandHsh); hashGenerationListener.onHashGenerated(dataMap); } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "We can't process this time..", Toast.LENGTH_SHORT).show(); } } ) { #Nullable #Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> map = new HashMap<String, String>(); map.put("key", mMerchantKey); map.put("texID", mTXNId); map.put("amount", mAmount); map.put("productname", mProductInfo); map.put("name", mFirstName); map.put("email", mEmailId); return map; } }; Volley.newRequestQueue(FinalPlaceOrderActivity.this).add(OrderPlace); } } } ); } but the toast appears a "Hash invalid". this method I am using in my code but it's not done here I am using the pay money code given to Documentation https://payumobile.gitbook.io/sdk-integration/android/payucheckoutpro. I trying too much but the toast appears in "invalid Hash" How to implement PayUmonney in Android & how to create a Hash key in local because I don't know how to create in server
Error loading WSDL from resource when running in AWS Lambda
I imported a WSDL file and modified my service to read from the project's resource. #WebServiceClient(name = "MyService", targetNamespace = "http://www.myservice.com/MyService", wsdlLocation = "/documentation/wsdl/MyService.wsdl") public class MyService extends Service { private final static URL MYSERVICE_WSDL_LOCATION; private final static WebServiceException MYSERVICE_EXCEPTION; private final static QName MYSERVICE_QNAME = new QName("http://www.myservice.com/MyService", "MyService"); static { URL url = null; WebServiceException e = null; try { url = URL.class.getResource("/documentation/wsdl/MyService.wsdl"); } catch (Exception ex) { e = new WebServiceException(ex); } MYSERVICE_WSDL_LOCATION = url; MYSERVICE_EXCEPTION = e; } ... } Running locally, it works perfectly. Running on an AWS Lambda, the following error occurs: FATAL Failed to access the WSDL at: file:/documentation/wsdl/MyService.wsdl. It failed with: /documentation/wsdl/MyService.wsdl (No such file or directory). > javax.xml.ws.WebServiceException: Failed to access the WSDL at: file:/documentation/wsdl/MyService.wsdl. It failed with: /documentation/wsdl/MyService.wsdl (No such file or directory). at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.tryWithMex(RuntimeWSDLParser.java:250) What am I missing?
Removing "wsdllocation" property from #WebServiceClient and changing load resource method solve the problem: #WebServiceClient(name = "MyService", targetNamespace = "http://www.myservice.com/MyService") public class MyService extends Service { private final static URL MYSERVICE_WSDL_LOCATION; private final static WebServiceException MYSERVICE_EXCEPTION; private final static QName MYSERVICE_QNAME = new QName("http://www.myservice.com/MyService", "MyService"); static { URL url = null; WebServiceException e = null; try { url = Thread.currentThread().getContextClassLoader().getResource("documentation/wsdl/MyService.wsdl"); } catch (Exception ex) { e = new WebServiceException(ex); } MYSERVICE_WSDL_LOCATION = url; MYSERVICE_EXCEPTION = e; } ... }
How to access CSV data set config in my Java Request Sampler
I have to read data from a csv file which contains 10000+ records. I want to use this data in JMeter to hit a web service. I had written my code with the hard coded value. But I want to make it dynamic. How can I access CSV data set config in my custom Java Request Sampler...? How can I access the variable i declared in the CSV data set config in my java request sampler..? Here is my full code : #Override public SampleResult runTest(JavaSamplerContext arg0) { SampleResult result = new SampleResult(); boolean success = true; byte arr[] = new byte[] {1,49,45,1,2,(byte)214,1,1,98,0,6,0,0,9,24,0,0,0,0,0,0,0,0,0,0,0,0,0,127,(byte)255,0,21,0,16,0,75,1,0,0,58,32,2,7,0,0,4,4,0,85,81,98,0,5,14,(byte)158,0,2,0,0,0,0,0,88,82,50,69,49,83,49,86,48,67,48,0,0,1,97,75,0,84,30,12,7,17,5,7,50,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,4,6,0,0,48,49,48,48,49,48,51,48,0,0,0,0,0,0,0,0,0,0,70,48,10,29,22,85,0,1,(byte)134,(byte)160,(byte)255,(byte)255,(byte)158,(byte)170,0,0,0,67,0,0,0,0,2,0,0,12,0,12,0,12,0,12,0,13,0,12,0,13,0,12,0,13,0,12,0,13,0,13,0,12,0,12,0,12,0,12,0,13,0,12,0,13,0,13,0,12,0,13,0,13,0,12,0,13,0,13,0,12,0,13,0,13,0,13,0,12,0,13,0,13,0,13,0,14,0,13,0,12,0,13,0,13,0,13,0,13,0,12,0,13,0,13,0,13,0,14,0,13,0,13,0,13,0,12,0,13,0,13,2,(byte)158,2,(byte)159,2,(byte)241,2,(byte)234,5,48,5,68,8,90,7,(byte)193,6,15,4,10,3,100,4,(byte)224,7,47,6,72,4,(byte)170,4,4,4,7,5,16,6,107,6,114,5,(byte)195,4,(byte)179,2,(byte)198,0,13,0,13,0,13,0,14,0,13,0,13,0,14,0,13,0,14,0,13,0,13,0,14,0,13,0,13,0,14,0,13,0,14,0,13,0,14,0,13,0,14,0,13,0,13,0,101,0,99,0,(byte)129,0,(byte)129,2,81,2,(byte)224,1,(byte)153,0,(byte)30,0,31,0,14,0,13,0,14,0,13,0,14,0,14,0,13,0,14,0,13,0,14,0,14,0,21,0,86,0,98,0,51,0,72,0,104,0,(byte)144,0,(byte)175,0,(byte)174,0,(byte)174,2,20,4,(byte)132,4,103,5,96,0,126,0,14,0,14,0,14,0,14,0,14,0,15,0,14,0,14,0,14,0,14,0,14,0,85,1,41,1,104,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,13,0,14,0,14,0,14,0,13,0,14,0,13,0,14,0,13,0,14,0,13,0,14,0,13,0,14,0,14,0,13,0,14,0,13,0,13,0,13,0,13,0,13,0,12,0,13,0,13,0,14,0,13,0,13,0,13,0,13,0,13,0,13,0,13,0,14,0,13,0,13,0,14,0,13,0,13,0,14,0,13,0,13,0,13,0,13,0,13,0,(byte)226,0,(byte)223,0,(byte)223,0,15,0,14,0,13,0,115,0,(byte) 223,(byte)162,40,38,85,115,101,114,78,97,109,101,61,101,82,101,103,38,85,115,101,114,80,97,115,115,119,111,114,100,61,97,98,99,49,50,51}; try { URL obj = new URL(POST_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); result.sampleStart(); OutputStream os = con.getOutputStream(); os.write(arr); os.flush(); os.close(); result.sampleEnd(); int responseCode = con.getResponseCode(); System.out.println("POST Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { //success BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result System.out.println(response.toString().getBytes()); } else { System.out.println("POST request not worked"); } } catch(Exception E) { } // result.setSuccessful(success); return result; } #Override public Arguments getDefaultParameters() { Arguments dp=new Arguments(); return dp; } #Override public void setupTest(JavaSamplerContext context) {} #Override public void teardownTest(JavaSamplerContext context) { }
Normally you should be able to access JMeter Variables like: String myVar = JMeterContextService.getContext().getVariables().get("your_variable_name_here"); However if you don't want to have it hard-coded you might consider moving the configuration to Java Request Sampler GUI like: String valueFromCsv = ""; String defaultValue = "insert_jmeter_variable_here"; #Override public Arguments getDefaultParameters() { Arguments dp = new Arguments(); dp.addArgument("hexData", "insert_jmeter_variable_here"); return dp; } #Override public void setupTest(JavaSamplerContext context) { valueFromCsv = context.getParameter("hexData", defaultValue ); } This way you will be able to control the parameter value directly from JMeter GUI. References: JMeterContextService JavaDoc Java Request Sampler documentation Extending JMeter Beanshell vs JSR223 vs Java JMeter Scripting: The Performance-Off You've Been Waiting For!
A full java sampler solution with CSV data: courtesy - https://dzone.com/articles/implement-custom-jmeter-samplers Created a class public class VDCSampler extends AbstractJavaSamplerClient implements Serializable { private static final String ARG1_IDATE = "idate"; private String attrib1; #Override public Arguments getDefaultParameters() { Arguments defaultParameters = new Arguments(); defaultParameters.addArgument(ARG1_IDATE, attrib1); return defaultParameters; } #Override public void setupTest(JavaSamplerContext javaSamplerContext) { attrib1 = javaSamplerContext.getParameter(ARG1_IDATE, attrib1); } #Override public SampleResult runTest(JavaSamplerContext javaSamplerContext) { VDCFunctionalitySampling functionalityForSampling = new VDCFunctionalitySampling(); SampleResult sampleResult = new SampleResult(); sampleResult.sampleStart(); try { String message = functionalityForSampling.testFunction(attrib1); } }
getting a 401 error on connecting to linkedin rest api with volley
I am trying to get email address of a user through linkedin's rest api. I am using volley for the request. But it shows 401 error. Can anyone help me through this. Below is the code. Access token is for r_basicprofile and r_emailaddress permissions private static final String PROFILE_URL = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address)"; private static final String OAUTH_ACCESS_TOKEN_PARAM ="oauth2_access_token"; private static final String QUESTION_MARK = "?"; private static final String EQUALS = "="; private static final String HEADER_CONTENT_TYPE = "Content-Type"; private static final String HEADER_AUTHORIZATION = "Authorization"; private static final String HEADER_SRC = "x-li-src"; private static final String HEADER_LI_FORMAT = "x-li-format"; private static final String HEADER_LI_VER = "x-li-msdk-ver"; private static final String CONTENT_VALUE = "application/json"; private static final String HEADER_SRC_VALUE = "msdk"; private static final String HEADER_LI_FORMAT_VALUE = "json"; private TextView welcomeText; private ProgressDialog pd; String accessToken; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fflifind_friends); welcomeText = (TextView) findViewById(R.id.activity_profile_welcome_text); //Request basic profile of the user SharedPreferences preferences = this.getSharedPreferences("user_info", 0); accessToken = preferences.getString("accessToken", null); if(accessToken!=null){ String profileUrl = getProfileUrl(accessToken); Log.d("profile url", profileUrl); // new GetProfileRequestAsyncTask().execute(profileUrl); doServer(profileUrl); } } private Map<String, String> getLiHeaders(String accessToken) { HashMap<String, String> headers = new HashMap<String, String>(); headers.put(HEADER_CONTENT_TYPE, CONTENT_VALUE); headers.put(HEADER_AUTHORIZATION, "Bearer " + accessToken); headers.put(HEADER_SRC, HEADER_SRC_VALUE); headers.put(HEADER_LI_FORMAT, HEADER_LI_FORMAT_VALUE); //headers.put(HEADER_LI_VER, BuildConfig.MSDK_VERSION); return headers; } private static final String getProfileUrl(String accessToken){ String url = PROFILE_URL + QUESTION_MARK + OAUTH_ACCESS_TOKEN_PARAM + EQUALS + accessToken; return url; } public void doServer(String url) { final ProgressDialog dialog = ProgressDialog.show(this, null, "Loading data "); JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.POST, url, null, new Response.Listener<JSONObject>() { #Override public void onResponse(JSONObject response) { dialog.dismiss(); Log.d("Jsonres-", response.toString()); } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { dialog.dismiss(); // TODO Auto-generated method stub Log.d("error ","err"); Toast.makeText(getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } }){ #Override public Map<String, String> getHeaders() throws AuthFailureError { return getLiHeaders(accessToken); } }; NetworkRequestQueue.getInstance(this).addToRequestQueue(jsObjRequest); }
Use this method to get the profile information of linkedin account and define what you want from profile in PROFILE_LINK string mention below it's working fine for me.I hope its solved your problem. public static final String HOST="https://api.linkedin.com/"; public static final String PROFILE_LINK=HOST+"v1/people/~:(id,firstName,lastName,picture-url)?oauth2_access_token="; public static final String JSON_FORMAT=AMPERSAND+"format=json"; private void profileRequestAsyncTask(final String accessToken) { showProgressDialog(); // Instantiate the RequestQueue. RequestQueue queue = Volley.newRequestQueue(activity); String url=PROFILE_LINK+accessToken+JSON_FORMAT; // Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { #Override public void onResponse(String response) { // Display the first 500 characters of the response string. Log.e(TAG, "onResponse: "+response ); JSONObject dataAsJson= null; try { dataAsJson = new JSONObject(response); String id=dataAsJson.getString("id"); String firstName=dataAsJson.getString("firstName"); String lastName=dataAsJson.getString("lastName"); String pictureUrl=dataAsJson.getString("pictureUrl"); Log.e(TAG, "onResponse: "+id+"="+firstName+"-"+lastName+"-"+pictureUrl ); String username=firstName+" "+lastName; insertLinkedinAccount(id,username,pictureUrl,accessToken,expires); editor.clear(); editor.commit(); } catch (JSONException e) { e.printStackTrace(); } //Log.e(TAG, "onApiSuccess:profileData- "+firstName+"-"+lastName+"-"+profileId); } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "onErrorResponse: "+error ); } }); // Add the request to the RequestQueue. queue.add(stringRequest); }