EJB + Webservice error on build process - web-services

I'm a java beginner. I had use netbean for create project Java EE>Enterprise Application and create Entity Class from Database and create JPA Persistance (I'm not sure to call this). So when I create ejb already done. I will use call ejb by web service. This my problem when I use web service with out ejb class or call ejb . It can build and deploy application but when I use ejb. I got error from bulid application. Anyone can explain me for slove this problem.
This error build process
Deploying D:\Project\Source\Dev\PYS\PYSServices\PYSServices-war\dist\PYSServices-war.war
{"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"PYSServices-war.war\".POST_MODULE" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"PYSServices-war.war\".POST_MODULE: Failed to process phase POST_MODULE of deployment \"PYSServices-war.war\""}}}}
D:\Project\Source\Dev\PYS\PYSServices\PYSServices-war\nbproject\build-impl.xml:1052: The module has not been deployed.
This server log
ERROR [org.jboss.msc.service.fail] (MSC service thread 1-6) MSC00001: Failed to start service jboss.deployment.subunit."PYSServices.ear"."PYSServices-ejb.jar".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.subunit."PYSServices.ear"."PYSServices-ejb.jar".PARSE: Failed to process phase PARSE of subdeployment "PYSServices-ejb.jar" of deployment "PYSServices.ear"
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_51]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_51]
at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_51]
Caused by: org.jboss.msc.service.ServiceNotFoundException: Service service jboss.ejb.default-resource-adapter-name-service not found
at org.jboss.msc.service.ServiceContainerImpl.getRequiredService(ServiceContainerImpl.java:447) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at org.jboss.as.ejb3.deployment.processors.MessageDrivenComponentDescriptionFactory.getDefaultResourceAdapterName(MessageDrivenComponentDescriptionFactory.java:273)
at org.jboss.as.ejb3.deployment.processors.MessageDrivenComponentDescriptionFactory.processMessageBeans(MessageDrivenComponentDescriptionFactory.java:153)
at org.jboss.as.ejb3.deployment.processors.MessageDrivenComponentDescriptionFactory.processAnnotations(MessageDrivenComponentDescriptionFactory.java:81)
at org.jboss.as.ejb3.deployment.processors.AnnotatedEJBComponentDescriptionDeploymentUnitProcessor.processAnnotations(AnnotatedEJBComponentDescriptionDeploymentUnitProcessor.java:58)
at org.jboss.as.ejb3.deployment.processors.AbstractDeploymentUnitProcessor.deploy(AbstractDeploymentUnitProcessor.java:81)
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
... 5 more
This is my web service source code. My probelm it will happen when I type annotation #EJB. It can't compile and building to war file. If I not to use EJB it can building and deploy to jboss server success.
public class PysWebServices {
#Resource
WebServiceContext wsContext;
#EJB
private PysUserFacade pysUserFacade;
#WebMethod(operationName = "hello")
public String hello(#WebParam(name = "name") String txt) {
return "Hello " + txt + " !";
}
private boolean userValidate(String userid,String password, String email, String mobileno){
boolean rev = true;
if (userid != null && password != null && email != null && mobileno != null) {
if (userid.length() <5){ rev = false;}
if (password.length() < 6) { rev= false;}
if (!email.contains("#")) { rev = false;}
if (mobileno.length() != 10) {rev = false; }
} else {
rev = false;
}
return rev;
}
#WebMethod(operationName="Create User")
public String crateUser(#WebParam(name="userId") String userid,#WebParam(name="userPassword") String password, #WebParam(name="eMail") String email, #WebParam(name="mobileNo") String mobileNo){
String rev="";
MessageContext mc = wsContext.getMessageContext();
HttpServletRequest req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
String clientIP = req.getRemoteAddr();
if (userValidate(userid, password, email, mobileNo)){
PysUser eUser = new PysUser();
eUser.setUserId(userid);
eUser.setUserPassword(password);
eUser.setMobileNo(mobileNo);
eUser.setCreateIp(clientIP);
eUser.setCreateDtm(new Date());
pysUserFacade.create(eUser);
rev = "Create User Success";
} else {
rev = "Err001:Verify Create User Faile";
}
return rev;
}
}

didn't get exactly your problem, but looking at the error message i guess:
You might need to activate/enable EJB specification in your project.
Make sure you included all required annotations in your ejbs
Hope this helps

Related

AWS SecretsManager works in Eclipse, can't connect to Service Endpoint in ColdFusion

I have the following class written in Java using Eclipse on my Amazon EC2 instance.
import java.nio.ByteBuffer;
import com.amazonaws.auth.*;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.secretsmanager.*;
import com.amazonaws.services.secretsmanager.model.*;
public class SMtest {
public static void main(String[] args) {
String x = getSecret();
System.out.println(x);
}
public SMtest()
{
}
public static String getSecret() {
String secretName = "mysecret";
String endpoint = "secretsmanager.us-east-1.amazonaws.com";
String region = "us-east-1";
String result = "";
//BasicAWSCredentials awsCreds = new BasicAWSCredentials("mypublickey", "mysecretkey");
AwsClientBuilder.EndpointConfiguration config = new AwsClientBuilder.EndpointConfiguration(endpoint, region);
AWSSecretsManagerClientBuilder clientBuilder = AWSSecretsManagerClientBuilder.standard()
.withCredentials(new InstanceProfileCredentialsProvider(false));
//.withCredentials(new AWSStaticCredentialsProvider(awsCreds));
clientBuilder.setEndpointConfiguration(config);
AWSSecretsManager client = clientBuilder.build();
String secret;
ByteBuffer binarySecretData;
GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest()
.withSecretId(secretName).withVersionStage("AWSCURRENT");
GetSecretValueResult getSecretValueResult = null;
try {
getSecretValueResult = client.getSecretValue(getSecretValueRequest);
} catch(ResourceNotFoundException e) {
System.out.println("The requested secret " + secretName + " was not found");
} catch (InvalidRequestException e) {
System.out.println("The request was invalid due to: " + e.getMessage());
} catch (InvalidParameterException e) {
System.out.println("The request had invalid params: " + e.getMessage());
}
if(getSecretValueResult == null) {
result = "";
}
// Depending on whether the secret was a string or binary, one of these fields will be populated
if(getSecretValueResult.getSecretString() != null) {
secret = getSecretValueResult.getSecretString();
result = secret;
//System.out.println(secret);
}
else {
binarySecretData = getSecretValueResult.getSecretBinary();
result = binarySecretData.toString();
}
return result;
}
}
When I execute it from within Eclipse, it works just fine. When I compile the class to use it in ColdFusion (2021) from the same EC2 with the following code:
<cfscript>
obj = CreateObject("java","SMtest");
obj.init();
result = obj.getSecret();
</cfscript>
<cfoutput>#result#</cfoutput>
I get a "Failed to connect to service endpoint" error. I believe I have all the IAM credentials set up properly since it is working in straight Java. However, when I change the credentials to use the Basic Credentials with my AWS Public and Secret Key (shown in comments in the code above), it works in both Java and ColdFusion.
I created an AWS Policy that manages the Secrets Manager permissions. I also added AmazonEC2FullAccess. I also tried to create a VPC Endpoint, but this had no effect.
Why would it be working in Java and not in ColdFusion (which is based on Java) ? What roles/policies would I have to add to get it to work in ColdFusion when it is already working in Java?
STACK TRACE ADDED:
com.amazonaws.SdkClientException: Failed to connect to service endpoint:
at com.amazonaws.internal.EC2ResourceFetcher.doReadResource(EC2ResourceFetcher.java:100)
at com.amazonaws.internal.InstanceMetadataServiceResourceFetcher.getToken(InstanceMetadataServiceResourceFetcher.java:91)
at com.amazonaws.internal.InstanceMetadataServiceResourceFetcher.readResource(InstanceMetadataServiceResourceFetcher.java:69)
at com.amazonaws.internal.EC2ResourceFetcher.readResource(EC2ResourceFetcher.java:66)
at com.amazonaws.auth.InstanceMetadataServiceCredentialsFetcher.getCredentialsEndpoint(InstanceMetadataServiceCredentialsFetcher.java:58)
at com.amazonaws.auth.InstanceMetadataServiceCredentialsFetcher.getCredentialsResponse(InstanceMetadataServiceCredentialsFetcher.java:46)
at com.amazonaws.auth.BaseCredentialsFetcher.fetchCredentials(BaseCredentialsFetcher.java:112)
at com.amazonaws.auth.BaseCredentialsFetcher.getCredentials(BaseCredentialsFetcher.java:68)
at com.amazonaws.auth.InstanceProfileCredentialsProvider.getCredentials(InstanceProfileCredentialsProvider.java:165)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.getCredentialsFromContext(AmazonHttpClient.java:1266)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.runBeforeRequestHandlers(AmazonHttpClient.java:842)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:792)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:779)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:753)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:713)
at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:695)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:559)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:539)
at com.amazonaws.services.secretsmanager.AWSSecretsManagerClient.doInvoke(AWSSecretsManagerClient.java:2454)
at com.amazonaws.services.secretsmanager.AWSSecretsManagerClient.invoke(AWSSecretsManagerClient.java:2421)
at com.amazonaws.services.secretsmanager.AWSSecretsManagerClient.invoke(AWSSecretsManagerClient.java:2410)
at com.amazonaws.services.secretsmanager.AWSSecretsManagerClient.executeGetSecretValue(AWSSecretsManagerClient.java:943)
at com.amazonaws.services.secretsmanager.AWSSecretsManagerClient.getSecretValue(AWSSecretsManagerClient.java:912)
at SMtest.getSecret(SMtest.java:52)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at coldfusion.runtime.java.JavaProxy.invoke(JavaProxy.java:106)
at coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:4254)
at coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:4217)
at cfsmtest2ecfm1508275519.runPage(D:\ColdFusion2021\cfusion\wwwroot\smtest.cfm:4)
at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:257)
at coldfusion.tagext.lang.IncludeTag.handlePageInvoke(IncludeTag.java:749)
at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:578)
at coldfusion.filter.CfincludeFilter.invoke(CfincludeFilter.java:65)
at coldfusion.filter.ApplicationFilter.invoke(ApplicationFilter.java:573)
at coldfusion.filter.RequestMonitorFilter.invoke(RequestMonitorFilter.java:43)
at coldfusion.filter.MonitoringFilter.invoke(MonitoringFilter.java:40)
at coldfusion.filter.PathFilter.invoke(PathFilter.java:162)
at coldfusion.filter.IpFilter.invoke(IpFilter.java:45)
at coldfusion.filter.LicenseFilter.invoke(LicenseFilter.java:30)
at coldfusion.filter.ExceptionFilter.invoke(ExceptionFilter.java:97)
at coldfusion.filter.BrowserDebugFilter.invoke(BrowserDebugFilter.java:81)
at coldfusion.filter.ClientScopePersistenceFilter.invoke(ClientScopePersistenceFilter.java:28)
at coldfusion.filter.BrowserFilter.invoke(BrowserFilter.java:38)
at coldfusion.filter.NoCacheFilter.invoke(NoCacheFilter.java:60)
at coldfusion.filter.GlobalsFilter.invoke(GlobalsFilter.java:38)
at coldfusion.filter.DatasourceFilter.invoke(DatasourceFilter.java:22)
at coldfusion.filter.CachingFilter.invoke(CachingFilter.java:62)
at coldfusion.CfmServlet.service(CfmServlet.java:231)
at coldfusion.bootstrap.BootstrapServlet.service(BootstrapServlet.java:311)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
at coldfusion.monitor.event.MonitoringServletFilter.doFilter(MonitoringServletFilter.java:46)
at coldfusion.bootstrap.BootstrapFilter.doFilter(BootstrapFilter.java:47)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
at coldfusion.inspect.weinre.MobileDeviceDomInspectionFilter.doFilter(MobileDeviceDomInspectionFilter.java:57)
at coldfusion.bootstrap.BootstrapFilter.doFilter(BootstrapFilter.java:47)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:373)
at org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:462)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.net.MalformedURLException: Unknown protocol: http
at java.base/java.net.URL.<init>(URL.java:708)
at java.base/java.net.URL.fromURI(URL.java:748)
at java.base/java.net.URI.toURL(URI.java:1139)
at com.amazonaws.internal.ConnectionUtils.connectToEndpoint(ConnectionUtils.java:83)
at com.amazonaws.internal.EC2ResourceFetcher.doReadResource(EC2ResourceFetcher.java:80)
... 80 more
Caused by: java.lang.IllegalStateException: Unknown protocol: http
at org.apache.felix.framework.URLHandlersStreamHandlerProxy.parseURL(URLHandlersStreamHandlerProxy.java:373)
at java.base/java.net.URL.<init>(URL.java:703)
... 84 more
After noticing that the bottom end of the Stack Trace says "unknown protocol: http" and "Illegal State Exception: Unknown Protocol", I changed the endpoint in my class above to:
String endpoint = "https://secretsmanager.us-east-1.amazonaws.com";
and I am running the web-site via https now. It still works with no problem running it in Eclpse, and I am still getting the same error when using ColdFusion (i.e., when using a browser)
Since the basic credentials are working and since the error is not access denied, it suggests there is no issue with your IAM setup. Instead, likely your process failed to fetch the EC2 instance metadata. For example, timeout when calling the metadata endpoint, hence the Failed to connect to service endpoint error.
One way around this is to retrieve the accessKey and secretKey manually by calling the instance metadata API. For example, using cfhttp to populate variables.
Example curl command from docs: retrieve /api/token and use it to retrieve /meta-data/iam/security-credentials/<rolename>.
[ec2-user ~]$ TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \
&& curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access
Output:
{
"Code" : "Success",
"LastUpdated" : "2012-04-26T16:39:16Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "ASIAIOSFODNN7EXAMPLE",
"SecretAccessKey" : "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"Token" : "token",
"Expiration" : "2017-05-17T15:09:54Z"
}
From here, if you still face any errors, at least it should be more explicit to you which step has failed and why.
Just a note, AWS recommends caching the credentials until near expiry instead of querying for every transaction to avoid throttling.

Configure a service provider via code WSO2 Identity Server

I am trying to configure my WSO2 Identity Server to set up service providers via a .xml file. Here are the steps I am taking:
Paste the service provider .xml file into the $WSO2_HOME/repository/conf/identity/service-providers folder
Run the wso2server.sh script in a fresh WSO2 environment (never setup, databases with empty tables)
The .xml file I created in step 1 was created using the "export" feature from the console, so I am pretty confident it is set up correctly. Just in case, this is the code (lines with "REMOVED" were removed for privacy):
<?xml version="1.0" encoding="UTF-8"?><ServiceProvider>
<ApplicationName>__REMOVED__</ApplicationName>
<Description>__REMOVED__</Description>
<InboundAuthenticationConfig>
<InboundAuthenticationRequestConfigs>
<InboundAuthenticationRequestConfig>
<InboundAuthKey>__REMOVED__</InboundAuthKey>
<InboundAuthType>passivests</InboundAuthType>
<InboundConfigType>standardAPP</InboundConfigType>
<Properties/>
</InboundAuthenticationRequestConfig>
<InboundAuthenticationRequestConfig>
<InboundAuthKey>__REMOVED__</InboundAuthKey>
<InboundAuthType>openid</InboundAuthType>
<InboundConfigType>standardAPP</InboundConfigType>
<Properties/>
</InboundAuthenticationRequestConfig>
<InboundAuthenticationRequestConfig>
<InboundAuthKey>__REMOVED__</InboundAuthKey>
<InboundAuthType>oauth2</InboundAuthType>
<InboundConfigType>standardAPP</InboundConfigType>
<inboundConfiguration><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<oAuthAppDO>
<oauthConsumerKey>__REMOVED__</oauthConsumerKey>
<oauthConsumerSecret>__REMOVED__</oauthConsumerSecret>
<applicationName>__REMOVED__</applicationName>
<callbackUrl></callbackUrl>
<oauthVersion>OAuth-2.0</oauthVersion>
<grantTypes>client_credentials </grantTypes>
<scopeValidators/>
<pkceSupportPlain>true</pkceSupportPlain>
<pkceMandatory>false</pkceMandatory>
<userAccessTokenExpiryTime>3600</userAccessTokenExpiryTime>
<applicationAccessTokenExpiryTime>3600</applicationAccessTokenExpiryTime>
<refreshTokenExpiryTime>84600</refreshTokenExpiryTime>
<idTokenExpiryTime>3600</idTokenExpiryTime>
<audiences/>
<bypassClientCredentials>false</bypassClientCredentials>
<requestObjectSignatureValidationEnabled>false</requestObjectSignatureValidationEnabled>
<idTokenEncryptionEnabled>false</idTokenEncryptionEnabled>
<idTokenEncryptionAlgorithm>null</idTokenEncryptionAlgorithm>
<idTokenEncryptionMethod>null</idTokenEncryptionMethod>
<backChannelLogoutUrl></backChannelLogoutUrl>
<tokenType>JWT</tokenType>
</oAuthAppDO>
]]></inboundConfiguration>
<Properties/>
</InboundAuthenticationRequestConfig>
</InboundAuthenticationRequestConfigs>
</InboundAuthenticationConfig>
<LocalAndOutBoundAuthenticationConfig>
<AuthenticationSteps/>
<AuthenticationType>default</AuthenticationType>
<alwaysSendBackAuthenticatedListOfIdPs>false</alwaysSendBackAuthenticatedListOfIdPs>
<UseTenantDomainInUsername>false</UseTenantDomainInUsername>
<UseUserstoreDomainInRoles>true</UseUserstoreDomainInRoles>
<UseUserstoreDomainInUsername>false</UseUserstoreDomainInUsername>
<EnableAuthorization>false</EnableAuthorization>
</LocalAndOutBoundAuthenticationConfig>
<RequestPathAuthenticatorConfigs/>
<InboundProvisioningConfig>
<ProvisioningUserStore/>
<IsProvisioningEnabled>false</IsProvisioningEnabled>
<IsDumbModeEnabled>false</IsDumbModeEnabled>
</InboundProvisioningConfig>
<OutboundProvisioningConfig>
<ProvisioningIdentityProviders/>
</OutboundProvisioningConfig>
<ClaimConfig>
<RoleClaimURI/>
<LocalClaimDialect>false</LocalClaimDialect>
<IdpClaim/>
<ClaimMappings>
<ClaimMapping>
<LocalClaim>
<ClaimUri>http://wso2.org/claims/role</ClaimUri>
<claimId>0</claimId>
</LocalClaim>
<RemoteClaim>
<ClaimUri>roles</ClaimUri>
<claimId>0</claimId>
</RemoteClaim>
<RequestClaim>true</RequestClaim>
<MandatoryClaim>false</MandatoryClaim>
</ClaimMapping>
</ClaimMappings>
<AlwaysSendMappedLocalSubjectId>false</AlwaysSendMappedLocalSubjectId>
<SPClaimDialects/>
</ClaimConfig>
<PermissionAndRoleConfig>
<Permissions/>
<RoleMappings/>
<IdpRoles/>
</PermissionAndRoleConfig>
<IsSaaSApp>false</IsSaaSApp>
</ServiceProvider>
After the startup script completes, I don't see the service provider in the console:
Something strange I noticed - If I try to import the service provider manually using the console, I get an error on the UI reading:
Error in importing provided service provider serviceprovider#carbon.super from file
My console output says:
Caused by: org.wso2.carbon.identity.application.common.IdentityApplicationManagementException: Application with the same name loaded from the file system.
at org.wso2.carbon.identity.application.mgt.ApplicationManagementServiceImpl.doAddApplication(ApplicationManagementServiceImpl.java:1637)
at org.wso2.carbon.identity.application.mgt.ApplicationManagementServiceImpl.createApplicationWithTemplate(ApplicationManagementServiceImpl.java:169)
at org.wso2.carbon.identity.application.mgt.ApplicationManagementServiceImpl.importSPApplicationFromObject(ApplicationManagementServiceImpl.java:1025)
... 80 more
I found the source code this error is from and it is the ApplicationManagementServiceImpl.java file
if (ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(applicationName)) {
throw new IdentityApplicationManagementException(
"Application with the same name loaded from the file system.");
}
which makes a call to ApplicationManagementServiceComponent.java.
private void buildFileBasedSPList() {
String spConfigDirPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "identity"
+ File.separator + "service-providers";
FileInputStream fileInputStream = null;
File spConfigDir = new File(spConfigDirPath);
OMElement documentElement;
if (spConfigDir.exists()) {
for (final File fileEntry : spConfigDir.listFiles()) {
try {
if (!fileEntry.isDirectory()) {
fileInputStream = new FileInputStream(new File(fileEntry.getAbsolutePath()));
documentElement = new StAXOMBuilder(fileInputStream).getDocumentElement();
ServiceProvider sp = ServiceProvider.build(documentElement);
if (sp != null) {
fileBasedSPs.put(sp.getApplicationName(), sp);
}
}
} catch (Exception e) {
log.error("Error while loading idp from file system.", e);
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
log.error("Error occurred while closing file input stream for file " + spConfigDirPath, e);
}
}
The error is thrown because my service provider directory has a file with the same service provider name that is trying to be imported through the console. However, the service provider in my file system wasn't imported in the first place.
So my failure to import the service provider when the server gets configured prevents me from importing the files through the console later.
Any help is appreciated.
The service providers deployed as the file $WSO2_HOME/repository/conf/identity/service-providers folder will not be visible in the UI. But it will be active in the system. Currently the InboundAuthenticationConfig in the deployed file is not supported. But, you can have the SAML configurations in the $WSO2_HOME/repository/conf/identity/sso-idp-config.xml file.
<SSOIdentityProviderConfig>
<ServiceProviders>
.......
.......
<ServiceProvider>
<Issuer>_InboundAuthKey_</Issuer>
<AssertionConsumerServiceURLs>
<AssertionConsumerServiceURL>_url_</AssertionConsumerServiceURL>
</AssertionConsumerServiceURLs>
......
......
</ServiceProvider>
</ServiceProviders>
</SSOIdentityProviderConfig>
Here the InboundAuthKey is the value of for saml InboundAuthenticationRequestConfig
I've failed to setup service provider by storing file to $WSO2_HOME/repository/conf/identity/service-providers. OAuth2/token request always fails with error that the particular client_id is not found.
What works for me is to create python script to load XML using SOAP interface.
import zeep
from requests import Session
import os
session = Session()
#uncomment in case you use HTTPS without valid certificates
session.verify = False
transport = zeep.Transport(session=session)
def get_client(service):
base_url = 'https://{IS_SERVICE_NAME}:{IS_PORT}/services/{SERVICE}?wsdl'.format(
IS_SERVICE_NAME=os.environ["IS_SERVICE_NAME"],
IS_PORT=os.environ["IS_PORT"],
SERVICE=service)
print("Getting client %s" % base_url)
return zeep.Client(base_url, transport=transport)
def init_session():
client = get_client('AuthenticationAdmin')
client.service.login(username=os.environ["IS_USERNAME"],
password=os.environ["IS_PASSWORD"],
remoteAddress=os.environ["IS_SERVICE_NAME"])
def import_config(path):
print("Calling IdentityApplicationManagementService")
client_iam = get_client('IdentityApplicationManagementService')
with open(path) as f:
contents = f.read()
# list of available namespaces
# print client_iam.client_iam.namespaces
sp_file_content_type = client_iam.get_type('ns2:SpFileContent')
sp_file_content = sp_file_content_type(content=contents,
fileName='service-provider.xml')
client_iam.service.importApplication(sp_file_content)
if __name__ == '__main__':
assert "IS_USERNAME" in os.environ, "Define IS_USERNAME env variable"
assert "IS_PASSWORD" in os.environ, "Define IS_PASSWORD env variable"
assert "IS_SERVICE_NAME" in os.environ, "Define IS_SERVICE_NAME env variable"
assert "IS_PORT" in os.environ, "Define IS_PORT env variable"
init_session()
import_config('/conf/service-provider.xml')
This SOAP interface is enabled by setting in carbon.xml.
<HideAdminServiceWSDLs>false</HideAdminServiceWSDLs>

javax.xml.ws.WebServiceException timeout from soap request using jax-ws

I am getting the following exception when I run my build in jenkins.
Here is what I did
I created java files from running the following command
wsimport -keep -verbose http://foobar.com/ws/server?wsdl
I copied the files created to my project and used it to construct the client stubs
Here is how my client looks
public class SoapClient {
private ServiceSoap soapService;
//30 secs
private static final Integer REQUEST_TIMEOUT_MILLI = 90000;
//15 secs
private static final Integer CONNECT_TIMEOUT_MILLI = 90000;
public SoapClient(){
Service service = new Service();
service.setHandlerResolver(new JaxWsHandlerResolver());
soapService = service.getServiceSoap();
((BindingProvider)soapService).getRequestContext()
.put(BindingProviderProperties.REQUEST_TIMEOUT,REQUEST_TIMEOUT_MILLI);
((BindingProvider)soapService).getRequestContext()
.put(BindingProviderProperties.CONNECT_TIMEOUT,CONNECT_TIMEOUT_MILLI);
}
public SoapResponse processRequest(String refNum){
SoapResponse response = null;
try {
response = soapService.requestInfo(refNum);
}
catch (Exception ex){
LOG.error("error connecting to Soap service, {}",ex.getLocalizedMessage());
LOG.error(ex.getMessage());
LOG.error(ex.getCause().toString());
ex.printStackTrace();
}
return response;
}
}
I have set connection and request timeouts above. I have increased upto 10 minutes. till I see the same exception. I have included the jaxws-rt dependency in my pom.xml
Here it is
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<jaxws.version>2.2.10</jaxws.version>
</dependency>
Here is the exception I am seeing
2016-05-05 04:43:40,337 [main] ERROR foo.bar.foobar.client.SoapClient - java.net.SocketTimeoutException: Read timed out
javax.xml.ws.WebServiceException: java.net.SocketTimeoutException: Read timed out
at com.sun.xml.ws.transport.http.client.HttpClientTransport.readResponseCodeAndMessage(HttpClientTransport.java:210)
at com.sun.xml.ws.transport.http.client.HttpTransportPipe.createResponsePacket(HttpTransportPipe.java:241)
at com.sun.xml.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:232)
at com.sun.xml.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:145)
at com.sun.xml.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:110)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
at com.sun.xml.ws.client.Stub.process(Stub.java:463)
at com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:191)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:92)
at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:161)
at com.sun.proxy.$Proxy50.requestInfo(Unknown Source)
at
The exception seems to be sun related. I have read other posts. but none helped me actually. I am stuck here for two days and any help here would be much appreciated.
Thanks
EDIT
I pretty much see same issue as here. but no solution has been posted

NoClassDefFoundError org/apache/cxf/jaxrs/client/WebClient

I am new to CXF web services. I need to write a Rest Client. I am getting
java.lang.NoClassDefFoundError: org/apache/cxf/jaxrs/client/WebClient
com.test.ws.CXFWebServiceConnector.get(CXFWebServiceConnector.java:21)
com.test.ws.SimpleServlet.doGet(SimpleServlet.java:29)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
root cause
java.lang.ClassNotFoundException: org.apache.cxf.jaxrs.client.WebClient
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
com.test.ws.CXFWebServiceConnector.get(CXFWebServiceConnector.java:21)
com.test.ws.SimpleServlet.doGet(SimpleServlet.java:29)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
This is not a maven project. Below jars are added in my class path. To get the NoClassDefinition Exception am I missing any other library ?
abdera-core-0.4.0-incubating.jar
abdera-extensions-main-0.4.0-incubating.jar
abdera-i18n-0.4.0-incubating.jar
abdera-parser-0.4.0-incubating.jar
axiom-api-1.2.7.jar
axiom-impl-1.2.7.jar
cxf-2.2.6.jar
geronimo-activation-1.1.jar
geronimo-annotation-1.0.jar
jaxb-api-2.1.jar
jaxb-impl-2.1.12.jar
jra-1.0-alpha-4.jar
jsr311-api-1.0.jar
neethi-2.0.4.jar
wss4j-1.5.8.jar
wstx-asl-3.2.9.jar
xml-resolver-1.2.jar
XmlSchema-1.4.5.jar
This is the way I access the Restful web service
public String get(String url) {
String response = null;
WebClient client = WebClient.create(url);
client.accept(MediaType.APPLICATION_JSON);
HTTPConduit conduit = WebClient.getConfig(client).getHttpConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setAllowChunking(false);
conduit.setClient(httpClientPolicy);
TLSClientParameters clientParameters = new TLSClientParameters();
clientParameters.setDisableCNCheck(true);
clientParameters.setSecureSocketProtocol("TLS");
conduit.setTlsClientParameters(clientParameters);
try {
response = client.get(String.class);
} finally {
if (client != null) {
client.reset();
}
}
return response;
}
WebClient is part of cxf-rt-frontend-jaxrs.jar. You do not have cxf JAXRS related jars I guess.
Use the below command in your project root to detect which dependencies are required:
mvn dependency:tree -Dincludes=org.apache.cxf

How to use NSS with Jetty?

I am trying to setup Jetty to use NSS as its cryptographic engine. I have gotten it to the point where the server starts BUT any client that tries to connect seems to hang in the browser.
The setup process / code I am following is as follows (32-bit Windows 1.6 JVM).
NSS Database Creation
modutil.exe -create -dbdir C:\nssdb
modutil.exe -create -fips true -dbdir C:\nssdb
modutil.exe -create -changepw "NSS FIPS 140-2 Certificate DB" -dbdir C:\nssdb
Load NSS into Java
String config = "name = NSS\n";
config += "nssLibraryDirectory = C:\\nss\\lib\n";
config += "nssSecmodDirectory = C:\\nssdb\n";
config += "nssDbMode = readWrite\n";
config += "nssModule = fips";
InputStream stream = new ByteArrayInputStream(config.getBytes("UTF-8"));
Provider nss = new sun.security.pkcs11.SunPKCS11(stream);
Security.addProvider(nss);
int sunJssePosition = -1;
int currentIndex = 0;
for (Provider provider : Security.getProviders()) {
if ("SunJSSE".equals(provider.getName())) {
sunJssePosition = currentIndex + 1;
break;
}
currentIndex++;
}
Security.removeProvider("SunJSSE");
Provider sunJsse = new com.sun.net.ssl.internal.ssl.Provider(nss);
if (sunJssePosition == -1) {
Security.addProvider(sunJsse);
} else {
Security.insertProviderAt(sunJsse, sunJssePosition);
}
NSS Self Sign Certificate Generation
C:\nss\bin\certutil.exe -S -n 127.0.0.1 -x -t "u,u,u" -s "CN=127.0.0.1, OU=Foo, O=Bar, L=City, ST=NY, C=US" -m 25001 -d C:\nssdb
Jetty Startup
KeyStore ks = KeyStore.getInstance("PKCS11");
ks.load(null, "SuperSecret");
//Start setting up Jetty
Server server = new Server();
SslContextFactory sslContextFactory = new SslContextFactory();
//sslContextFactory.setKeyStoreProvider("SunPKCS11-NSS");
sslContextFactory.setKeyStore(ks);
//sslContextFactory.setKeyStorePassword(new String("SuperSecret"));
SslSelectChannelConnector sslConnector = new SslSelectChannelConnector(sslContextFactory);
sslConnector.setPort(443);
server.addConnector(sslConnector);
WebAppContext context = new WebAppContext();
//Blah Blah Blah, setup Jetty
server.setHandler(context);
server.start();
server.join();
Any ideas?
Edit: This seems extremely odd but I can access the server using Internet Explorer just fine. Firefox seems to be the one having an issue.
I have solved the issue. It turns out there are severe bugs in the Java 6 SSL implementation. The solution? Switch to Java 7!