List of usage examples for java.util Properties toString
@Override public synchronized String toString()
From source file:dk.defxws.fedoragsearch.server.Config.java
private void checkConfig() throws ConfigException { if (logger.isDebugEnabled()) logger.debug("fedoragsearch.properties=" + fgsProps.toString()); // Check for unknown properties, indicating typos or wrong property names String[] propNames = { "fedoragsearch.deployFile", "fedoragsearch.soapBase", "fedoragsearch.soapUser", "fedoragsearch.soapPass", "fedoragsearch.defaultNoXslt", "fedoragsearch.defaultGfindObjectsRestXslt", "fedoragsearch.defaultUpdateIndexRestXslt", "fedoragsearch.defaultBrowseIndexRestXslt", "fedoragsearch.defaultGetRepositoryInfoRestXslt", "fedoragsearch.defaultGetIndexInfoRestXslt", "fedoragsearch.mimeTypes", "fedoragsearch.maxPageSize", "fedoragsearch.defaultBrowseIndexTermPageSize", "fedoragsearch.defaultGfindObjectsHitPageSize", "fedoragsearch.defaultGfindObjectsSnippetsMax", "fedoragsearch.defaultGfindObjectsFieldMaxLength", "fedoragsearch.repositoryNames", "fedoragsearch.indexNames", "fedoragsearch.updaterNames", "fedoragsearch.searchResultFilteringModule", "fedoragsearch.searchResultFilteringType" }; //checkPropNames("fedoragsearch.properties", fgsProps, propNames); // Check rest stylesheets checkRestStylesheet("fedoragsearch.defaultNoXslt"); checkRestStylesheet("fedoragsearch.defaultGfindObjectsRestXslt"); checkRestStylesheet("fedoragsearch.defaultUpdateIndexRestXslt"); checkRestStylesheet("fedoragsearch.defaultBrowseIndexRestXslt"); checkRestStylesheet("fedoragsearch.defaultGetRepositoryInfoRestXslt"); checkRestStylesheet("fedoragsearch.defaultGetIndexInfoRestXslt"); // Check mimeTypes checkMimeTypes("fedoragsearch", fgsProps, "fedoragsearch.mimeTypes"); // Check resultPage properties try {// w w w.ja va 2 s.c om maxPageSize = Integer.parseInt(fgsProps.getProperty("fedoragsearch.maxPageSize")); } catch (NumberFormatException e) { errors.append("\n*** maxPageSize is not valid:\n" + e.toString()); } try { defaultBrowseIndexTermPageSize = Integer .parseInt(fgsProps.getProperty("fedoragsearch.defaultBrowseIndexTermPageSize")); } catch (NumberFormatException e) { errors.append("\n*** defaultBrowseIndexTermPageSize is not valid:\n" + e.toString()); } try { defaultGfindObjectsHitPageSize = Integer .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsHitPageSize")); } catch (NumberFormatException e) { errors.append("\n*** defaultGfindObjectsHitPageSize is not valid:\n" + e.toString()); } try { defaultGfindObjectsSnippetsMax = Integer .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsSnippetsMax")); } catch (NumberFormatException e) { errors.append("\n*** defaultGfindObjectsSnippetsMax is not valid:\n" + e.toString()); } try { defaultGfindObjectsFieldMaxLength = Integer .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsFieldMaxLength")); } catch (NumberFormatException e) { errors.append("\n*** defaultGfindObjectsFieldMaxLength is not valid:\n" + e.toString()); } // Check updater properties String updaterProperty = fgsProps.getProperty("fedoragsearch.updaterNames"); if (updaterProperty == null) { updaterNameToProps = null; // No updaters will be created } else { updaterNameToProps = new Hashtable(); StringTokenizer updaterNames = new StringTokenizer(updaterProperty); while (updaterNames.hasMoreTokens()) { String updaterName = updaterNames.nextToken(); try { InputStream propStream = null; try { propStream = getResourceInputStream("/updater/" + updaterName + "/updater.properties"); } catch (ConfigException e) { errors.append("\n" + e.getMessage()); } Properties props = new Properties(); props.load(propStream); propStream.close(); //MIH convertProperties(props); if (logger.isInfoEnabled()) { logger.info( configName + "/updater/" + updaterName + "/updater.properties=" + props.toString()); } // Check properties String propsNamingFactory = props.getProperty("java.naming.factory.initial"); String propsProviderUrl = props.getProperty("java.naming.provider.url"); String propsConnFactory = props.getProperty("connection.factory.name"); String propsClientId = props.getProperty("client.id"); if (propsNamingFactory == null) { errors.append("\n*** java.naming.factory.initial not provided in " + configName + "/updater/" + updaterName + "/updater.properties"); } if (propsProviderUrl == null) { errors.append("\n*** java.naming.provider.url not provided in " + configName + "/updater/" + updaterName + "/updater.properties"); } if (propsConnFactory == null) { errors.append("\n*** connection.factory.name not provided in " + configName + "/updater/" + updaterName + "/updater.properties"); } if (propsClientId == null) { errors.append("\n*** client.id not provided in " + configName + "/updater/" + updaterName + "/updater.properties"); } updaterNameToProps.put(updaterName, props); } catch (IOException e) { errors.append("\n*** Error loading " + configName + "/updater/" + updaterName + ".properties:\n" + e.toString()); } } } // Check searchResultFilteringModule property searchResultFilteringModuleProperty = fgsProps.getProperty("fedoragsearch.searchResultFilteringModule"); if (searchResultFilteringModuleProperty != null && searchResultFilteringModuleProperty.length() > 0) { try { getSearchResultFiltering(); } catch (ConfigException e) { errors.append(e.getMessage()); } String searchResultFilteringTypeProperty = fgsProps .getProperty("fedoragsearch.searchResultFilteringType"); StringTokenizer srft = new StringTokenizer(""); if (searchResultFilteringTypeProperty != null) { srft = new StringTokenizer(searchResultFilteringTypeProperty); } int countTokens = srft.countTokens(); if (searchResultFilteringTypeProperty == null || countTokens == 0 || countTokens > 1) { errors.append("\n*** " + configName + ": fedoragsearch.searchResultFilteringType=" + searchResultFilteringTypeProperty + ": one and only one of 'presearch', 'insearch', 'postsearch' must be stated.\n"); } else { for (int i = 0; i < countTokens; i++) { String token = srft.nextToken(); if (!("presearch".equals(token) || "insearch".equals(token) || "postsearch".equals(token))) { errors.append("\n*** " + configName + ": fedoragsearch.searchResultFilteringType=" + searchResultFilteringTypeProperty + ": only 'presearch', 'insearch', 'postsearch' may be stated, not '" + token + "'.\n"); } } } } // Check repository properties Enumeration repositoryNames = repositoryNameToProps.keys(); while (repositoryNames.hasMoreElements()) { String repositoryName = (String) repositoryNames.nextElement(); Properties props = (Properties) repositoryNameToProps.get(repositoryName); if (logger.isDebugEnabled()) logger.debug(configName + "/repository/" + repositoryName + "/repository.properties=" + props.toString()); // Check for unknown properties, indicating typos or wrong property names String[] reposPropNames = { "fgsrepository.repositoryName", "fgsrepository.fedoraSoap", "fgsrepository.fedoraUser", "fgsrepository.fedoraPass", "fgsrepository.fedoraObjectDir", "fgsrepository.fedoraVersion", "fgsrepository.defaultGetRepositoryInfoResultXslt", "fgsrepository.trustStorePath", "fgsrepository.trustStorePass" }; //checkPropNames(configName+"/repository/"+repositoryName+"/repository.properties", props, reposPropNames); // Check repositoryName String propsRepositoryName = props.getProperty("fgsrepository.repositoryName"); if (!repositoryName.equals(propsRepositoryName)) { errors.append("\n*** " + configName + "/repository/" + repositoryName + ": fgsrepository.repositoryName must be=" + repositoryName); } // Check fedoraObjectDir // String fedoraObjectDirName = insertSystemProperties(props.getProperty("fgsrepository.fedoraObjectDir")); // File fedoraObjectDir = new File(fedoraObjectDirName); // if (fedoraObjectDir == null) { // errors.append("\n*** "+configName+"/repository/" + repositoryName // + ": fgsrepository.fedoraObjectDir=" // + fedoraObjectDirName + " not found"); // } // Check result stylesheets checkResultStylesheet("/repository/" + repositoryName, props, "fgsrepository.defaultGetRepositoryInfoResultXslt"); } // Check index properties Enumeration indexNames = indexNameToProps.keys(); while (indexNames.hasMoreElements()) { String indexName = (String) indexNames.nextElement(); Properties props = (Properties) indexNameToProps.get(indexName); if (logger.isDebugEnabled()) logger.debug(configName + "/index/" + indexName + "/index.properties=" + props.toString()); // Check for unknown properties, indicating typos or wrong property names String[] indexPropNames = { "fgsindex.indexName", "fgsindex.indexBase", "fgsindex.indexUser", "fgsindex.indexPass", "fgsindex.operationsImpl", "fgsindex.defaultUpdateIndexDocXslt", "fgsindex.defaultUpdateIndexResultXslt", "fgsindex.defaultGfindObjectsResultXslt", "fgsindex.defaultBrowseIndexResultXslt", "fgsindex.defaultGetIndexInfoResultXslt", "fgsindex.indexDir", "fgsindex.analyzer", "fgsindex.untokenizedFields", "fgsindex.defaultQueryFields", "fgsindex.snippetBegin", "fgsindex.snippetEnd", "fgsindex.maxBufferedDocs", "fgsindex.mergeFactor", "fgsindex.ramBufferSizeMb", "fgsindex.defaultWriteLockTimeout", "fgsindex.defaultSortFields", "fgsindex.uriResolver" }; //checkPropNames(configName+"/index/"+indexName+"/index.properties", props, indexPropNames); // Check indexName String propsIndexName = props.getProperty("fgsindex.indexName"); if (!indexName.equals(propsIndexName)) { errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.indexName must be=" + indexName); } // Check operationsImpl class String operationsImpl = props.getProperty("fgsindex.operationsImpl"); if (operationsImpl == null || operationsImpl.equals("")) { errors.append( "\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl must be set in " + configName + "/index/ " + indexName + ".properties"); } try { Class operationsImplClass = Class.forName(operationsImpl); try { GenericOperationsImpl ops = (GenericOperationsImpl) operationsImplClass .getConstructor(new Class[] {}).newInstance(new Object[] {}); } catch (InstantiationException e) { errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl=" + operationsImpl + ": instantiation error.\n" + e.toString()); } catch (IllegalAccessException e) { errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl=" + operationsImpl + ": instantiation error.\n" + e.toString()); } catch (InvocationTargetException e) { errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl=" + operationsImpl + ": instantiation error.\n" + e.toString()); } catch (NoSuchMethodException e) { errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl=" + operationsImpl + ": instantiation error.\n" + e.toString()); } } catch (ClassNotFoundException e) { errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl=" + operationsImpl + ": class not found.\n" + e); } // Check result stylesheets checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultUpdateIndexDocXslt"); checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultUpdateIndexResultXslt"); checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultGfindObjectsResultXslt"); checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultBrowseIndexResultXslt"); checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultGetIndexInfoResultXslt"); // Check indexDir String indexDir = insertSystemProperties(props.getProperty("fgsindex.indexDir")); File indexDirFile = new File(indexDir); if (indexDirFile == null) { errors.append("\n*** " + configName + "/index/" + indexName + " fgsindex.indexDir=" + indexDir + " must exist as a directory"); } // Check analyzer class for lucene and solr if (operationsImpl.indexOf("fgslucene") > -1 || operationsImpl.indexOf("fgssolr") > -1) { String analyzer = props.getProperty("fgsindex.analyzer"); if (analyzer == null || analyzer.equals("")) { analyzer = defaultAnalyzer; } try { Class analyzerClass = Class.forName(analyzer); try { Analyzer a = (Analyzer) analyzerClass.getConstructor(new Class[] {}) .newInstance(new Object[] {}); } catch (InstantiationException e) { errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString()); } catch (IllegalAccessException e) { errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString()); } catch (InvocationTargetException e) { errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString()); } catch (NoSuchMethodException e) { errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer + ": fgsindex.analyzer=" + analyzer + ": instantiation error:\n" + e.toString()); } } catch (ClassNotFoundException e) { errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.analyzer=" + analyzer + ": class not found:\n" + e.toString()); } } // Add untokenizedFields property for lucene if (operationsImpl.indexOf("fgslucene") > -1) { String defaultUntokenizedFields = props.getProperty("fgsindex.untokenizedFields"); if (defaultUntokenizedFields == null) props.setProperty("fgsindex.untokenizedFields", ""); if (indexDirFile != null) { StringBuffer untokenizedFields = new StringBuffer( props.getProperty("fgsindex.untokenizedFields")); IndexReader ir = null; try { ir = IndexReader.open(FSDirectory.open(new File(indexDir)), true); int max = ir.numDocs(); if (max > 10) max = 10; for (int i = 0; i < max; i++) { Document doc = ir.document(i); for (ListIterator li = doc.getFields().listIterator(); li.hasNext();) { Field f = (Field) li.next(); if (!f.isTokenized() && f.isIndexed() && untokenizedFields.indexOf(f.name()) < 0) { untokenizedFields.append(" " + f.name()); } } } } catch (Exception e) { } props.setProperty("fgsindex.untokenizedFields", untokenizedFields.toString()); if (logger.isDebugEnabled()) logger.debug("indexName=" + indexName + " fgsindex.untokenizedFields=" + untokenizedFields); } } // Check defaultQueryFields - how can we check this? String defaultQueryFields = props.getProperty("fgsindex.defaultQueryFields"); // Use custom URIResolver if given //MIH: also check for solr if (operationsImpl.indexOf("fgslucene") > -1 || operationsImpl.indexOf("fgssolr") > -1) { Class uriResolverClass = null; String uriResolver = props.getProperty("fgsindex.uriResolver"); if (!(uriResolver == null || uriResolver.equals(""))) { try { uriResolverClass = Class.forName(uriResolver); try { URIResolverImpl ur = (URIResolverImpl) uriResolverClass.getConstructor(new Class[] {}) .newInstance(new Object[] {}); if (ur != null) { ur.setConfig(this); indexNameToUriResolvers.put(indexName, ur); } } catch (InstantiationException e) { errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n" + e.toString()); } catch (IllegalAccessException e) { errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n" + e.toString()); } catch (InvocationTargetException e) { errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n" + e.toString()); } catch (NoSuchMethodException e) { errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error:\n" + e.toString()); } } catch (ClassNotFoundException e) { errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.uriResolver=" + uriResolver + ": class not found:\n" + e.toString()); } } } } if (logger.isDebugEnabled()) logger.debug("configCheck configName=" + configName + " errors=" + errors.toString()); if (errors.length() > 0) throw new ConfigException(errors.toString()); }
From source file:com.bigdata.rdf.sail.webapp.AbstractTestNanoSparqlClient.java
protected AbstractTripleStore createTripleStore(final IIndexManager indexManager, final String namespace, final Properties properties) { if (log.isInfoEnabled()) log.info("KB namespace=" + namespace); // Locate the resource declaration (aka "open"). This tells us if it // exists already. AbstractTripleStore tripleStore = (AbstractTripleStore) indexManager.getResourceLocator().locate(namespace, ITx.UNISOLATED);/* w w w . j a v a 2s. co m*/ if (tripleStore != null) { fail("exists: " + namespace); } /* * Create the KB instance. */ if (log.isInfoEnabled()) { log.info("Creating KB instance: namespace=" + namespace); log.info("Properties=" + properties.toString()); } if (indexManager instanceof Journal) { // Create the kb instance. tripleStore = new LocalTripleStore(indexManager, namespace, ITx.UNISOLATED, properties); } else { tripleStore = new ScaleOutTripleStore(indexManager, namespace, ITx.UNISOLATED, properties); } // create the triple store. tripleStore.create(); if (log.isInfoEnabled()) log.info("Created tripleStore: " + namespace); // New KB instance was created. return tripleStore; }
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
/** * [used by Spring]/*from w ww. j a v a 2s . c o m*/ */ public void init() { VFSContainer root = mailModule.getRootForAttachments(); attachmentStorage = new FileStorage(root); PublisherData pdata = getPublisherData(); SubscriptionContext scontext = getSubscriptionContext(); notificationsManager.getOrCreatePublisher(scontext, pdata); Properties p = null; try { velocityEngine = new VelocityEngine(); p = new Properties(); p.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); p.setProperty(RuntimeConstants.RESOURCE_MANAGER_CACHE_CLASS, "org.olat.core.gui.render.velocity.InfinispanResourceCache"); p.setProperty("runtime.log.logsystem.log4j.category", "syslog"); velocityEngine.init(p); } catch (Exception e) { throw new RuntimeException("config error " + p.toString()); } }
From source file:voldemort.server.protocol.admin.AdminServiceRequestHandler.java
private Message handleDisableStoreVersion(VAdminProto.DisableStoreVersionRequest disableStoreVersion) { String storeName = disableStoreVersion.getStoreName(); Long version = disableStoreVersion.getPushVersion(); Properties properties = new Properties(); try {/*from w w w . j a v a 2s.c o m*/ properties.load(new StringReader(disableStoreVersion.getInfo())); } catch (IOException e) { logger.error("Got IOException while trying to decipher a DisableStoreVersionRequest's info.", e); } logger.info("Received DisableStoreVersionRequest:\n" + "\tstore_name: " + storeName + "\n" + "\tpush_version: " + version + "\n" + "\tinfo: " + properties.toString()); VAdminProto.DisableStoreVersionResponse.Builder response = VAdminProto.DisableStoreVersionResponse .newBuilder(); response.setNodeId(server.getMetadataStore().getNodeId()); final String logMessagePrefix = "handleDisableStoreVersion returning response: "; try { StorageEngine storeToDisable = storeRepository.getStorageEngine(storeName); if (storeToDisable == null) { response.setDisableSuccess(false).setInfo("The store '" + storeName + "' does not exist!"); } else { StoreVersionManager storeVersionManager = (StoreVersionManager) storeToDisable .getCapability(StoreCapabilityType.DISABLE_STORE_VERSION); storeVersionManager.disableStoreVersion(version); response.setDisableSuccess(true).setDisablePersistenceSuccess(true).setInfo( "The store '" + storeName + "' version " + version + " was successfully disabled."); } logger.info(logMessagePrefix + response.getInfo()); } catch (PersistenceFailureException e) { String message = "The store '" + storeName + "' version " + version + " was disabled" + " but the change could not be persisted and will thus remain in effect only" + " until the next server restart. This is likely caused by the IO subsystem" + " becoming read-only."; logger.error(logMessagePrefix + message, e); response.setDisableSuccess(true).setDisablePersistenceSuccess(false).setInfo(message); } catch (NoSuchCapabilityException e) { String message = "The store '" + storeName + "' does not support disabling versions!"; logger.error(logMessagePrefix + message, e); response.setDisableSuccess(false).setInfo(message); } catch (Exception e) { String message = "The store '" + storeName + "' version " + version + " was not disabled because of an unexpected exception."; logger.error(logMessagePrefix + message, e); response.setDisableSuccess(false).setInfo(message); } if (response.getDisableSuccess()) { // Then we also want to put the server in offline mode VAdminProto.SetOfflineStateRequest offlineStateRequest = VAdminProto.SetOfflineStateRequest.newBuilder() .setOfflineMode(true).build(); handleSetOfflineState(offlineStateRequest); } return response.build(); }
From source file:voldemort.server.protocol.admin.AdminServiceRequestHandler.java
private Message handleFetchFailure(VAdminProto.HandleFetchFailureRequest handleFetchFailure) { String storeName = handleFetchFailure.getStoreName(); long pushVersion = handleFetchFailure.getPushVersion(); String extraInfo = handleFetchFailure.getInfo(); Properties extraInfoProperties = new Properties(); try {/*from w ww . j a va 2 s . c o m*/ extraInfoProperties.load(new StringReader(extraInfo)); } catch (IOException e) { logger.error("Got IOException while trying to decipher a HandleFetchFailureRequest's info.", e); } logger.info("Received HandleFetchFailureRequest:\n" + "\tstore_name: " + storeName + "\n" + "\tpush_version: " + pushVersion + "\n" + "\tinfo: " + extraInfoProperties.toString()); VAdminProto.HandleFetchFailureResponse.Builder response = VAdminProto.HandleFetchFailureResponse .newBuilder(); AdminClient adminClient = AdminClient.createTempAdminClient(voldemortConfig, metadataStore.getCluster(), 1); int maxNodeFailure = voldemortConfig.getHighAvailabilityPushMaxNodeFailures(); Set<Integer> nodesFailedInThisFetch = Sets.newHashSet(handleFetchFailure.getFailedNodesList()); int failureCount = nodesFailedInThisFetch.size(); boolean swapIsPossible = false; String responseMessage = ""; if (failureCount > maxNodeFailure) { // Too many nodes failed to tolerate this strategy... let's bail out. responseMessage = "We cannot use pushHighAvailability because there is more than " + maxNodeFailure + " nodes that failed their fetches..."; logger.error(responseMessage); } else { FailedFetchLock distributedLock = null; try { Class<? extends FailedFetchLock> failedFetchLockClass = (Class<? extends FailedFetchLock>) Class .forName(voldemortConfig.getHighAvailabilityPushLockImplementation()); Props props = new Props(extraInfoProperties); // Pass both server properties and the remote job's properties to the FailedFetchLock constructor Object[] failedFetchLockParams = new Object[] { voldemortConfig, props }; distributedLock = ReflectUtils.callConstructor(failedFetchLockClass, failedFetchLockParams); distributedLock.acquireLock(); Set<Integer> alreadyDisabledNodes = distributedLock.getDisabledNodes(); Set<Integer> allNodesToBeDisabled = Sets.newHashSet(); allNodesToBeDisabled.addAll(alreadyDisabledNodes); allNodesToBeDisabled.addAll(nodesFailedInThisFetch); if (allNodesToBeDisabled.size() > maxNodeFailure) { // Too many exceptions to tolerate this strategy... let's bail out. responseMessage = "We cannot use pushHighAvailability because it would bring the total number of " + "nodes with disabled stores to more than " + maxNodeFailure + "..."; logger.error(responseMessage); } else { String nodesString = "node"; if (nodesFailedInThisFetch.size() > 1) { // Good grammar is important son nodesString += "s"; } nodesString += " ["; boolean firstNode = true; for (Integer nodeId : nodesFailedInThisFetch) { logger.warn("Will disable store '" + storeName + "' on node " + nodeId); distributedLock.addDisabledNode(nodeId, storeName, pushVersion); if (firstNode) { firstNode = false; } else { nodesString += ", "; } nodesString += nodeId; response.addDisableStoreResponses(adminClient.readonlyOps.disableStoreVersion(nodeId, storeName, pushVersion, extraInfo)); } nodesString += "]"; swapIsPossible = true; responseMessage = "Swap will be possible even though " + nodesString + " failed to fetch."; logger.info(responseMessage); } } catch (ClassNotFoundException e) { String logMessage = "Failed to find requested FailedFetchLock implementation while setting up pushHighAvailability. "; logger.error(responseMessage, e); responseMessage = logMessage + "\n" + ExceptionUtils.stackTraceToString(e); } catch (Exception e) { String logMessage = "Got exception while trying to execute pushHighAvailability. "; logger.error(responseMessage, e); responseMessage = logMessage + "\n" + ExceptionUtils.stackTraceToString(e); } finally { if (distributedLock != null) { try { distributedLock.releaseLock(); } catch (Exception e) { logger.error("Error while trying to release the shared lock used for pushHighAvailability!", e); } finally { try { distributedLock.close(); } catch (Exception inception) { logger.error( "Error while trying to close the shared lock used for pushHighAvailability!", inception); } } } } } response.setSwapIsPossible(swapIsPossible); response.setInfo(responseMessage); return response.build(); }
From source file:org.apache.hupa.server.InMemoryIMAPStoreCache.java
private Session createSession(final User user) { Properties props = new Properties(); Settings settings = user.getSettings(); props.setProperty("mail.mime.decodetext.strict", "false"); if (settings.getImapSecure()) { props.setProperty("mail.store.protocol", "imaps"); props.setProperty("mail.imaps.connectionpoolsize", connectionPoolSize + ""); props.setProperty("mail.imaps.connectionpooltimeout", timeout + ""); if (trustSSL) { props.setProperty("mail.imaps.ssl.trust", settings.getImapServer()); }/*from ww w .j ava 2s .co m*/ } else { props.setProperty("mail.imap.connectionpoolsize", connectionPoolSize + ""); props.setProperty("mail.imap.connectionpooltimeout", timeout + ""); } if (settings.getSmtpSecure()) { if (settings.getSmtpPort() == 587) { props.setProperty("mail.smtp.starttls.enable", "true"); props.setProperty("mail.transport.protocol.rfc822", "smtp"); } else { props.setProperty("mail.transport.protocol.rfc822", "smtps"); props.setProperty("mail.smtps.ssl.enable", "true"); if (trustSSL) { props.setProperty("mail.smtps.ssl.trust", settings.getSmtpServer()); } } } else { props.setProperty("mail.transport.protocol.rfc822", "smtp"); } props.setProperty("mail.smtp.host", settings.getSmtpServer()); props.setProperty("mail.smtps.host", settings.getSmtpServer()); props.setProperty("mail.smtp.port", settings.getSmtpPort() + ""); props.setProperty("mail.smtps.port", settings.getSmtpPort() + ""); Authenticator auth = null; if (settings.getSmtpAuth() && user.getPassword() != null && user.getName() != null) { props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtps.auth", "true"); auth = new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { String userId = user.getId(); StackTraceElement[] sElms = Thread.currentThread().getStackTrace(); for (StackTraceElement e : sElms) { if (e.getClassName().equals(InMemoryIMAPStoreCache.class.getName()) && e.getMethodName().equals("get")) { // We try with the id part the second time (unix imap/smtp auth compatible) if (userId.matches(".*@.*")) { userId = userId.replaceFirst("@.*", ""); user.setId(userId); break; } else { return null; } } } return new PasswordAuthentication(userId, user.getPassword()); } }; } Session ses = Session.getInstance(props, auth); ses.setDebug(debug && logger.isDebugEnabled()); logger.debug("Created session " + user.getName() + "\n" + settings + "\n" + props.toString().replaceAll(",", ",\n ")); return ses; }
From source file:org.wso2.carbon.data.provider.utils.RDBMSTableTestUtils.java
private static DataSource initDataSource() { String databaseType = System.getenv("DATABASE_TYPE"); if (databaseType == null) { databaseType = TestType.H2.toString(); }/*from ww w . jav a 2 s .c o m*/ TestType type = RDBMSTableTestUtils.TestType.valueOf(databaseType); user = System.getenv("DATABASE_USER"); password = System.getenv("DATABASE_PASSWORD"); String port = System.getenv("PORT"); Properties connectionProperties = new Properties(); switch (type) { case MySQL: url = connectionUrlMysql.replace("{{container.ip}}", getIpAddressOfContainer()) .replace("{{container.port}}", port); driverClassName = JDBC_DRIVER_CLASS_NAME_MYSQL; dropTableQuery = "DROP TABLE IF EXISTS Foo_Table"; createTableQuery = "CREATE TABLE IF NOT EXISTS Foo_Table (recipe_id INT NOT NULL," + "recipe_name VARCHAR(30) NOT NULL,PRIMARY KEY (recipe_id), UNIQUE (recipe_name))"; recordsTableQuery = "INSERT INTO Foo_Table (recipe_id, recipe_name) VALUES (1,'Tacos'), (2,'Tomato " + "Soup'), (3, 'Grilled Cheese')"; recordInsertQuery = "INSERT INTO Foo_Table VALUES (?, ?)"; break; case H2: url = CONNECTION_URL_H2; driverClassName = JDBC_DRIVER_CLASS_NAME_H2; user = USERNAME; password = PASSWORD; dropTableQuery = "DROP TABLE IF EXISTS Foo_Table"; createTableQuery = "CREATE TABLE IF NOT EXISTS Foo_Table (recipe_id INT NOT NULL," + "recipe_name VARCHAR(30) NOT NULL,PRIMARY KEY (recipe_id), UNIQUE (recipe_name))"; recordsTableQuery = "INSERT INTO Foo_Table (recipe_id, recipe_name) VALUES (1,'Tacos'), (2,'Tomato " + "Soup'), (3, " + "'Grilled Cheese')"; recordInsertQuery = "INSERT INTO Foo_Table VALUES (?, ?)"; break; case POSTGRES: url = connectionUrlPostgres.replace("{{container.ip}}", getIpAddressOfContainer()) .replace("{{container.port}}", port); driverClassName = JDBC_DRIVER_CLASS_POSTGRES; dropTableQuery = "DROP TABLE IF EXISTS Foo_Table"; createTableQuery = "CREATE TABLE IF NOT EXISTS Foo_Table (recipe_id INT NOT NULL," + "recipe_name VARCHAR(30) NOT NULL,PRIMARY KEY (recipe_id), UNIQUE (recipe_name))"; recordsTableQuery = "INSERT INTO Foo_Table (recipe_id, recipe_name) VALUES (1,'Tacos'), (2,'Tomato " + "Soup'), (3, 'Grilled Cheese')"; recordInsertQuery = "INSERT INTO Foo_Table VALUES (?, ?)"; break; case ORACLE: url = connectionUrlOracle.replace("{{container.ip}}", getIpAddressOfContainer()) .replace("{{container.port}}", port); driverClassName = JDBC_DRIVER_CLASS_NAME_ORACLE; dropTableQuery = "BEGIN EXECUTE IMMEDIATE 'DROP TABLE Foo_Table';EXCEPTION WHEN OTHERS THEN IF " + "SQLCODE != -942 THEN RAISE;END IF;END;"; createTableQuery = "CREATE TABLE Foo_Table (recipe_id number(10) NOT NULL, recipe_name varchar2(30) " + "NOT NULL, CONSTRAINT recipe_name PRIMARY KEY (recipe_id))"; recordsTableQuery = "INSERT ALL INTO Foo_Table (recipe_id, recipe_name) VALUES (1,'Tacos') INTO " + "Foo_Table (recipe_id, recipe_name) VALUES (2,'Tomato Soup') INTO Foo_Table (recipe_id, " + "recipe_name) VALUES (3,'Grilled Cheese') SELECT * FROM DUAL"; recordInsertQuery = "INSERT INTO Foo_Table VALUES (?, ?)"; break; case MSSQL: url = connectionUrlMsSQL.replace("{{container.ip}}", getIpAddressOfContainer()) .replace("{{container.port}}", port); driverClassName = JDBC_DRIVER_CLASS_MSSQL; dropTableQuery = "DROP TABLE IF EXISTS Foo_Table"; createTableQuery = "CREATE TABLE Foo_Table (recipe_id INT NOT NULL," + "recipe_name VARCHAR(30) NOT NULL,PRIMARY KEY (recipe_id), UNIQUE (recipe_name))"; recordsTableQuery = "INSERT INTO Foo_Table (recipe_id, recipe_name) VALUES (1,'Tacos'), (2,'Tomato " + "Soup'), (3, 'Grilled Cheese')"; recordInsertQuery = "INSERT INTO Foo_Table VALUES (?, ?)"; break; case DB2: url = connectionUrlDB2.replace("{{container.ip}}", getIpAddressOfContainer()) .replace("{{container.port}}", port); driverClassName = JDBC_DRIVER_CLASS_DB2; break; } log.info("URL of docker instance: " + url); connectionProperties.setProperty("jdbcUrl", url); connectionProperties.setProperty("driverClassName", driverClassName); connectionProperties.setProperty("dataSource.user", user); connectionProperties.setProperty("dataSource.password", password); connectionProperties.setProperty("poolName", "Test_Pool"); log.info(connectionProperties.toString()); HikariConfig config = new HikariConfig(connectionProperties); return new HikariDataSource(config); }
From source file:it.txt.ens.client.subscriber.printer.osgi.test.ENSEventPrinterTest.java
private void declareEventPrinter(Properties properties) throws Exception { LOGGER.fine("Declaring an event printer"); Configuration eventListenerConfig = configAdmin .createFactoryConfiguration(RegisteredServices.EVENT_PRINTER_LISTENER_SERVICE_PID, null); Dictionary<String, Object> configuration = MapConverter.convert(properties); configuration.put(FilterAttributes.EVENT_PRINTER_OWNER_ID, context.getBundle().getBundleId()); // configuration.put(FilterAttributes.IMPLEMENTATION_KEY, EventPrinterListenersMSF.IMPLEMENTATION_ID); eventListenerConfig.update(configuration); // Object patternOBJ = properties.get(ENSResourceFactory.PATTERN); // String pattern = null; // if (patternOBJ == null) { // Object resourceOBJ = properties.get(ENSResourceFactory.URI); // if (resourceOBJ == null) // throw new Exception("Missing property " + ENSResourceFactory.URI); // else { // ServiceReference<ENSResourceFactory> resourceFactorySR = context.getServiceReference( // ENSResourceFactory.class); // ENSResourceFactory resourceFactory = context.getService(resourceFactorySR); // try { // pattern = resourceFactory.create(new URI(resourceOBJ.toString())).getPattern(); // } finally { // context.ungetService(resourceFactorySR); // } // } // } else { // pattern = (String) patternOBJ; // }/*from w ww . j av a2 s . c o m*/ EqualsFilter ownership = new EqualsFilter(FilterAttributes.EVENT_PRINTER_OWNER_ID, (int) context.getBundle().getBundleId()); // EqualsFilter implementation = new EqualsFilter(FilterAttributes.IMPLEMENTATION_KEY, // EventPrinterListenersMSF.IMPLEMENTATION_ID); // EqualsFilter patternFilter = new EqualsFilter(ENSResource.PATTERN_PARAMETER_NAME, pattern); AndFilter filter = new AndFilter()/*.and(implementation)*/.and(ownership)/*.and(patternFilter)*/; // Filter f; try { f = FrameworkUtil.createFilter(filter.encode()); } catch (InvalidSyntaxException e) { throw new ConfigurationException(null, "An error occurred while tracking subscription services using filter " + filter.encode(), e); } ServiceTracker<ENSEventPrinter, ENSEventPrinter> tracker = new ServiceTracker<ENSEventPrinter, ENSEventPrinter>( context, f, null); tracker.open(); ENSEventPrinter eventPrinter = tracker.waitForService(TIMEOUT); tracker.close(); assertNotNull("No event printer has been found using the filter " + f.toString(), eventPrinter); // Collection<ServiceReference<ENSEventPrinter>> references; // long startTime = System.currentTimeMillis(); // do { // references = context.getServiceReferences(ENSEventPrinter.class, f.toString()); // } while (references.isEmpty() && (System.currentTimeMillis() - startTime) <= TIMEOUT); // // assertTrue("No event printer has been found using the filter " + f.toString(),references.iterator().hasNext()); // ServiceReference<ENSEventPrinter> eventPrinterSR = references.iterator().next(); // assertNotNull(eventPrinterSR); // serviceReferences.add(eventPrinterSR); // ENSEventPrinter eventPrinter = context.getService(eventPrinterSR); LOGGER.fine("Created ENS event printer with configuration: " + properties.toString()); eventPrinter.start(); }
From source file:org.ejbca.ui.cli.ca.CaType.java
@Override public CommandResult execute(ParameterContainer parameters) { // Install BC provider CryptoProviderTools.installBCProviderIfNotAvailable(); String profileName = parameters.get(CERTIFICATE_PROFILE_KEY); final String superAdminCN = parameters.get(SUPERADMIN_CN_KEY); //Default is X509 final CaType type; if (parameters.get(TYPE_KEY) != null) { type = CaType.lookupCaType(parameters.get(TYPE_KEY)); if (type == null) { log.error("CA type of name " + parameters.get(TYPE_KEY) + " unknown. Available types: " + CaType.getTypeNames()); return CommandResult.FUNCTIONAL_FAILURE; }/* www. j av a2 s . c o m*/ } else { type = CaType.X509; } final String explicitEcc = (parameters.get(EXPLICIT_ECC_KEY) != null ? Boolean.TRUE.toString() : Boolean.FALSE.toString()); final String extcachainName = parameters.get(EXTERNAL_CHAIN_KEY); final String caname = parameters.get(CA_NAME_KEY); final String dn = CertTools.stringToBCDNString(StringTools.strip(parameters.get(DN_KEY))); final String catokentype = parameters.get(TOKEN_TYPE_KEY); String catokenpassword = StringTools.passwordDecryption(parameters.get(TOKEN_PASSWORD_KEY), "ca.tokenpassword"); if (StringUtils.equals(catokenpassword, "prompt")) { getLogger().info("Enter CA token password: "); getLogger().info(""); catokenpassword = String.valueOf(System.console().readPassword()); } final String keyspec = parameters.get(KEY_SPEC_KEY); final String keytype = parameters.get(KEY_TYPE_KEY); final long validity = Long.parseLong(parameters.get(VALIDITY_KEY)); String policyId = parameters.get(POLICY_ID_KEY); final ArrayList<CertificatePolicy> policies = new ArrayList<CertificatePolicy>(1); if ((policyId != null) && (policyId.toLowerCase().trim().equals("null"))) { policyId = null; } else { String[] array = policyId.split(" "); for (int i = 0; i < array.length; i += 2) { String id = array[i + 0]; String cpsurl = ""; if (array.length > i + 1) { cpsurl = array[i + 1]; } policies.add(new CertificatePolicy(id, CertificatePolicy.id_qt_cps, cpsurl)); } } String signAlg = parameters.get(SIGNING_ALGORITHM_KEY); Properties cryptoTokenProperties = new Properties(); String caTokenPropertiesFile = parameters.get(CA_TOKEN_PROPERTIES_KEY); if (caTokenPropertiesFile != null && "soft".equals(catokentype)) { log.error("Can't define a CAToken properties file for a soft token."); return CommandResult.FUNCTIONAL_FAILURE; } else if (caTokenPropertiesFile != null) { if ((caTokenPropertiesFile != null) && (!caTokenPropertiesFile.equalsIgnoreCase("null"))) { File file = new File(caTokenPropertiesFile); if (!file.exists()) { log.error("CA Token propoerties file " + caTokenPropertiesFile + " does not exist."); return CommandResult.FUNCTIONAL_FAILURE; } else if (file.isDirectory()) { log.error("CA Token propoerties file " + caTokenPropertiesFile + " is a directory."); return CommandResult.FUNCTIONAL_FAILURE; } else { try { cryptoTokenProperties.load(new FileInputStream(caTokenPropertiesFile)); } catch (FileNotFoundException e) { //Can't happen throw new IllegalStateException( "Newly referenced file " + caTokenPropertiesFile + " was not found.", e); } catch (IOException e) { throw new IllegalStateException("Unknown exception was caught when reading input stream", e); } } } } int signedByCAId = CAInfo.SELFSIGNED; if (parameters.get(SIGNED_BY) != null) { if (StringUtils.equalsIgnoreCase("External", parameters.get(SIGNED_BY))) { signedByCAId = CAInfo.SIGNEDBYEXTERNALCA; if (extcachainName == null) { log.error("Signing by external CA requires parameter " + EXTERNAL_CHAIN_KEY); return CommandResult.FUNCTIONAL_FAILURE; } } else { signedByCAId = Integer.valueOf(parameters.get(SIGNED_BY)); } } // Check that the CA doesn't exist already getLogger().debug("Checking that CA doesn't exist: " + caname); if (getCAInfo(getAuthenticationToken(), caname) != null) { getLogger().error("Error: CA '" + caname + "' exists already"); return CommandResult.FUNCTIONAL_FAILURE; } // Get the profile ID from the name if we specified a certain profile name int certificateProfileId = CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA; if (profileName == null) { if (signedByCAId == CAInfo.SELFSIGNED) { profileName = "ROOTCA"; } else { profileName = "SUBCA"; certificateProfileId = CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA; } } else { certificateProfileId = EjbRemoteHelper.INSTANCE.getRemoteSession(CertificateProfileSessionRemote.class) .getCertificateProfileId(profileName); if (certificateProfileId == 0) { getLogger().info("Error: Certificate profile with name '" + profileName + "' does not exist."); return CommandResult.FUNCTIONAL_FAILURE; } CertificateProfile certificateProfile = EjbRemoteHelper.INSTANCE .getRemoteSession(CertificateProfileSessionRemote.class).getCertificateProfile(profileName); if (certificateProfile.getType() != CertificateConstants.CERTTYPE_ROOTCA && certificateProfile.getType() != CertificateConstants.CERTTYPE_SUBCA) { getLogger().info("Error: Certificate profile " + profileName + " is not of type ROOTCA or SUBCA."); return CommandResult.FUNCTIONAL_FAILURE; } } if (KeyTools.isUsingExportableCryptography()) { getLogger().warn("WARNING!"); getLogger().warn("WARNING: Using exportable strength crypto!"); getLogger().warn("WARNING!"); getLogger().warn( "The Unlimited Strength Crypto policy files have not been installed. EJBCA may not function correctly using exportable crypto."); getLogger().warn( "Please install the Unlimited Strength Crypto policy files as documented in the Installation guide."); getLogger().warn("Sleeping 10 seconds..."); getLogger().warn(""); try { Thread.sleep(10000); } catch (InterruptedException e) { throw new IllegalStateException("Thread.sleep was interrupted for unknown reason.", e); } } getLogger().info("Initializing CA"); getLogger().info("Generating rootCA keystore:"); getLogger().info("CA Type:" + type.getTypeName()); getLogger().info("CA name: " + caname); getLogger().info("SuperAdmin CN: " + superAdminCN); getLogger().info("DN: " + dn); getLogger().info("CA token type: " + catokentype); getLogger().info("CA token password: " + (catokenpassword == null ? "null" : "hidden")); getLogger().info("Keytype: " + keytype); getLogger().info("Keyspec: " + keyspec); getLogger().info("Validity (days): " + validity); getLogger().info("Policy ID: " + policyId); getLogger().info("Signature alg: " + signAlg); getLogger().info("Certificate profile: " + profileName); getLogger().info("CA token properties: " + cryptoTokenProperties.toString()); if (StringUtils.equalsIgnoreCase(explicitEcc, "true")) { // Set if we should use explicit ECC parameters of not. On Java 6 this renders the created CA certificate not serializable getLogger().info("Explicit ECC public key parameters: " + explicitEcc); cryptoTokenProperties.setProperty(CryptoToken.EXPLICIT_ECC_PUBLICKEY_PARAMETERS, explicitEcc); } try { String signedByStr = "Signed by: "; if ((signedByCAId != CAInfo.SELFSIGNED) && (signedByCAId != CAInfo.SIGNEDBYEXTERNALCA)) { try { CAInfo cainfo = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class) .getCAInfo(getAuthenticationToken(), signedByCAId); signedByStr += cainfo.getName(); } catch (CADoesntExistsException e) { throw new IllegalArgumentException("CA with id " + signedByCAId + " does not exist."); } } else if (signedByCAId == CAInfo.SELFSIGNED) { signedByStr += "Self signed"; } else if (signedByCAId == CAInfo.SIGNEDBYEXTERNALCA) { signedByStr += "External CA"; } getLogger().info(signedByStr); if (superAdminCN != null) { try { initAuthorizationModule(getAuthenticationToken(), dn.hashCode(), superAdminCN); } catch (RoleExistsException e) { log.error("Tryin to initialize Authorization module (since " + SUPERADMIN_CN_KEY + " was set), but module is already initialized."); return CommandResult.FUNCTIONAL_FAILURE; } } // Transform our mixed properties into CA Token properties and cryptoTokenProperties final Properties caTokenProperties = new Properties(); final String defaultAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING); if (defaultAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING, defaultAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING); } else { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING, CAToken.SOFTPRIVATEDECKEYALIAS); } final String certSignAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING); if (certSignAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING, certSignAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING); } else { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); } final String crlSignAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING); if (crlSignAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, crlSignAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING); } else { final String certSignValue = caTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, certSignValue); } final String hardTokenEncAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT_STRING); if (hardTokenEncAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT_STRING, hardTokenEncAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT_STRING); } final String keyEncAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT_STRING); if (keyEncAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT_STRING, keyEncAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT_STRING); } final String testKeyAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_TESTKEY_STRING); if (testKeyAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_TESTKEY_STRING, testKeyAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_TESTKEY_STRING); } // If authentication code is provided as "null", use the default token password for soft tokens (from cesecore.properties), and auto activation // If a user defined authentication code is provided, use this and do not enable auto activation for soft tokens final char[] authenticationCode; if (StringUtils.equalsIgnoreCase(catokenpassword, "null")) { authenticationCode = null; // auto activation is enabled by default when using the default soft token pwd, which is used by default } else { authenticationCode = catokenpassword.toCharArray(); } // We must do this in order to not set the default password when creating a new soft CA token // A bit tricky, but thats how it is as of EJBCA 5.0.x, 2012-05. final String className; if (StringUtils.equalsIgnoreCase(catokentype, "soft")) { className = SoftCryptoToken.class.getName(); if (authenticationCode != null) { getLogger().info("Non default password used for soft CA token, auto activation disabled."); cryptoTokenProperties.setProperty(SoftCryptoToken.NODEFAULTPWD, "true"); } } else { className = PKCS11CryptoToken.class.getName(); } // Create the CryptoToken final CryptoTokenManagementSessionRemote cryptoTokenManagementSession = EjbRemoteHelper.INSTANCE .getRemoteSession(CryptoTokenManagementSessionRemote.class); int cryptoTokenId; try { try { cryptoTokenId = cryptoTokenManagementSession.createCryptoToken(getAuthenticationToken(), caname, className, cryptoTokenProperties, null, authenticationCode); } catch (CryptoTokenNameInUseException e) { // If the name was already in use we simply add a timestamp to the name to make it unique final String postfix = "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); try { cryptoTokenId = cryptoTokenManagementSession.createCryptoToken(getAuthenticationToken(), caname + postfix, className, cryptoTokenProperties, null, authenticationCode); } catch (CryptoTokenNameInUseException e1) { //Shouldn't be able to happen. throw new IllegalStateException( "Crypto token name was in use, even though a unique name was just generated.", e); } } } catch (NoSuchSlotException e) { log.error("Slot as defined in the file " + caTokenPropertiesFile + " was not found: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } catch (CryptoTokenAuthenticationFailedException e) { log.error("Authentication to crypto token failed: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } // Create the CA Token final CAToken caToken = new CAToken(cryptoTokenId, caTokenProperties); caToken.setSignatureAlgorithm(signAlg); caToken.setEncryptionAlgorithm(AlgorithmConstants.SIGALG_SHA1_WITH_RSA); // Generate CA keys if it is a soft CryptoToken if ("soft".equals(catokentype)) { final String signKeyAlias = caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN); final String signKeySpecification = "DSA".equals(keytype) ? "DSA" + keyspec : keyspec; try { cryptoTokenManagementSession.createKeyPair(getAuthenticationToken(), cryptoTokenId, signKeyAlias, signKeySpecification); } catch (InvalidAlgorithmParameterException e) { log.error(signKeySpecification + " was not a valid alias: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } catch (InvalidKeyException e) { log.error("Key generation for alias " + signKeyAlias + " failed." + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } final String defaultKeyAlias = caToken .getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT); // Decryption key must be RSA final String defaultKeySpecification = "RSA".equals(keytype) ? keyspec : "2048"; try { cryptoTokenManagementSession.createKeyPair(getAuthenticationToken(), cryptoTokenId, defaultKeyAlias, defaultKeySpecification); } catch (InvalidAlgorithmParameterException e) { log.error(defaultKeySpecification + " was not a valid alias: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } catch (InvalidKeyException e) { log.error("Key generation for alias " + defaultKeyAlias + " failed: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } } // Create the CA Info CAInfo cainfo = null; switch (type) { case CVC: // Get keysequence from SERIALNUMBER in DN is it exists final String keysequence = CertTools.getPartFromDN(dn, "SN"); if (keysequence != null) { getLogger().info("CVC key sequence: " + keysequence); caToken.setKeySequence(keysequence); if (StringUtils.isNumeric(keysequence)) { getLogger().info("CVC key sequence format is numeric."); caToken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); } else { getLogger().info("CVC key sequence format is alphanumeric."); caToken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_ALPHANUMERIC); } } cainfo = createCVCCAInfo(dn, caname, certificateProfileId, validity, signedByCAId, caToken); break; case X509: //Default, slip below. default: // Create and active OSCP CA Service. ArrayList<ExtendedCAServiceInfo> extendedcaservices = new ArrayList<ExtendedCAServiceInfo>(); String extendedServiceKeySpec = keyspec; if (keytype.equals(AlgorithmConstants.KEYALGORITHM_RSA)) { // Never use larger keys than 2048 bit RSA for OCSP signing int len = Integer.parseInt(extendedServiceKeySpec); if (len > 2048) { extendedServiceKeySpec = "2048"; } } extendedcaservices.add(new XKMSCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE, "CN=XKMSCertificate, " + dn, "", extendedServiceKeySpec, keytype)); extendedcaservices.add(new CmsCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE, "CN=CmsCertificate, " + dn, "", extendedServiceKeySpec, keytype)); extendedcaservices.add(new HardTokenEncryptCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE)); extendedcaservices.add(new KeyRecoveryCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE)); cainfo = createX509CaInfo(dn, caname, certificateProfileId, validity, signedByCAId, caToken, policies, extendedcaservices); break; } getLogger().info("Creating CA..."); // Make an error control before starting do do something else. List<Certificate> cachain = null; if (cainfo.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) { try { cachain = CertTools.getCertsFromPEM(extcachainName); } catch (CertificateException e) { log.error("Certificate file " + extcachainName + " did not contain a correct certificate."); return CommandResult.FUNCTIONAL_FAILURE; } if (cachain == null || cachain.isEmpty()) { log.error( extcachainName + " does not seem to exist or contain any certificates in PEM format."); return CommandResult.FUNCTIONAL_FAILURE; } } try { EjbRemoteHelper.INSTANCE.getRemoteSession(CAAdminSessionRemote.class) .createCA(getAuthenticationToken(), cainfo); } catch (CAExistsException e) { log.error("CA " + caname + " already exists."); return CommandResult.FUNCTIONAL_FAILURE; } catch (InvalidAlgorithmException e) { log.error("Algirithm was not valid: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } try { if (StringUtils.equalsIgnoreCase(explicitEcc, "true")) { getLogger().info( "Not re-reading CAInfo, since explicit ECC parameters were used, which is not serializable on Java 6. Use Web GUI for further interactions."); } else { CAInfo newInfo; newInfo = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class) .getCAInfo(getAuthenticationToken(), caname); int caid = newInfo.getCAId(); getLogger().info("CAId for created CA: " + caid); } if (cainfo.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) { getLogger().info("Creating a CA signed by an external CA, creating certificate request."); CAInfo info = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class) .getCAInfo(getAuthenticationToken(), caname); if (info.getStatus() != CAConstants.CA_WAITING_CERTIFICATE_RESPONSE) { log.error( "Creating a CA signed by an external CA should result in CA having status, CA_WAITING_CERTIFICATE_RESPONSE. Terminating process, please troubleshoot."); return CommandResult.FUNCTIONAL_FAILURE; } byte[] request; try { request = EjbRemoteHelper.INSTANCE.getRemoteSession(CAAdminSessionRemote.class).makeRequest( getAuthenticationToken(), info.getCAId(), cachain, info.getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); } catch (CertPathValidatorException e) { log.error("Error creating certificate request for CA:" + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } final String filename = info.getName() + "_csr.der"; FileOutputStream fos = new FileOutputStream(filename); fos.write(request); fos.close(); getLogger().info( "Created CSR for CA, to be sent to external CA. Wrote CSR to file '" + filename + "'."); } else { getLogger().info("Created and published initial CRL."); } } catch (CADoesntExistsException e) { throw new IllegalStateException("Newly created CA does not exist.", e); } getLogger().info("CA initialized"); getLogger().info("Note that any open browser sessions must be restarted to interact with this CA."); } catch (AuthorizationDeniedException e) { log.error("Current CLI user not authorized to create CA: " + e.getMessage()); return CommandResult.AUTHORIZATION_FAILURE; } catch (CryptoTokenOfflineException e) { log.error("Crypto token was unavailable: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } catch (IOException e) { throw new IllegalStateException("Unknown IOException was caught.", e); } return CommandResult.SUCCESS; }
From source file:com.smartmarmot.common.Configurator.java
private static Query getQueryProperties(Properties _propsq, String _queryName) throws Exception { try {//from w ww . j av a2 s . c o m String query = ""; try { query = new String(_propsq.getProperty(_queryName + "." + Constants.QUERY_POSTFIX)); } catch (Exception ex) { SmartLogger.logThis(Level.ERROR, "Error while getting " + _queryName + "." + Constants.QUERY_POSTFIX + " " + ex.getMessage()); } String noDataFound = ""; try { noDataFound = new String(_propsq.getProperty(_queryName + "." + Constants.QUERY_NO_DATA_FOUND)); } catch (Exception ex) { SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.QUERY_NO_DATA_FOUND + " null or not present " + ex.getMessage()); } String whenNotAlive = ""; try { whenNotAlive = new String(_propsq.getProperty(_queryName + "." + Constants.QUERY_WHEN_NOT_ALIVE)); } catch (Exception ex) { SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.QUERY_WHEN_NOT_ALIVE + " null or not present " + ex.getMessage()); } String raceCondQuery = ""; try { raceCondQuery = new String(_propsq.getProperty(_queryName + "." + Constants.RACE_CONDITION_QUERY)); } catch (Exception ex) { SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.RACE_CONDITION_QUERY + " null or not present " + ex.getMessage()); } String raceCondValue = ""; try { raceCondValue = new String(_propsq.getProperty(_queryName + "." + Constants.RACE_CONDITION_VALUE)); } catch (Exception ex) { SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.RACE_CONDITION_VALUE + " null or not present " + ex.getMessage()); } /** * set Period if not defined period =2 min. */ int period = -1; try { period = new Integer(_propsq.getProperty(_queryName + "." + Constants.QUERY_PERIOD)); } catch (Exception ex) { SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.QUERY_PERIOD + " null or not present " + ex.getMessage()); try { period = new Integer(_propsq.getProperty(Constants.QUERY_DEFAULT_PERIOD)); } catch (Exception ex1) { SmartLogger.logThis(Level.DEBUG, "Note: " + Constants.QUERY_DEFAULT_PERIOD + " null or not present using default values 2 min."); period = 2; } } Boolean active = true; try { String active_str = _propsq.getProperty(_queryName + "." + Constants.QUERY_ACTIVE); if (active_str != null) { if (active_str.equalsIgnoreCase("false")) { active = false; } } } catch (Exception ex) { SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.QUERY_ACTIVE + " null or not present " + ex.getMessage()); SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.QUERY_ACTIVE + " null or not present using default values TRUE"); } Boolean trim = true; try { String trim_str = _propsq.getProperty(_queryName + "." + Constants.QUERY_TRIM); if (trim_str != null) { if (trim_str.equalsIgnoreCase("false")) { trim = false; } } } catch (Exception ex) { SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.QUERY_TRIM + " null or not present " + ex.getMessage()); SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.QUERY_TRIM + " null or not present using default values TRUE"); } Boolean space = false; try { String space_str = _propsq.getProperty(_queryName + "." + Constants.QUERY_SPACE); if (space_str != null) { if (space_str.equalsIgnoreCase("true")) { space = true; } } } catch (Exception ex) { SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.QUERY_SPACE + " null or not present " + ex.getMessage()); SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.QUERY_SPACE + " null or not present using default values TRUE"); } List<Integer> excludeColumns = new ArrayList<Integer>(); try { String excludeColumnsList = new String( _propsq.getProperty(_queryName + "." + Constants.QUERY_EXCLUDE_COLUMNS)); StringTokenizer st = new StringTokenizer(excludeColumnsList, Constants.DELIMITER); while (st.hasMoreTokens()) { String token = st.nextToken().toString(); Integer tmpInteger = new Integer(token); excludeColumns.add(tmpInteger); } } catch (Exception ex) { SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.QUERY_EXCLUDE_COLUMNS + " error " + ex.getMessage()); } List<Integer> raceExcludeColumns = new ArrayList<Integer>(); try { String excludeColumnsList = new String( _propsq.getProperty(_queryName + "." + Constants.RACE_CONDITION_EXCLUDE_COLUMNS)); StringTokenizer st = new StringTokenizer(excludeColumnsList, Constants.DELIMITER); while (st.hasMoreTokens()) { String token = st.nextToken().toString(); Integer tmpInteger = new Integer(token); excludeColumns.add(tmpInteger); } } catch (Exception ex) { SmartLogger.logThis(Level.DEBUG, "Note: " + _queryName + "." + Constants.RACE_CONDITION_EXCLUDE_COLUMNS + " error " + ex.getMessage()); } Query q = new Query(query, _queryName, noDataFound, whenNotAlive, raceCondQuery, raceCondValue, period, active, trim, space, excludeColumns, raceExcludeColumns); return q; } catch (Exception ex) { SmartLogger.logThis(Level.ERROR, "Error on Configurator on getQueryProperties(" + _propsq.toString() + ") " + ex.getMessage()); return null; } }