use of com.sun.enterprise.admin.servermgmt.DomainException in project Payara by payara.
the class DomainBuilder method run.
/**
* Performs all the domain configurations which includes security, configuration processing,
* substitution of parameters... etc.
*
* @throws DomainException If any exception occurs in configuration.
*/
public void run() throws RepositoryException, DomainException {
// Create domain directories.
File domainDir = FileUtils.safeGetCanonicalFile(new File(_domainConfig.getRepositoryRoot(), _domainConfig.getDomainName()));
createDirectory(domainDir);
try {
// Extract other jar entries
byte[] buffer = new byte[10000];
for (Enumeration<JarEntry> entry = _templateJar.entries(); entry.hasMoreElements(); ) {
JarEntry jarEntry = (JarEntry) entry.nextElement();
String entryName = jarEntry.getName();
if (entryName.startsWith(META_DIR_NAME)) {
// Skipping the extraction of jar meta data.
continue;
}
if (_extractedEntries.contains(entryName)) {
continue;
}
if (jarEntry.isDirectory()) {
File dir = new File(domainDir, jarEntry.getName());
if (!dir.exists()) {
if (!dir.mkdir()) {
_logger.log(Level.WARNING, SLogger.DIR_CREATION_ERROR, dir.getName());
}
}
continue;
}
InputStream in = null;
BufferedOutputStream outputStream = null;
try {
in = _templateJar.getInputStream(jarEntry);
outputStream = new BufferedOutputStream(new FileOutputStream(new File(domainDir.getAbsolutePath(), jarEntry.getName())));
int i = 0;
while ((i = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, i);
}
} finally {
if (in != null) {
try {
in.close();
} catch (Exception io) {
/**
* ignore
*/
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception io) {
/**
* ignore
*/
}
}
}
}
File configDir = new File(domainDir, DomainConstants.CONFIG_DIR);
String user = (String) _domainConfig.get(DomainConfig.K_USER);
String password = (String) _domainConfig.get(DomainConfig.K_PASSWORD);
String[] adminUserGroups = ((String) _domainConfig.get(DomainConfig.K_INITIAL_ADMIN_USER_GROUPS)).split(",");
String masterPassword = (String) _domainConfig.get(DomainConfig.K_MASTER_PASSWORD);
Boolean saveMasterPassword = (Boolean) _domainConfig.get(DomainConfig.K_SAVE_MASTER_PASSWORD);
// Process domain security.
DomainSecurity domainSecurity = new DomainSecurity();
domainSecurity.processAdminKeyFile(new File(configDir, DomainConstants.ADMIN_KEY_FILE), user, password, adminUserGroups);
try {
domainSecurity.createSSLCertificateDatabase(configDir, _domainConfig, masterPassword);
} catch (Exception e) {
String msg = _strings.getString("SomeProblemWithKeytool", e.getMessage());
System.err.println(msg);
FileOutputStream fos = null;
try {
File keystoreFile = new File(configDir, DomainConstants.KEYSTORE_FILE);
fos = new FileOutputStream(keystoreFile);
fos.write(_keystoreBytes);
} catch (Exception ex) {
getLogger().log(Level.SEVERE, UNHANDLED_EXCEPTION, ex);
} finally {
if (fos != null)
fos.close();
}
}
domainSecurity.changeMasterPasswordInMasterPasswordFile(new File(configDir, DomainConstants.MASTERPASSWORD_FILE), masterPassword, saveMasterPassword);
domainSecurity.createPasswordAliasKeystore(new File(configDir, DomainConstants.DOMAIN_PASSWORD_FILE), masterPassword);
// Add customized tokens in domain.xml.
CustomTokenClient tokenClient = new CustomTokenClient(_domainConfig);
Map<String, String> generatedTokens = tokenClient.getSubstitutableTokens();
// Perform string substitution.
if (_domainTempalte.hasStringsubs()) {
StringSubstitutor substitutor = _domainTempalte.getStringSubs();
Map<String, String> lookUpMap = SubstitutableTokens.getSubstitutableTokens(_domainConfig);
lookUpMap.putAll(generatedTokens);
substitutor.setAttributePreprocessor(new AttributePreprocessorImpl(lookUpMap));
substitutor.substituteAll();
}
// Change the permission for bin & config directories.
try {
File binDir = new File(domainDir, DomainConstants.BIN_DIR);
if (binDir.exists() && binDir.isDirectory()) {
domainSecurity.changeMode("-R u+x ", binDir);
}
domainSecurity.changeMode("-R g-rwx,o-rwx ", configDir);
} catch (Exception e) {
throw new DomainException(_strings.get("setPermissionError"), e);
}
// Generate domain-info.xml
DomainInfoManager domainInfoManager = new DomainInfoManager();
domainInfoManager.process(_domainTempalte, domainDir);
} catch (DomainException de) {
// roll-back
FileUtils.liquidate(domainDir);
throw de;
} catch (Exception ex) {
// roll-back
FileUtils.liquidate(domainDir);
throw new DomainException(ex);
}
}
use of com.sun.enterprise.admin.servermgmt.DomainException in project Payara by payara.
the class TemplateInfoHolder method parse.
/**
* Parse the configuration stream against the template-info schema.
*
* @param configStream InputStream of template-info.xml file.
* @return Parsed Object.
* @throws Exception If any error occurs in parsing.
*/
@SuppressWarnings("rawtypes")
private TemplateInfo parse(InputStream configStream) throws Exception {
if (configStream == null) {
throw new DomainException("Invalid stream");
}
try {
URL schemaUrl = getClass().getClassLoader().getResource(TEMPLATE_INFO_SCHEMA_PATH);
JAXBContext context = JAXBContext.newInstance(TemplateInfo.class.getPackage().getName());
Unmarshaller unmarshaller = context.createUnmarshaller();
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaUrl);
unmarshaller.setSchema(schema);
InputSource is = new InputSource(configStream);
SAXSource source = new SAXSource(is);
Object obj = unmarshaller.unmarshal(source);
return obj instanceof JAXBElement ? (TemplateInfo) (((JAXBElement) obj).getValue()) : (TemplateInfo) obj;
} finally {
try {
configStream.close();
configStream = null;
} catch (IOException e) {
/**
* Ignore
*/
}
}
}
use of com.sun.enterprise.admin.servermgmt.DomainException in project Payara by payara.
the class CustomTokenClient method getSubstitutableTokens.
/**
* Get's the substitutable custom tokens.
*
* @return {@link Map} of substitutable tokens, or empty Map
* if no custom token found.
* @throws DomainException If error occurred in retrieving the
* custom tokens.
*/
public Map<String, String> getSubstitutableTokens() throws DomainException {
CustomizationTokensProvider provider = CustomizationTokensProviderFactory.createCustomizationTokensProvider();
Map<String, String> generatedTokens = new HashMap<String, String>();
String lineSeparator = System.getProperty("line.separator");
int noOfTokens = 0;
try {
List<ConfigCustomizationToken> customTokens = provider.getPresentConfigCustomizationTokens();
if (!customTokens.isEmpty()) {
StringBuffer generatedSysTags = new StringBuffer();
// Check presence of token place-holder
Set<Integer> usedPorts = new HashSet<Integer>();
Properties domainProps = _domainConfig.getDomainProperties();
String portBase = (String) _domainConfig.get(DomainConfig.K_PORTBASE);
Map<String, String> filePaths = new HashMap<String, String>(3, 1);
filePaths.put(SystemPropertyConstants.INSTALL_ROOT_PROPERTY, System.getProperty(SystemPropertyConstants.INSTALL_ROOT_PROPERTY));
filePaths.put(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY, System.getProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY));
filePaths.put(SystemPropertyConstants.JAVA_ROOT_PROPERTY, System.getProperty(SystemPropertyConstants.JAVA_ROOT_PROPERTY));
noOfTokens = customTokens.size();
for (ConfigCustomizationToken token : customTokens) {
String name = token.getName();
// Check for valid custom token parameters.
if (isNullOrEmpty(name) || isNullOrEmpty(token.getValue()) || isNullOrEmpty(token.getDescription())) {
throw new IllegalArgumentException(_strings.get("invalidTokenParameters", name, token.getValue(), token.getDescription()));
}
switch(token.getCustomizationType()) {
case PORT:
Integer port = null;
if (domainProps.containsKey(name)) {
port = Integer.valueOf(domainProps.getProperty(token.getName()));
if (!NetUtils.isPortFree(port)) {
throw new DomainException(_strings.get("unavailablePort", port));
}
} else {
if (portBase != null && token.getTokenTypeDetails() instanceof PortTypeDetails) {
PortTypeDetails portTypeDetails = (PortTypeDetails) token.getTokenTypeDetails();
port = Integer.parseInt(portBase) + Integer.parseInt(portTypeDetails.getBaseOffset());
if (!generatedTokens.containsKey(PORTBASE_PLACE_HOLDER)) {
// Adding a token to persist port base value as a system tag
generatedTokens.put(PORTBASE_PLACE_HOLDER, SystemPropertyTagBuilder.buildSystemTag(PORTBASE_PLACE_HOLDER, portBase));
}
} else {
port = Integer.valueOf(token.getValue());
}
// Find next available unused port by incrementing the port value by 1
while (!NetUtils.isPortFree(port) && !usedPorts.contains(port++)) ;
}
usedPorts.add(port);
generatedSysTags.append(SystemPropertyTagBuilder.buildSystemTag(token, port.toString()));
break;
case FILE:
String path = token.getValue();
for (Map.Entry<String, String> entry : filePaths.entrySet()) {
if (path.contains(entry.getKey())) {
path = path.replace(entry.getKey(), entry.getValue());
break;
}
}
if (token.getTokenTypeDetails() instanceof FileTypeDetails) {
FileTypeDetails details = (FileTypeDetails) token.getTokenTypeDetails();
File file = new File(path);
switch(details.getExistCondition()) {
case MUST_EXIST:
if (!file.exists()) {
throw new DomainException(_strings.get("missingFile", file.getAbsolutePath()));
}
break;
case MUST_NOT_EXIST:
if (file.exists()) {
throw new DomainException(_strings.get("filePresenceNotDesired", file.getAbsolutePath()));
}
break;
case NO_OP:
break;
}
}
generatedSysTags.append(SystemPropertyTagBuilder.buildSystemTag(token, path));
break;
case STRING:
generatedSysTags.append(SystemPropertyTagBuilder.buildSystemTag(token));
break;
}
if (--noOfTokens > 0) {
generatedSysTags.append(lineSeparator);
}
}
String tags = generatedSysTags.toString();
if (!isNullOrEmpty(tags)) {
generatedTokens.put(CUSTOM_TOKEN_PLACE_HOLDER, tags);
}
}
List<ConfigCustomizationToken> defaultTokens = provider.getPresentDefaultConfigCustomizationTokens();
if (!defaultTokens.isEmpty()) {
StringBuffer defaultSysTags = new StringBuffer();
noOfTokens = defaultTokens.size();
for (ConfigCustomizationToken token : defaultTokens) {
defaultSysTags.append(SystemPropertyTagBuilder.buildSystemTag(token));
if (--noOfTokens > 0) {
defaultSysTags.append(lineSeparator);
}
}
generatedTokens.put(DEFAULT_TOKEN_PLACE_HOLDER, defaultSysTags.toString());
}
} catch (DomainException de) {
throw de;
} catch (Exception ex) {
throw new DomainException(ex);
}
return generatedTokens;
}
use of com.sun.enterprise.admin.servermgmt.DomainException in project Payara by payara.
the class DomainBuilder method validateTemplate.
/**
* Validate's the template.
*
* @throws DomainException If any exception occurs in validation.
*/
public void validateTemplate() throws DomainException {
try {
// Sanity check on the repository.
RepositoryManager repoManager = new RepositoryManager();
repoManager.checkRepository(_domainConfig, false);
// Validate the port values.
DomainPortValidator portValidator = new DomainPortValidator(_domainConfig, _defaultPortValues);
portValidator.validateAndSetPorts();
// Validate other domain config parameters.
new PEDomainConfigValidator().validate(_domainConfig);
} catch (Exception ex) {
throw new DomainException(ex);
}
}
use of com.sun.enterprise.admin.servermgmt.DomainException in project Payara by payara.
the class DomainBuilder method initialize.
/**
* Initialize template by loading template jar.
*
* @throws DomainException If exception occurs in initializing the template jar.
*/
// TODO : localization of index.html
private void initialize() throws DomainException {
String templateJarPath = (String) _domainConfig.get(DomainConfig.K_TEMPLATE_NAME);
if (templateJarPath == null || templateJarPath.isEmpty()) {
String defaultTemplateName = Version.getDefaultDomainTemplate();
if (defaultTemplateName == null || defaultTemplateName.isEmpty()) {
throw new DomainException(_strings.get("missingDefaultTemplateName"));
}
Map<String, String> envProperties = new ASenvPropertyReader().getProps();
templateJarPath = envProperties.get(SystemPropertyConstants.INSTALL_ROOT_PROPERTY) + File.separator + DEFAULT_TEMPLATE_RELATIVE_PATH + File.separator + defaultTemplateName;
}
File template = new File(templateJarPath);
if (!template.exists() || !template.getName().endsWith(".jar")) {
throw new DomainException(_strings.get("invalidTemplateJar", template.getAbsolutePath()));
}
try {
_templateJar = new JarFile(new File(templateJarPath));
JarEntry je = _templateJar.getJarEntry("config/" + DomainConstants.DOMAIN_XML_FILE);
if (je == null) {
throw new DomainException(_strings.get("missingMandatoryFile", DomainConstants.DOMAIN_XML_FILE));
}
// Loads template-info.xml
je = _templateJar.getJarEntry(TEMPLATE_INFO_XML);
if (je == null) {
throw new DomainException(_strings.get("missingMandatoryFile", TEMPLATE_INFO_XML));
}
TemplateInfoHolder templateInfoHolder = new TemplateInfoHolder(_templateJar.getInputStream(je), templateJarPath);
_extractedEntries.add(TEMPLATE_INFO_XML);
// Loads string substitution XML.
je = _templateJar.getJarEntry(STRINGSUBS_FILE);
StringSubstitutor stringSubstitutor = null;
if (je != null) {
stringSubstitutor = StringSubstitutionFactory.createStringSubstitutor(_templateJar.getInputStream(je));
List<Property> defaultStringSubsProps = stringSubstitutor.getDefaultProperties(PropertyType.PORT);
for (Property prop : defaultStringSubsProps) {
_defaultPortValues.setProperty(prop.getKey(), prop.getValue());
}
_extractedEntries.add(je.getName());
} else {
_logger.log(Level.WARNING, SLogger.MISSING_FILE, STRINGSUBS_FILE);
}
_domainTempalte = new DomainTemplate(templateInfoHolder, stringSubstitutor, templateJarPath);
// Loads default self signed certificate.
je = _templateJar.getJarEntry("config/" + DomainConstants.KEYSTORE_FILE);
if (je != null) {
_keystoreBytes = new byte[(int) je.getSize()];
InputStream in = null;
int count = 0;
try {
in = _templateJar.getInputStream(je);
count = in.read(_keystoreBytes);
if (count < _keystoreBytes.length) {
throw new DomainException(_strings.get("loadingFailure", je.getName()));
}
} finally {
if (in != null) {
in.close();
}
}
_extractedEntries.add(je.getName());
}
File parentDomainDir = FileUtils.safeGetCanonicalFile(new File(_domainConfig.getRepositoryRoot()));
createDirectory(parentDomainDir);
} catch (Exception e) {
throw new DomainException(e);
}
}
Aggregations