I am using the Amazon Java SDK (that latest is version 1.11.147 as of this writing) with Groovy (Groovy Version: 2.4.11 JVM: 1.8.0_112 Vendor: Oracle Corporation OS: Mac OS X) to upload files to S3. Using the instructions from Amazon's documentation for a Transfer Manager, I was able to copy contents from one bucket to another. However, uploading always fails. I attempted the the following 3 methods. I have Grapes grab new versions of httpclient and httpcore because of what I read at the this Stack Overflow Post Apache PoolingHttpClientConnectionManager throwing illegal state exception
#Grapes([
#Grab(group='com.amazonaws', module='aws-java-sdk', version='1.11.147'),
// https://mvnrepository.com/artifact/org.apache.commons/commons-compress
#Grab(group='org.apache.commons', module='commons-compress', version='1.13'),
// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
#Grab(group='org.apache.httpcomponents', module='httpclient', version='4.5.3'),
// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore
#Grab(group='org.apache.httpcomponents', module='httpcore', version='4.4.6')
])
// creds is String saying which ~/.aws/credentials profile to use
def credentials = new ProfileCredentialsProvider(creds)
def s3client = AmazonS3ClientBuilder.standard().
withCredentials(credentials).
withRegion(region).
build()
def tx = TransferManagerBuilder.standard().
withS3Client(s3client).
build()
def config_path = "/path/to/my/root"
def dir = "key_path"
def f = new File("${config_path}/${dir}/")
// Method 1, upload whole directory in one call
def mfu = tx.uploadDirectory(data_bucket, dir, f, true)
mfu.waitForCompletion() // <-- throws exception, w/o this line, just doesn't upload, but script continues
// Method 2, upload each file separately
def ld
ld = { File file ->
file.listFiles().each { g ->
if (g.isDirectory()) {
ld.call(g)
} else {
def key = g.toString().substring(config_path_length)
def fu = tx.upload(data_bucket, key, g)
def fu = tx.upload(data_bucket, key, g)
fu.waitForCompletion() // <-- throws exception, w/o this line, just doesn't upload, but script continues
}
}
}
ld.call(f)
// Finally Method 3, avoiding TransferManager altogether, and call putObject directly on each file
def ld
ld = { File file ->
file.listFiles().each { g ->
if (g.isDirectory()) {
ld.call(g)
} else {
def key = g.toString().substring(config_path_length)
def fu = tx.upload(data_bucket, key, g)
s3client.putObject(new PutObjectRequest(data_bucket, key, g)) // <-- throws exception
}
}
}
ld.call(f)
However, no matter which method I try, I always get the following stacktrace:
Caught: java.lang.IllegalStateException: Connection pool shut down
java.lang.IllegalStateException: Connection pool shut down at
org.apache.http.util.Asserts.check(Asserts.java:34) at
org.apache.http.pool.AbstractConnPool.lease(AbstractConnPool.java:184)
at
org.apache.http.impl.conn.PoolingHttpClientConnectionManager.requestConnection(PoolingHttpClientConnectionManager.java:251)
at
com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler.invoke(ClientConnectionManagerFactory.java:76)
at com.amazonaws.http.conn.$Proxy11.requestConnection(Unknown Source)
at
org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:175)
at
org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
at
org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at
org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at
org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
at
com.amazonaws.http.apache.client.impl.SdkHttpClient.execute(SdkHttpClient.java:72)
at
com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1190)
at
com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1030)
at
com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:742)
at
com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:716)
at
com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
at
com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
at
com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
at
com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
at
com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4221)
at
com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4168)
at
com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:1718)
at com.amazonaws.services.s3.AmazonS3$putObject.call(Unknown Source)
...
I am unable at this time to confirm whether groovy is using the updated httpcomponent libraries, or if that is the problem. Installed in the 1.8 JDK are httpclient_4.2.6 and httpclient_4.3.5. Any suggestions for how to get unstuck would be greatly appreciated. Thank you. -Vincent
I figured it out. the s3client had another TranferManager attached to it elsewhere in the code. when tx.shutdownNow() was called, it closed this TransferManager as well.
Related
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.
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>
I am trying to upload an image to AWS S3.
The web app runs in my local desktop in tomcat server.
When I upload the image from server, I see the file details in http request multipart file , I'm able to get its size and details.
This is how I set up connection
File convFile = new File( file.getOriginalFilename());
file.transferTo(convFile);
AmazonS3 s3 = AmazonS3ClientBuilder.standard()
.withRegion(Regions.US_WEST_2) //regionName is a string for a region not supported by the SDK yet
.withCredentials(new AWSStaticCredentialsProvider
(new BasicAWSCredentials("key", "accessId")))
// .setEndpointConfiguration(new EndpointConfiguration("https://s3.console.aws.amazon.com", "us-west-1"))
.enablePathStyleAccess()
.disableChunkedEncoding()
.build();
s3.putObject(new PutObjectRequest(bucketName, "key", convFile));
I tried two methodologies.
1) Converting Multipart file to java.io.File and uploading
Error: com.amazonaws.SdkClientException: Unable to calculate MD5 hash: MyImage.png (No such file or directory)
2) Sending the image as bytestream
Error: I am getting java.io.FileNotFound Exception: /path/to/tomcat/MyImage.tmp not found
The actual image name is MyImage.png.
Either method I try, I get exception.
Ok. There were several issues.
I mis typed the Region for a different set of keys.
But still the issues was happening and I went back to 1.11.76 version. And still there were some issues and this is how I fixed.
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType(file.getContentType());
byte[] contentBytes = null;
try {
InputStream is = file.getInputStream();
contentBytes = IOUtils.toByteArray(is);
} catch (IOException e) {
System.err.printf("Failed while reading bytes from %s", e.getMessage());
}
Long contentLength = Long.valueOf(contentBytes.length);
objectMetadata.setContentLength(contentLength);
objectMetadata.setHeader("filename", fileNameWithExtn);
/*
* Reobtain the tmp uploaded file as input stream
*/
InputStream inputStream = file.getInputStream();
File convFile = new File(fileNameWithExtn); //If i don't do //this, I think I was getting file not found or MD5 error.
file.transferTo(convFile);
FileUtils.copyInputStreamToFile(inputStream, convFile); //you //need to have commons.io in your pom.xml for this FileUtils to work. Not //the apache FileUtils.
AmazonS3 s3 = new AmazonS3Client(new AWSStaticCredentialsProvider
(new BasicAWSCredentials("<yourkeyId>", "<YourAccessKey>")));
s3.setRegion(Region.US_West.toAWSRegion());
s3.setEndpoint("yourRegion.amazonaws.com");
versionId = s3.putObject(new PutObjectRequest("YourBucketName", name, convFile)).getVersionId();
I created a video chat, used Opentok like this:
in video_session_controller.rb file.
require 'opentok'
def show
#video_session = VideoSession.find_by(id: params[:id])
opentok = OpenTok::OpenTok.new ENV['OPENTOK_API_KEY'], ENV['OPENTOK_SECRET']
session = opentok.create_session :media_mode => :routed
#token = session.generate_token
#video_session.create_opentok_session(session_id: session.session_id, token: #token)
end
It is working on live site, but it is not working on local machine.
In local, it shows following error.
OpenTok::OpenTokError: Failed to connect to OpenTok. Response code:
SSL_connect returned=1 errno=0 state=error: certificate verify failed
How can I fix it?
Thanks.
In pig, I'm using my udf which is using external jar file routines, and in eclipse I did export that jar file too. But while running pig -x local script1.pig, it gives me error for external jar file routines.
Please help!
Thanks.
EDIT 1:
As asked in comments for my code:
script1.pig:
REGISTER ./csv2arff.jar;
csvraw = LOAD 'sample' USING PigStorage('\n') as (c);
arffraws = FOREACH csvraw GENERATE pighw2java.CSV2ARFF(c);
pighw2java.CSV2ARFF:
public String exec(Tuple input) throws IOException {
if (input == null || input.size() == 0)
return null;
try{
System.out.println(">>> " + input.get(0).toString());
// 1.1) csv to instances
ByteArrayInputStream inputStream = new ByteArrayInputStream(input.get(0).toString().getBytes("UTF-8"));
CSVLoader loader = new CSVLoader(); **HERE IS ERROR**
.....
}
}
Error I got:
java.lang.NoClassDefFoundError: weka/core/converters/CSVLoader
at pighw2java.CSV2ARFF.exec(CSV2ARFF.java:24)
at pighw2java.CSV2ARFF.exec(CSV2ARFF.java:1)
at org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.POUserFunc.getNext(POUserFunc.java:216)
at org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.POUserFunc.getNext(POUserFunc.java:305)
at org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator.getNext(PhysicalOperator.java:322)
at org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POForEach.processPlan(POForEach.java:332)
at org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POForEach.getNext(POForEach.java:284)
at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigGenericMapBase.runPipeline(PigGenericMapBase.java:271)
at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigGenericMapBase.map(PigGenericMapBase.java:266)
at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigGenericMapBase.map(PigGenericMapBase.java:64)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:144)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:764)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:370)
at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:212)
Caused by: java.lang.ClassNotFoundException: weka.core.converters.CSVLoader
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 14 more
You need to register all of the 3rd party dependencies that are used in your custom UDF. Here:
register '/path/to/weka.jar'