Esempio di codice
Questo esempio di codice Java™ è di un servizio OSGi che effettua una connessione a un database MySQL esterno tramite il servizio OSGi DataSourcePool di AEM.
La configurazione del factory OSGi DataSourcePool specifica a sua volta una porta (30001
) mappata tramite la regola portForwards
nell'operazione enableEnvironmentAdvancedNetworkingConfiguration all'host e alla porta esterni, mysql.example.com:3306
.
...
"portForwards": [{
"name": "mysql.example.com",
"portDest": 3306,
"portOrig": 30001
}]
...
core/src/com/adobe/aem/wknd/examples/connections/impl/JdbcExternalServiceImpl.java
package com.adobe.aem.wknd.examples.core.connections.impl;
import com.adobe.aem.wknd.examples.core.connections.ExternalService;
import com.day.commons.datasource.poolservice.DataSourceNotFoundException;
import com.day.commons.datasource.poolservice.DataSourcePool;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@Component
public class JdbcExternalServiceImpl implements ExternalService {
private static final Logger log = LoggerFactory.getLogger(JdbcExternalServiceImpl.class);
@Reference
private DataSourcePool dataSourcePool;
// The datasource.name value of the OSGi configuration containing the connection this OSGi component will use.
private static final String DATA_SOURCE_NAME = "wknd-examples-mysql";
@Override
public boolean isAccessible() {
try {
// Get the JDBC data source based on the named OSGi configuration
DataSource dataSource = (DataSource) dataSourcePool.getDataSource(DATA_SOURCE_NAME);
// Establish a connection with the external JDBC service
// Per the OSGi configuration, this will use the injected $[env:AEM_PROXY_HOST] value as the host
// and the port (30001) mapped via Cloud Manager API call
try (Connection connection = dataSource.getConnection()) {
// Validate the connection
connection.isValid(1000);
// Close the connection, since this is just a simple connectivity check
connection.close();
// Return true if AEM could reach the external JDBC service
return true;
} catch (SQLException e) {
log.error("Unable to validate SQL connection for [ {} ]", DATA_SOURCE_NAME, e);
}
} catch (DataSourceNotFoundException e) {
log.error("Unable to establish an connection with the JDBC data source [ {} ]", DATA_SOURCE_NAME, e);
}
return false;
}
}