I'm trying to execute aws device farm example code that we can get below site.
https://docs.aws.amazon.com/devicefarm/latest/testgrid/getting-started-local.html
// Import the AWS SDK for Java 2.x Device Farm client:
...
// in your tests ...
public class MyTests {
// ... When you set up your test suite
private static RemoteWebDriver driver;
#Before
void setUp() {
String myProjectARN = "...";
DeviceFarmClient client = DeviceFarmClient.builder().region(Region.US_WEST_2).build();
CreateTestGridUrlRequest request = CreateTestGridUrlRequest.builder()
.expiresInSeconds(300)
.projectArn(myProjectARN)
.build();
CreateTestGridUrlResponse response = client.createTest.GridUrl(request);
URL testGridUrl = new URL(response.url());
// You can now pass this URL into RemoteWebDriver.
WebDriver driver = new RemoteWebDriver(testGridUrl, DesiredCapabilities.firefox());
}
#After
void tearDown() {
// make sure to close your WebDriver:
driver.quit();
}
}
After executing above codes, the error was occurred and the message is like this.
java.net.UnknownHostException: devicefarm.us-westt-2.amazonaws.com
I guess the code can't resolve host because of proxy server.
How can i resolve this problem?
Thanks.
Can you please confirm which line throws java.net.UnknownHostException: devicefarm.us-westt-2.amazonaws.com. Is it client.createTest.GridUrl(request) or WebDriver driver = new RemoteWebDriver(testGridUrl, DesiredCapabilities.firefox());
If it is the client.createTest.GridUrl(request), then please follow Proxy Configuration mentioned at https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/section-client-configuration.html
My current setUp method is like this.
#Before
public void setUp() {
try {
ProxyConfiguration.Builder proxyConfig = ProxyConfiguration.builder();
proxyConfig.endpoint(new URI("<YOUR PROXY URL>"));
proxyConfig.username("<YOUR USER ID>");
proxyConfig.password("YOUR PASSWORD");
ApacheHttpClient.Builder httpClientBuilder =
ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig.build());
String myARN = "<YOUR ARN>";
DeviceFarmClient client = DeviceFarmClient.builder()
.credentialsProvider(DefaultCredentialsProvider.create())
.region(Region.US_WEST_2)
.httpClientBuilder(httpClientBuilder)
.overrideConfiguration(ClientOverrideConfiguration.builder().build())
.build();
CreateTestGridUrlRequest request = CreateTestGridUrlRequest.builder()
.expiresInSeconds(300) // 5 minutes
.projectArn(myARN)
.build();
URL testGridUrl = null;
CreateTestGridUrlResponse response = client.createTestGridUrl(request);
testGridUrl = new URL(response.url());
driver = new RemoteWebDriver(testGridUrl, DesiredCapabilities.chrome());
} catch (Exception e) {
e.printStackTrace();
}
}
Thank you again.
Related
public class UserRegistrationCustomEventHandler extends AbstractEventHandler {
JSONObject jsonObject = null;
private static final Log log = LogFactory.getLog(UserRegistrationCustomEventHandler.class);
#Override
public String getName() {
return "customClaimUpdate";
}
if (IdentityEventConstants.Event.POST_SET_USER_CLAIMS.equals(event.getEventName())) {
String tenantDomain = (String) event.getEventProperties()
.get(IdentityEventConstants.EventProperty.TENANT_DOMAIN);
String userName = (String) event.getEventProperties().get(IdentityEventConstants.EventProperty.USER_NAME);
Map<String, Object> eventProperties = event.getEventProperties();
String eventName = event.getEventName();
UserStoreManager userStoreManager = (UserStoreManager) eventProperties.get(IdentityEventConstants.EventProperty.USER_STORE_MANAGER);
// String userStoreDomain = UserCoreUtil.getDomainName(userStoreManager.getRealmConfiguration());
#SuppressWarnings("unchecked")
Map<String, String> claimValues = (Map<String, String>) eventProperties.get(IdentityEventConstants.EventProperty
.USER_CLAIMS);
String emailId = claimValues.get("http://wso2.org/claims/emailaddress");
userName = "USERS/"+userName;
JSONObject json = new JSONObject();
json.put("userName",userName );
json.put("emailId",emailId );
log.info("JSON:::::::"+json);
// Sample API
//String apiValue = "http://192.168.1.X:8080/SomeService/user/updateUserEmail?email=sujith#gmail.com&userName=USERS/sujith";
try {
URL url = new URL(cityAppUrl) ;
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
log.info("CONN:::::::::::::"+con);
OutputStream os = con.getOutputStream();
os.write(cityAppUrl.toString().getBytes("UTF-8"));
os.close();
InputStream in = new BufferedInputStream(con.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
jsonObject = new JSONObject(result);
log.info("JSON OBJECT:::::::::"+jsonObject);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void init(InitConfig configuration) throws IdentityRuntimeException {
super.init(configuration);
}
#Override
public int getPriority(MessageContext messageContext) {
return 250;
}
}
I'm using wso2 identity server 5.10.0 and have to push the updated claim value to an API so I'm using a custom handler and have subscribed to POST_SET_USER_CLAIMS, i have to read the API value from deployment.toml file in jave code of the custom handler. So can any one please help here to read the value from deployment file
I can fetch the updated claim value in logs but im not able to get the API value. So can anyone help me here to read the value from deployment file.
Since the API path is required inside your custom event handler, let's define the API path value as one of the properties of the event handler.
Add the deployment.toml config as follows.
[[event_handler]]
name= "UserRegistrationCustomEventHandler"
subscriptions =["POST_SET_USER_CLAIMS"]
properties.apiPath = "http://192.168.1.X:8080/SomeService/user/updateUserEmail"
Once you restart the server identity-event.properties file populates the given configs.
In your custom event handler java code needs to read the config from identity-event.properties file. The file reading is done at the server startup and every config is loaded to the memory.
By adding this to your java code, you can load to configured value in the property.
configs.getModuleProperties().getProperty("UserRegistrationCustomEventHandler.apiPath")
NOTE: property name needs to be defined as <event_handler_name>.<property_name>
Here is a reference to such event hanlder's property loading code snippet https://github.com/wso2-extensions/identity-governance/blob/68e3f2d5e246b6a75f48e314ee1019230c662b55/components/org.wso2.carbon.identity.password.policy/src/main/java/org/wso2/carbon/identity/password/policy/handler/PasswordPolicyValidationHandler.java#L128-L133
I have created an API Gateway with a Web Socket on AWS. I would like to connect to it using the HttpClient provided by VertX. I am using the following code for the client verticle:
public class WebSocketClient extends AbstractVerticle {
// application address replaced by [address]
protected final String host = "[address].execute-api.us-east-1.amazonaws.com";
protected final String path = "/dev";
protected final int port = 80;
protected final String webSocketAddress = "wss://[address].execute-api.us-east-1.amazonaws.com/dev";
#Override
public void start() throws Exception {
startClient(this.vertx);
}
protected void startClient(Vertx vertx) {
HttpClient client = vertx.createHttpClient();
client.webSocket(port, host, path, asyncWebSocket -> {
if (asyncWebSocket.succeeded()) {
WebSocket socket = asyncWebSocket.result();
System.out.println("Successfully connected. Node closing.");
socket.close().onFailure(throwable -> {
throwable.printStackTrace();
});
} else {
asyncWebSocket.cause().printStackTrace();
}
});
}
}
The same code works when I am testing it with a VertX server running on the localhost, so I assume that it is a question of the correct WebSocketConnectionOptions.
When I try to connect to the AWS socket using the HttpClient verticle, I get a "connection refused" error. Connecting to it using wscat works without problems.
Thanks a lot for your help.
This question is dealing with basically the same problem. I will post the solution here just to document a straight-forward way to use AWS ApiGateway Websockets with VertX.
So, the goal is to implement a VertX WebClient connected to a deployed AWS Api WebSocket Gateway which can be reached under the WsUri "wss://[address].execute-api.us-east-1.amazonaws.com/dev" (you will have to replace [address] by the address of your ApiGateway Websocket).
Here the code to set up the WebClient, connect to the Websocket, print out a success message, and then disconnect again:
public class WebSocketClient extends AbstractVerticle {
protected final String webSocketUrl = "wss://[address].execute-api.us-east-1.amazonaws.com/dev"
protected final String host = "[address].execute-api.us-east-1.amazonaws.com";
protected final String path = "/dev";
protected final int sslPort = 443;
#Override
public void start() throws Exception {
startClient(this.vertx);
}
protected void startClient(Vertx vertx) {
HttpClient client = vertx
.createHttpClient(new
HttpClientOptions().setDefaultHost(host).setDefaultPort(sslPort).setSsl(true));
// connect to the web socket
client.webSocket(path, asyncWebSocket -> {
if (asyncWebSocket.succeeded()) {
// executed on a successful connection
WebSocket socket = asyncWebSocket.result(); // use this for further communication
System.out.println("Successfully connected. Closing the socket.");
// Closing the socket
socket.close().onFailure(throwable -> {
throwable.printStackTrace();
});
} else {
// executed if the connection attempt fails
asyncWebSocket.cause().printStackTrace();
}
});
}
You can use the following class to run the example:
public class PlayWebSocket {
public static void main(String[] args) throws URISyntaxException{
Vertx vertx = Vertx.vertx();
WebSocketClient clientVerticle = new WebSocketClient();
vertx.deployVerticle(clientVerticle);
}
}
On the Java side, this should print the message about the successful connection and the closing of the socket. On the AWS side, the $connect and the $disconnect methods of the ApiGateway should be called. You can check this in the logs of your handler function(s) using CloudWatch.
I've added connected service via Microsoft WCF Web Service Reference Provider (see picture) proxy class has been successfuly created.
Then, when I try execute sample method from this web service (client.TestLanguageAsync() - which returns string) I get null reference exception - but I dont know what is null, because details of exception are very poor (look on picture). Below is code.
private async void BtnTest_Clicked(object sender, EventArgs e) {
try {
var endpoint = new EndpointAddress("https://f9512056.f95.ficosa.com/WMS/WMSWebService.asmx");
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport) {
Name = "basicHttpBinding",
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647
};
TimeSpan timeout = new TimeSpan(0, 0, 30);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
WMSWebServiceSoapClient client = new WMSWebServiceSoapClient(binding, endpoint);
string text = await client.TestLanguageAsync(); //This causes exception
label.Text = text;
} catch (Exception E) {
label.Text = E.ToString();
}
}
Look also on screen
Adding service reference and exception screen
Any ideas? Thanks in advance:)
I am developing a Java client which will create an application in WSO2 Identity Server through calling the OAuthAdminService. After some digging I found that registerOAuthApplicationData() method is the one used for creating an application in IS. Before calling the method, I have authenticated the admin user via login() method of AuthenticationAdminStub type. Even after such authentication the registerOAuthApplicationData() method make the IS console to print
[2016-04-26 13:08:52,577] WARN
{org.wso2.carbon.server.admin.module.handler.AuthenticationHandler} -
Illegal access attempt at [2016-04-26 13:08:52,0577] from IP address
127.0.0.1 while trying to authenticate access to service OAuthAdminService
and the application is not getting created in the IS database.
The code which I have tried goes as follows
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.wso2.carbon.authenticator.proxy.AuthenticationAdminStub;
import org.wso2.carbon.identity.oauth.OAuthAdminServicePortTypeProxy;
import org.wso2.carbon.identity.oauth.dto.xsd.OAuthConsumerAppDTO;
public class IdentityClientOne {
private final static String SERVER_URL = "https://localhost:9443/services/";
private final static String APP_ID = "myapp";
/**
* #param args
*/
public static void main(String[] args) {
AuthenticationAdminStub authstub = null;
ConfigurationContext configContext = null;
System.setProperty("javax.net.ssl.trustStore", "wso2carbon.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
try {
configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
"repo", "repo/conf/client.axis2.xml");
authstub = new AuthenticationAdminStub(configContext, SERVER_URL
+ "AuthenticationAdmin");
// Authenticates as a user having rights to add users.
if (authstub.login("admin", "admin", APP_ID)) {
System.out.println("admin authenticated");
OAuthConsumerAppDTO consumerApp = new OAuthConsumerAppDTO("Oauth-2.0",
"sample_app",
"",
"authorization_code implicit password client_credentials refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer iwa:ntlm","","","");
OAuthAdminServicePortTypeProxy OAuthAdminProxy = new OAuthAdminServicePortTypeProxy();
OAuthAdminProxy.registerOAuthApplicationData(consumerApp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Please help what should be done right ?
You have to access the stub via the authenticated session.
Could you try below.
public class Test {
private final static String SERVER_URL = "https://localhost:9443/services/";
public static void main(String[] args) throws RemoteException, OAuthAdminServiceException {
OAuthAdminServiceStub stub = new OAuthAdminServiceStub(null, SERVER_URL + "OAuthAdminService");
ServiceClient client = stub._getServiceClient();
authenticate(client);
OAuthConsumerAppDTO consumerAppDTO = new OAuthConsumerAppDTO();
consumerAppDTO.setApplicationName("sample-app");
consumerAppDTO.setCallbackUrl("http://localhost:8080/playground2/oauth2client");
consumerAppDTO.setOAuthVersion("OAuth-2.0");
consumerAppDTO.setGrantTypes("authorization_code implicit password client_credentials refresh_token "
+ "urn:ietf:params:oauth:grant-type:saml2-bearer iwa:ntlm");
stub.registerOAuthApplicationData(consumerAppDTO);
}
public static void authenticate(ServiceClient client) {
Options option = client.getOptions();
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername("admin");
auth.setPassword("admin");
auth.setPreemptiveAuthentication(true);
option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
option.setManageSession(true);
}
}
Getting Error while consuming webservices in java through SOAP approach. Plz suggest, i am stuck in this for last 10 days. I am using this server for webservices "http://www.webservicex.net/globalweather.asmx"
Error:
Exception in thread "main" [SOAPException: faultCode=SOAP-ENV:Client; msg=Error
opening socket: Connection timed out: connect;
targetException=java.lang.IllegalArgumentException: Error opening
socket: Connection timed out: connect]
at org.apache.soap.transport.http.SOAPHTTPConnection.se(SOAPHTTPConnection.java:324)
at org.apache.soap.rpc.Call.invoke(Call.java:205)
at com.check.ClientNet.main(ClientNet.java:47)
My java code is :
package com.check;
import java.net.*;
import java.util.*;
import org.apache.soap.*;
import org.apache.soap.encoding.SOAPMappingRegistry;
import org.apache.soap.rpc.*;
import org.apache.soap.encoding.soapenc.StringDeserializer;
import org.apache.soap.util.xml.QName;
import com.check.ProxyAuthenticator;
public class ClientNet {
public static void main (String[] args)
throws Exception {
Properties properties = System.getProperties();
properties.put("http.proxyHost", "10.136.236.30");
properties.put("http.proxyPort", "8080");
properties.put("http.proxyUser", "bnkishore");
properties.put("http.proxyPassword","XXXX");
Properties newprops = new Properties(properties);
System.setProperties(newprops);
String username = System.getProperty("http.proxyUser");
String password = System.getProperty("http.proxyPassword");
if (username != null && !username.equals("")) {
Authenticator.setDefault(new ProxyAuthenticator(username, password));
}
System.out.println("\n\nCalling the SOAP Server:\n\n");
//http://www.webservicex.net/globalweather.asmx
URL url = new URL ("http://www.webservicex.net/globalweather.asmx");
String CountryName = "India";
Call call = new Call();
SOAPMappingRegistry soapMappingRegistry = new SOAPMappingRegistry();
soapMappingRegistry.mapTypes(Constants.NS_URI_SOAP_ENC, new QName("http://www.webserviceX.NET", "globalweather"),null,null, new StringDeserializer());
call.setTargetObjectURI("http://www.webserviceX.NET");
call.setMethodName("GetCitiesByCountry");
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
Vector<Parameter> params = new Vector<Parameter>();
params.addElement(new Parameter("CountryName", String.class, CountryName, null));
call.setParams (params);
System.out.print("The SOAP Server says: ");
Response resp = call.invoke(url, " ");
if (resp.generatedFault()) {
Fault fault = resp.getFault();
System.out.println("\nOuch, the call failed: ");
System.out.println(" Fault Code = " + fault.getFaultCode());
System.out.println(" Fault String = " + fault.getFaultString());
} else {
Parameter result = resp.getReturnValue();
System.out.print(result.getValue());
System.out.println();
}
}
}
And ProxyAuthencator code is :
package com.check;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class ProxyAuthenticator extends Authenticator {
private String userName, passWord;
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName,passWord.toCharArray());
}
public ProxyAuthenticator(String userName, String password) {
this.userName = userName;
this.passWord = password;
getPasswordAuthentication();
}
}
Thanks.
There is a timeout, that means you client is not reaching the server. Check connectivity. For dealing with a proxy, additionally to your ProxyAuthenticator you need to add few system properties: proxySet, proxyHost and proxyPort. If you are using maven, you can do it in this way:
mvn jetty:run -DproxySet=true -DproxyHost=proxy.indra.es -DproxyPort=8080