List of usage examples for java.lang Thread setName
public final synchronized void setName(String name)
From source file:com.intuit.tank.harness.APITestHarness.java
private void startHttp(String baseUrl) { isLocal = false;/*w ww .jav a 2s. c om*/ CommandListener.startHttpServer(tankConfig.getAgentConfig().getAgentPort()); if (baseUrl == null) { baseUrl = AmazonUtil.getControllerBaseUrl(); } AgentServiceClient client = new AgentServiceClient(baseUrl); String instanceUrl = null; int tries = 0; while (instanceUrl == null) { try { instanceUrl = "http://" + AmazonUtil.getPublicHostName() + ":" + tankConfig.getAgentConfig().getAgentPort(); LOG.info("MyInstanceURL = " + instanceUrl); } catch (IOException e1) { tries++; if (tries < 10) { try { Thread.sleep(200); } catch (InterruptedException e) { // ignore } } else { LOG.error("Error getting amazon host. maybe local."); String publicIp = new HostInfo().getPublicIp(); if (!publicIp.equals(HostInfo.UNKNOWN)) { instanceUrl = "http://" + publicIp + ":" + tankConfig.getAgentConfig().getAgentPort(); LOG.info("MyInstanceURL from hostinfo = " + instanceUrl); } else { instanceUrl = "http://localhost:" + tankConfig.getAgentConfig().getAgentPort(); } } } } LOG.info("MyInstanceURL = " + instanceUrl); if (capacity < 0) { capacity = AmazonUtil.getCapacity(); } VMRegion region = VMRegion.STANDALONE; if (AmazonUtil.isInAmazon()) { try { region = AmazonUtil.getVMRegion(); } catch (IOException e) { LOG.warn(LogUtil.getLogMessage("Error getting region. using CUSTOM...", LogEventType.System)); } } if (agentRunData.getJobId() == null) { agentRunData.setJobId(AmazonUtil.getJobId()); agentRunData.setStopBehavior(AmazonUtil.getStopBehavior()); } LogUtil.getLogEvent().setJobId(agentRunData.getJobId()); LOG.info(LogUtil.getLogMessage("Active Profile" + agentRunData.getActiveProfile().getDisplayName())); AgentData data = new AgentData(agentRunData.getJobId(), instanceId, instanceUrl, capacity, region, AmazonUtil.getZone()); try { AgentTestStartData startData = null; int count = 0; LOG.info(LogUtil.getLogMessage("Sending AgentData to controller: " + data.toString(), LogEventType.System)); while (count < 10) { try { startData = client.agentReady(data); break; } catch (Exception e) { LOG.error("Error sending ready: " + e, e); count++; } } writeXmlToFile(startData.getScriptUrl()); agentRunData.setNumUsers(startData.getConcurrentUsers()); agentRunData.setNumStartUsers(startData.getStartUsers()); agentRunData.setRampTime(startData.getRampTime()); agentRunData.setJobId(startData.getJobId()); agentRunData.setUserInterval(startData.getUserIntervalIncrement()); agentRunData.setSimulationTime(startData.getSimulationTime()); agentRunData.setAgentInstanceNum(startData.getAgentInstanceNum()); agentRunData.setTotalAgents(startData.getTotalAgents()); if (startData.getDataFiles() != null) { for (DataFileRequest dfRequest : startData.getDataFiles()) { saveDataFile(dfRequest); } } Thread t = new Thread(new StartedChecker()); t.setName("StartedChecker"); t.setDaemon(false); t.start(); } catch (Exception e) { LOG.error("Error communicating with controller: " + e, e); System.exit(0); } }
From source file:net.dv8tion.jda.core.requests.WebSocketClient.java
@Override public void onThreadCreated(WebSocket websocket, ThreadType threadType, Thread thread) throws Exception { String identifier = api.getIdentifierString(); switch (threadType) { case CONNECT_THREAD: thread.setName(identifier + " MainWS-ConnectThread"); break;/* w ww. j a va 2 s .co m*/ case FINISH_THREAD: thread.setName(identifier + " MainWS-FinishThread"); break; case READING_THREAD: thread.setName(identifier + " MainWS-ReadThread"); break; case WRITING_THREAD: thread.setName(identifier + " MainWS-WriteThread"); break; default: thread.setName(identifier + " MainWS-" + threadType); } }
From source file:custom.SevenZFileExt.java
public InputStream getInputStream(final int bufferSize) { final PipedInputStream in = new PipedInputStream(bufferSize); try {/*from ww w . ja v a 2s .c om*/ final PipedOutputStream out = new PipedOutputStream(in); Thread thread = new Thread(() -> { try { byte[] buffer = new byte[bufferSize]; int len = read(buffer); while (len > 0) { try { out.write(buffer, 0, len); len = read(buffer); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } } out.flush(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } } } }); thread.setName("GenerateInputStreamSeven7File"); thread.start(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return in; }
From source file:org.dasein.cloud.rackspace.compute.CloudServerImages.java
@Override public @Nonnull AsynchronousTask<String> imageVirtualMachine(@Nonnull String vmId, @Nonnull String name, @Nonnull String description) throws CloudException, InternalException { VirtualMachine vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(vmId); if (vm == null) { throw new CloudException("No such virtual machine: " + vmId); }// ww w. j av a 2 s. co m final ImageCreateOptions options = ImageCreateOptions.getInstance(vm, name, description); final AsynchronousTask<String> task = new AsynchronousTask<String>(); Thread t = new Thread() { public void run() { try { task.completeWithResult(capture(options, null).getProviderMachineImageId()); } catch (Throwable t) { task.complete(t); } finally { provider.release(); } } }; provider.hold(); t.setName("Image Capture: " + options.getVirtualMachineId()); t.setDaemon(true); t.start(); return task; }
From source file:com.streamsets.pipeline.stage.origin.hdfs.cluster.ClusterHDFSSourceIT.java
private Thread createThreadForAddingBatch(final SourceRunner sourceRunner, final List<Map.Entry> list) { Thread sourceThread = new Thread() { @Override/*from w w w . j av a 2 s. c o m*/ public void run() { try { ClusterHdfsSource source = (ClusterHdfsSource) sourceRunner.getStage(); source.put(list); } catch (Exception ex) { LOG.error("Error in waiter thread: " + ex, ex); } } }; sourceThread.setName(getClass().getName() + "-sourceThread"); sourceThread.setDaemon(true); sourceThread.start(); return sourceThread; }
From source file:com.twinsoft.convertigo.engine.Engine.java
public static synchronized void start() throws EngineException { if (Engine.theApp == null) { System.out.println("Starting Convertigo Enterprise Mobility Server"); // If the engine has been stopped by the admin, we must reload // properties EnginePropertiesManager.loadProperties(); boolean bProjectsDataCompatibilityMode = Boolean.parseBoolean( EnginePropertiesManager.getProperty(PropertyName.PROJECTS_DATA_COMPATIBILITY_MODE)); if (bProjectsDataCompatibilityMode) { System.out.println("Projects data compatibility mode required"); try { Engine.PROJECTS_PATH = new File(Engine.WEBAPP_PATH + "/projects").getCanonicalPath(); File projectsDir = new File(Engine.PROJECTS_PATH); projectsDir.mkdir();//from w ww. jav a 2s . com } catch (IOException e) { throw new EngineException("Unable to update projects path for compatibility mode", e); } } isStarted = false; isStartFailed = false; RequestableObject.nbCurrentWorkerThreads = 0; Engine.startStopDate = System.currentTimeMillis(); System.out.println("Creating/updating loggers"); String logFile = EnginePropertiesManager.getProperty(PropertyName.LOG4J_APPENDER_CEMSAPPENDER_FILE); System.out.println("Log file: " + logFile); // Main loggers Engine.logConvertigo = Logger.getLogger("cems"); Engine.logEngine = Logger.getLogger("cems.Engine"); Engine.logAdmin = Logger.getLogger("cems.Admin"); Engine.logBeans = Logger.getLogger("cems.Beans"); Engine.logBillers = Logger.getLogger("cems.Billers"); Engine.logEmulators = Logger.getLogger("cems.Emulators"); Engine.logContext = Logger.getLogger("cems.Context"); Engine.logUser = Logger.getLogger("cems.Context.User"); Engine.logUsageMonitor = Logger.getLogger("cems.UsageMonitor"); Engine.logStatistics = Logger.getLogger("cems.Statistics"); Engine.logScheduler = Logger.getLogger("cems.Scheduler"); Engine.logSiteClipper = Logger.getLogger("cems.SiteClipper"); /** #3437 : Disabled ExternalBrowser feature because it's not terminated Engine.logExternalBrowser = Logger.getLogger("cems.ExternalBrowser"); */ Engine.logAudit = Logger.getLogger("cems.Context.Audit"); // Managers Engine.logContextManager = Logger.getLogger("cems.ContextManager"); Engine.logCacheManager = Logger.getLogger("cems.CacheManager"); Engine.logTracePlayerManager = Logger.getLogger("cems.TracePlayerManager"); Engine.logJobManager = Logger.getLogger("cems.JobManager"); Engine.logCertificateManager = Logger.getLogger("cems.CertificateManager"); Engine.logDatabaseObjectManager = Logger.getLogger("cems.DatabaseObjectManager"); Engine.logProxyManager = Logger.getLogger("cems.ProxyManager"); Engine.logDevices = Logger.getLogger("cems.Devices"); Engine.logCouchDbManager = Logger.getLogger("cems.CouchDbManager"); Engine.logSecurityTokenManager = Logger.getLogger("cems.SecurityTokenManager"); // Logger for compatibility issues Engine.log = new LogWrapper(Engine.logConvertigo); LogWrapper.initWrapper(Engine.logEmulators); try { Engine.logEngine.info("==========================================================="); Engine.logEngine.info("Web app home: " + Engine.WEBAPP_PATH); Engine.logEngine.info("User workspace: " + Engine.USER_WORKSPACE_PATH); Engine.logEngine.info("Configuration path: " + Engine.CONFIGURATION_PATH); Engine.logEngine.info("Projects path: " + Engine.PROJECTS_PATH); if (bProjectsDataCompatibilityMode) { Engine.logEngine.warn("Projects data compatibility mode required"); } Engine.logEngine.info("Log: " + Engine.LOG_PATH); if (cloud_customer_name != null) { Engine.logEngine.info("Cloud customer: " + cloud_customer_name); } // Check environment and native dependencies if (!isStudioMode()) { StartupDiagnostics.run(); } // Initializing the engine Engine.theApp = new Engine(); CachedIntrospector.prefetchDatabaseObjectsAsync(); try { Engine.theApp.usageMonitor = new UsageMonitor(); Engine.theApp.usageMonitor.init(); Thread vulture = new Thread(Engine.theApp.usageMonitor); vulture.setName("UsageMonitor"); vulture.setDaemon(true); vulture.start(); } catch (Exception e) { Engine.logEngine.error("Unable to launch the usage monitor.", e); } Engine.theApp.eventManager = new EventManager(); Engine.theApp.eventManager.init(); Engine.theApp.databaseObjectsManager = new DatabaseObjectsManager(); Engine.theApp.databaseObjectsManager.init(); Engine.theApp.sqlConnectionManager = new JdbcConnectionManager(); Engine.theApp.sqlConnectionManager.init(); Engine.theApp.filePropertyManager = new FilePropertyManager(); Engine.theApp.filePropertyManager.init(); try { Engine.theApp.proxyManager = new ProxyManager(); Engine.theApp.proxyManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to launch the proxy manager.", e); } try { Engine.theApp.billingManager = new BillingManager(); Engine.theApp.billingManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to launch the billing manager.", e); } // Initialization of the trace player try { Engine.theApp.tracePlayerManager = new TracePlayerManager(); Engine.theApp.tracePlayerManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to run the trace player.", e); } try { Engine.theApp.minificationManager = new MinificationManager(); Engine.theApp.minificationManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to run the minification manager.", e); } try { Engine.theApp.couchDbManager = new CouchDbManager(); Engine.theApp.couchDbManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to run the couchDbProxy manager.", e); } try { Engine.theApp.pluginsManager = new PluginsManager(); Engine.theApp.pluginsManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to run the plugins manager.", e); } try { Engine.theApp.restApiManager = RestApiManager.getInstance(); Engine.theApp.restApiManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to run the rest api manager.", e); } Engine.logEngine.info("Current working directory is '" + System.getProperty("user.dir") + "'."); // Creating the Carioca Authentication objects Engine.logEngine.debug("Creating the Carioca Authentication objects"); String cariocaUserName = EnginePropertiesManager .getProperty(PropertyName.CARIOCA_DEFAULT_USER_NAME); String cariocaPassword = EnginePropertiesManager .getProperty(PropertyName.CARIOCA_DEFAULT_USER_PASSWORD); Engine.theApp.authentications = new HashMap<String, Authentication>(); // Initialization of the default TAS properties try { KeyManager.log = new LogWrapper(Engine.logEngine); Authentication auth = Engine.theApp.getAuthenticationObject("", null); auth.login(cariocaUserName, cariocaPassword); } catch (Exception e) { Engine.logEngine.error("The authentication to Carioca has failed (user name: \"" + cariocaUserName + "\", user password: \"" + cariocaPassword + "\").", e); } // TODO : retrieve SOA flag from KeyManager isSOA = true; // Creation of the session manager Engine.theApp.sessionManager = new SessionManager(); Engine.theApp.sessionManager.setLog(new LogWrapper(Engine.logEngine)); Engine.theApp.sessionManager.setProductCode(SessionManager.CONVERTIGO); String s = EnginePropertiesManager.getProperty(PropertyName.CONNECTORS_MONITORING); Engine.theApp.setMonitored(s.equalsIgnoreCase("true")); // Create Projects directory if needed File projectsDirFile = new File(Engine.PROJECTS_PATH); try { if (!projectsDirFile.exists()) projectsDirFile.mkdirs(); } catch (Exception e) { Engine.logEngine.error("An error occured while creating projects directory.", e); } // Starts projects migration process MigrationManager.performProjectsMigration(); // Security providers registration try { File dir = new File(Engine.CERTIFICATES_PATH); String[] files = dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith((".pkcs11")); } }); if (files != null && files.length > 0) { Engine.logEngine.info("Registering security providers..."); try { Class<?> sunPKCS11Class = Class.forName("sun.security.pkcs11.SunPKCS11"); String file; for (int i = 0; i < files.length; i++) { file = Engine.CERTIFICATES_PATH + "/" + files[i]; try { Constructor<?> constructor = sunPKCS11Class .getConstructor(new Class[] { String.class }); Provider provider = (Provider) constructor.newInstance(new Object[] { file }); Security.addProvider(provider); Engine.logEngine.info("Provider '" + provider.getName() + "' has been successfully registered."); } catch (Exception e) { Engine.logEngine.error("Unable to register security provider from file: " + file + " . Please check that the implementation library is in the Java lib path."); } } } catch (ClassNotFoundException e) { Engine.logEngine.error( "Unable to find sun.security.pkcs11.SunPKCS11 class! PKCS#11 authentication won't be available. You must use JVM 1.5 or higher in order to use PKCS#11 authentication."); } } Provider[] providers = Security.getProviders(); String sProviders = ""; for (int i = 0; i < providers.length; i++) { sProviders += providers[i].getName() + ", "; } Engine.logEngine.debug("Registered providers: " + sProviders); } catch (Exception e) { Engine.logEngine.error("Unable to register security providers.", e); } // Launch the cache manager try { String cacheManagerClassName = EnginePropertiesManager .getProperty(PropertyName.CACHE_MANAGER_CLASS); Engine.logEngine.debug("Cache manager class: " + cacheManagerClassName); Engine.theApp.cacheManager = (CacheManager) Class.forName(cacheManagerClassName).newInstance(); Engine.theApp.cacheManager.init(); Thread vulture = new Thread(Engine.theApp.cacheManager); Engine.theApp.cacheManager.executionThread = vulture; vulture.setName("CacheManager"); vulture.setDaemon(true); vulture.start(); } catch (Exception e) { Engine.logEngine.error("Unable to launch the cache manager.", e); } // Launch the thread manager try { Engine.theApp.threadManager = new ThreadManager(); Engine.theApp.threadManager.init(); Thread vulture = new Thread(Engine.theApp.threadManager); Engine.theApp.threadManager.executionThread = vulture; vulture.setName("ThreadManager"); vulture.setDaemon(true); vulture.start(); } catch (Exception e) { Engine.theApp.threadManager = null; Engine.logEngine.error("Unable to launch the thread manager.", e); } // Launch the context manager try { Engine.theApp.contextManager = new ContextManager(); Engine.theApp.contextManager.init(); Thread vulture = new Thread(Engine.theApp.contextManager); Engine.theApp.contextManager.executionThread = vulture; vulture.setName("ContextManager"); vulture.setDaemon(true); vulture.start(); } catch (Exception e) { Engine.theApp.contextManager = null; Engine.logEngine.error("Unable to launch the context manager.", e); } // Launch the security token manager Engine.theApp.securityTokenManager = new SecurityTokenManager(); Engine.theApp.securityTokenManager.init(); // Initialize the HttpClient try { Engine.logEngine.debug("HttpClient initializing..."); Engine.theApp.httpClient = HttpUtils.makeHttpClient3(true); Engine.theApp.httpClient4 = HttpUtils.makeHttpClient4(true); Engine.logEngine.debug("HttpClient initialized!"); } catch (Exception e) { Engine.logEngine.error("Unable to initialize the HttpClient.", e); } // Initialization of the schedule manager Engine.theApp.schedulerManager = new SchedulerManager(true); // Initialization of the RSA manager Engine.theApp.rsaManager = new RsaManager(); Engine.theApp.rsaManager.init(); // Initialization of the External Browser manager /** #3437 : Disabled ExternalBrowser feature because it's not terminated Engine.theApp.externalBrowserManager = new ExternalBrowserManager(); Engine.theApp.externalBrowserManager.init(); */ // Initialization of the Schema manager Engine.theApp.schemaManager = new SchemaManager(); Engine.theApp.schemaManager.init(); // XUL initialization String xulrunner_url = System.getProperty("org.eclipse.swt.browser.XULRunnerPath"); if (xulrunner_url == null || xulrunner_url.equals("")) { xulrunner_url = EnginePropertiesManager.getProperty(PropertyName.XULRUNNER_URL); } File f = new File(xulrunner_url); if (f.exists()) { xulrunner_url = f.getAbsolutePath(); Engine.logEngine .debug("initMozillaSWT: org.eclipse.swt.browser.XULRunnerPath=" + xulrunner_url); System.setProperty("org.eclipse.swt.browser.XULRunnerPath", xulrunner_url); } else { Engine.logEngine.error("Error in initMozillaSWT: " + xulrunner_url + " doesn't exist, fix it with xulrunner.url"); } if (Engine.isEngineMode() && Engine.isLinux() && "true".equals(EnginePropertiesManager.getProperty(PropertyName.LINUX_LAUNCH_XVNC))) { Engine.logEngine .debug("initMozillaSWT: org.eclipse.swt.browser.XULRunnerPath=" + xulrunner_url); final String display = System.getenv("DISPLAY"); if (display != null) { try { String port = System.getProperty("xvnc.port"); if (port == null) { port = "" + (Integer.parseInt(display.replaceAll(".*:(\\d*)", "$1")) + 5900); System.setProperty("xvnc.port", port); } Engine.logEngine.debug("Xvnc should listen on " + port + " port"); } catch (Exception e) { } try { File vncDir = new File(Engine.WEBAPP_PATH + "/WEB-INF/xvnc"); File Xvnc = new File(vncDir, "/Xvnc"); File fonts = new File(vncDir, "/fonts"); File wm = new File(vncDir, "/matchbox-window-manager"); if (vncDir.exists() && Xvnc.exists() && fonts.exists() && wm.exists()) { for (File file : GenericUtils.<File>asList(Xvnc, wm)) { new ProcessBuilder("/bin/chmod", "u+x", file.getAbsolutePath()).start() .waitFor(); } String depth = EnginePropertiesManager.getProperty(PropertyName.LINUX_XVNC_DEPTH); String geometry = EnginePropertiesManager .getProperty(PropertyName.LINUX_XVNC_GEOMETRY); Engine.logEngine .debug("Xvnc will use depth " + depth + " and geometry " + geometry); Process pr_xvnc = new ProcessBuilder(Xvnc.getAbsolutePath(), display, "-fp", fonts.getAbsolutePath(), "-depth", depth, "-geometry", geometry).start(); Thread.sleep(500); try { int exit = pr_xvnc.exitValue(); InputStream err = pr_xvnc.getErrorStream(); byte[] buf = new byte[err.available()]; err.read(buf); Engine.logEngine.debug("Xvnc failed to run with exit code " + exit + " and this error : <<" + new String(buf, "UTF-8") + ">>"); } catch (Exception e) { new ProcessBuilder(wm.getAbsolutePath()).start(); Engine.logEngine.debug("Xvnc successfully started !"); } } else { Engine.logEngine.info( vncDir.getAbsolutePath() + " not found or incomplet, cannot start Xvnc"); } } catch (Exception e) { Engine.logEngine.info("failed to launch Xvnc (maybe already launched", e); } } else Engine.logEngine .warn("Trying to start Xvnc on Linux without DISPLAY environment variable !"); } // SAP provider registration try { SapJcoDestinationDataProvider.init(); Engine.logEngine.debug("SAP destination provider successfully registered"); } catch (Throwable e) { Engine.logEngine.error("Error while registering SAP destination provider", e); } isStarted = true; Engine.logEngine.info("Convertigo engine started"); } catch (Throwable e) { isStartFailed = true; Engine.logEngine.error("Unable to successfully start the engine.", e); } } else { Engine.logEngine.info("Convertigo engine already started"); } }
From source file:org.jasig.portal.events.aggr.PortalRawEventsAggregatorImpl.java
@Override @AggrEventsTransactional//from ww w . j a v a2s . co m public EventProcessingResult doCloseAggregations() { if (!this.clusterLockService.isLockOwner(AGGREGATION_LOCK_NAME)) { throw new IllegalStateException("The cluster lock " + AGGREGATION_LOCK_NAME + " must be owned by the current thread and server"); } final IEventAggregatorStatus cleanUnclosedStatus = eventAggregationManagementDao .getEventAggregatorStatus(ProcessingType.CLEAN_UNCLOSED, true); //Update status with current server name final String serverName = this.portalInfoProvider.getUniqueServerName(); cleanUnclosedStatus.setServerName(serverName); cleanUnclosedStatus.setLastStart(new DateTime()); //Determine date of most recently aggregated data final IEventAggregatorStatus eventAggregatorStatus = eventAggregationManagementDao .getEventAggregatorStatus(ProcessingType.AGGREGATION, false); if (eventAggregatorStatus == null || eventAggregatorStatus.getLastEventDate() == null) { //Nothing has been aggregated, skip unclosed cleanup cleanUnclosedStatus.setLastEnd(new DateTime()); eventAggregationManagementDao.updateEventAggregatorStatus(cleanUnclosedStatus); return new EventProcessingResult(0, null, null, true); } final DateTime lastAggregatedDate = eventAggregatorStatus.getLastEventDate(); //If lastCleanUnclosedDate is null use the oldest date dimension as there can be //no aggregations that exist before it final DateTime lastCleanUnclosedDate; if (cleanUnclosedStatus.getLastEventDate() == null) { final DateDimension oldestDateDimension = this.dateDimensionDao.getOldestDateDimension(); lastCleanUnclosedDate = oldestDateDimension.getDate().toDateTime(); } else { lastCleanUnclosedDate = cleanUnclosedStatus.getLastEventDate(); } if (!(lastCleanUnclosedDate.isBefore(lastAggregatedDate))) { logger.debug("No events aggregated since last unclosed aggregation cleaning, skipping clean: {}", lastAggregatedDate); return new EventProcessingResult(0, lastCleanUnclosedDate, lastAggregatedDate, true); } //Switch to flush on commit to avoid flushes during queries final EntityManager entityManager = this.getEntityManager(); entityManager.flush(); entityManager.setFlushMode(FlushModeType.COMMIT); //Track the number of closed aggregations and the last date of a cleaned interval int closedAggregations = 0; int cleanedIntervals = 0; DateTime cleanUnclosedEnd; final Thread currentThread = Thread.currentThread(); final String currentName = currentThread.getName(); try { currentThread.setName(currentName + "-" + lastCleanUnclosedDate + "-" + lastAggregatedDate); //Local caches used to reduce db io final IntervalsForAggregatorHelper intervalsForAggregatorHelper = new IntervalsForAggregatorHelper(); final Map<AggregationInterval, AggregationIntervalInfo> previousIntervals = new HashMap<AggregationInterval, AggregationIntervalInfo>(); //A DateTime within the next interval to close aggregations in DateTime nextIntervalDate = lastCleanUnclosedDate; do { //Reset our goal of catching up to the last aggregated event on every iteration cleanUnclosedEnd = lastAggregatedDate; //For each interval the aggregator supports, cleanup the unclosed aggregations for (final AggregationInterval interval : intervalsForAggregatorHelper.getHandledIntervals()) { final AggregationIntervalInfo previousInterval = previousIntervals.get(interval); if (previousInterval != null && nextIntervalDate.isBefore(previousInterval.getEnd())) { logger.debug( "{} interval before {} has already been cleaned during this execution, ignoring", interval, previousInterval.getEnd()); continue; } //The END date of the last clean session will find us the next interval to clean final AggregationIntervalInfo nextIntervalToClean = intervalHelper.getIntervalInfo(interval, nextIntervalDate); previousIntervals.put(interval, nextIntervalToClean); if (nextIntervalToClean == null) { continue; } final DateTime start = nextIntervalToClean.getStart(); final DateTime end = nextIntervalToClean.getEnd(); if (!end.isBefore(lastAggregatedDate)) { logger.debug("{} interval between {} and {} is still active, ignoring", new Object[] { interval, start, end }); continue; } //Track the oldest interval end, this ensures that nothing is missed if (end.isBefore(cleanUnclosedEnd)) { cleanUnclosedEnd = end; } logger.debug("Cleaning unclosed {} aggregations between {} and {}", new Object[] { interval, start, end }); for (final IPortalEventAggregator<PortalEvent> portalEventAggregator : portalEventAggregators) { checkShutdown(); final Class<? extends IPortalEventAggregator<?>> aggregatorType = getClass( portalEventAggregator); //Get aggregator specific interval info config final AggregatedIntervalConfig aggregatorIntervalConfig = intervalsForAggregatorHelper .getAggregatorIntervalConfig(aggregatorType); //If the aggregator is being used for the specified interval call cleanUnclosedAggregations if (aggregatorIntervalConfig.isIncluded(interval)) { closedAggregations += portalEventAggregator.cleanUnclosedAggregations(start, end, interval); } } cleanedIntervals++; } //Set the next interval to the end date from the last aggregation run nextIntervalDate = cleanUnclosedEnd; logger.debug("Closed {} aggregations across {} interval before {} with goal of {}", new Object[] { closedAggregations, cleanedIntervals, cleanUnclosedEnd, lastAggregatedDate }); //Loop until either the batchSize of cleaned aggregations has been reached or no aggregation work is done } while (closedAggregations <= cleanUnclosedAggregationsBatchSize && cleanedIntervals <= cleanUnclosedIntervalsBatchSize && cleanUnclosedEnd.isBefore(lastAggregatedDate)); } finally { currentThread.setName(currentName); } //Update the status object and store it cleanUnclosedStatus.setLastEventDate(cleanUnclosedEnd); cleanUnclosedStatus.setLastEnd(new DateTime()); eventAggregationManagementDao.updateEventAggregatorStatus(cleanUnclosedStatus); return new EventProcessingResult(closedAggregations, lastCleanUnclosedDate, lastAggregatedDate, !cleanUnclosedEnd.isBefore(lastAggregatedDate)); }
From source file:org.apache.xml.security.stax.impl.processor.input.AbstractDecryptInputProcessor.java
private XMLSecEvent processEvent(InputProcessorChain inputProcessorChain, boolean isSecurityHeaderEvent) throws XMLStreamException, XMLSecurityException { if (!tmpXmlEventList.isEmpty()) { return tmpXmlEventList.pollLast(); }/*www. j a v a 2 s.c o m*/ XMLSecEvent xmlSecEvent = isSecurityHeaderEvent ? inputProcessorChain.processHeaderEvent() : inputProcessorChain.processEvent(); boolean encryptedHeader = false; if (xmlSecEvent.getEventType() == XMLStreamConstants.START_ELEMENT) { XMLSecStartElement xmlSecStartElement = xmlSecEvent.asStartElement(); //buffer the events until the EncryptedData Element appears and discard it if we found the reference inside it //otherwise replay it if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_wsse11_EncryptedHeader)) { xmlSecEvent = readAndBufferEncryptedHeader(inputProcessorChain, isSecurityHeaderEvent, xmlSecEvent); xmlSecStartElement = xmlSecEvent.asStartElement(); encryptedHeader = true; } //check if the current start-element has the name EncryptedData and an Id attribute if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_xenc_EncryptedData)) { ReferenceType referenceType = null; if (references != null) { referenceType = matchesReferenceId(xmlSecStartElement); if (referenceType == null) { //if the events were not for us (no matching reference-id the we have to replay the EncryptedHeader elements) if (!tmpXmlEventList.isEmpty()) { return tmpXmlEventList.pollLast(); } return xmlSecEvent; } //duplicate id's are forbidden if (processedReferences.contains(referenceType)) { throw new XMLSecurityException("signature.Verification.MultipleIDs"); } processedReferences.add(referenceType); } tmpXmlEventList.clear(); //the following logic reads the encryptedData structure and doesn't pass them further //through the chain InputProcessorChain subInputProcessorChain = inputProcessorChain.createSubChain(this); EncryptedDataType encryptedDataType = parseEncryptedDataStructure(isSecurityHeaderEvent, xmlSecEvent, subInputProcessorChain); if (encryptedDataType.getId() == null) { encryptedDataType.setId(IDGenerator.generateID(null)); } InboundSecurityToken inboundSecurityToken = getSecurityToken(inputProcessorChain, xmlSecStartElement, encryptedDataType); handleSecurityToken(inboundSecurityToken, inputProcessorChain.getSecurityContext(), encryptedDataType); final String algorithmURI = encryptedDataType.getEncryptionMethod().getAlgorithm(); final int ivLength = JCEAlgorithmMapper.getIVLengthFromURI(algorithmURI) / 8; Cipher symCipher = getCipher(algorithmURI); if (encryptedDataType.getCipherData().getCipherReference() != null) { handleCipherReference(inputProcessorChain, encryptedDataType, symCipher, inboundSecurityToken); subInputProcessorChain.reset(); return isSecurityHeaderEvent ? subInputProcessorChain.processHeaderEvent() : subInputProcessorChain.processEvent(); } //create a new Thread for streaming decryption DecryptionThread decryptionThread = new DecryptionThread(subInputProcessorChain, isSecurityHeaderEvent); Key decryptionKey = inboundSecurityToken.getSecretKey(algorithmURI, XMLSecurityConstants.Enc, encryptedDataType.getId()); decryptionKey = XMLSecurityUtils.prepareSecretKey(algorithmURI, decryptionKey.getEncoded()); decryptionThread.setSecretKey(decryptionKey); decryptionThread.setSymmetricCipher(symCipher); decryptionThread.setIvLength(ivLength); XMLSecStartElement parentXMLSecStartElement = xmlSecStartElement.getParentXMLSecStartElement(); if (encryptedHeader) { parentXMLSecStartElement = parentXMLSecStartElement.getParentXMLSecStartElement(); } AbstractDecryptedEventReaderInputProcessor decryptedEventReaderInputProcessor = newDecryptedEventReaderInputProcessor( encryptedHeader, parentXMLSecStartElement, encryptedDataType, inboundSecurityToken, inputProcessorChain.getSecurityContext()); //add the new created EventReader processor to the chain. inputProcessorChain.addProcessor(decryptedEventReaderInputProcessor); inputProcessorChain.getDocumentContext().setIsInEncryptedContent( inputProcessorChain.getProcessors().indexOf(decryptedEventReaderInputProcessor), decryptedEventReaderInputProcessor); //fire here only ContentEncryptedElementEvents //the other ones will be fired later, because we don't know the encrypted element name yet //important: this must occur after setIsInEncryptedContent! if (SecurePart.Modifier.Content.getModifier().equals(encryptedDataType.getType())) { handleEncryptedContent(inputProcessorChain, xmlSecStartElement.getParentXMLSecStartElement(), inboundSecurityToken, encryptedDataType); } Thread thread = new Thread(decryptionThread); thread.setPriority(Thread.NORM_PRIORITY + 1); thread.setName("decryption thread"); //when an exception in the decryption thread occurs, we want to forward them: thread.setUncaughtExceptionHandler(decryptedEventReaderInputProcessor); decryptedEventReaderInputProcessor.setDecryptionThread(thread); //we have to start the thread before we call decryptionThread.getPipedInputStream(). //Otherwise we will end in a deadlock, because the StAX reader expects already data. //@See some lines below: log.debug("Starting decryption thread"); thread.start(); InputStream prologInputStream; InputStream epilogInputStream; try { prologInputStream = writeWrapperStartElement(xmlSecStartElement); epilogInputStream = writeWrapperEndElement(); } catch (UnsupportedEncodingException e) { throw new XMLSecurityException(e); } catch (IOException e) { throw new XMLSecurityException(e); } InputStream decryptInputStream = decryptionThread.getPipedInputStream(); decryptInputStream = applyTransforms(referenceType, decryptInputStream); //spec says (4.2): "The cleartext octet sequence obtained in step 3 is //interpreted as UTF-8 encoded character data." XMLStreamReader xmlStreamReader = inputProcessorChain.getSecurityContext() .<XMLInputFactory>get(XMLSecurityConstants.XMLINPUTFACTORY).createXMLStreamReader( new MultiInputStream(prologInputStream, decryptInputStream, epilogInputStream), "UTF-8"); //forward to wrapper element forwardToWrapperElement(xmlStreamReader); decryptedEventReaderInputProcessor.setXmlStreamReader(xmlStreamReader); if (isSecurityHeaderEvent) { return decryptedEventReaderInputProcessor.processNextHeaderEvent(inputProcessorChain); } else { return decryptedEventReaderInputProcessor.processNextEvent(inputProcessorChain); } } } return xmlSecEvent; }
From source file:org.apereo.portal.events.aggr.PortalRawEventsAggregatorImpl.java
@Override @AggrEventsTransactional/* ww w .j a va2 s . co m*/ public EventProcessingResult doCloseAggregations() { if (!this.clusterLockService.isLockOwner(AGGREGATION_LOCK_NAME)) { throw new IllegalStateException("The cluster lock " + AGGREGATION_LOCK_NAME + " must be owned by the current thread and server"); } final IEventAggregatorStatus cleanUnclosedStatus = eventAggregationManagementDao .getEventAggregatorStatus(IEventAggregatorStatus.ProcessingType.CLEAN_UNCLOSED, true); //Update status with current server name final String serverName = this.portalInfoProvider.getUniqueServerName(); cleanUnclosedStatus.setServerName(serverName); cleanUnclosedStatus.setLastStart(new DateTime()); //Determine date of most recently aggregated data final IEventAggregatorStatus eventAggregatorStatus = eventAggregationManagementDao .getEventAggregatorStatus(IEventAggregatorStatus.ProcessingType.AGGREGATION, false); if (eventAggregatorStatus == null || eventAggregatorStatus.getLastEventDate() == null) { //Nothing has been aggregated, skip unclosed cleanup cleanUnclosedStatus.setLastEnd(new DateTime()); eventAggregationManagementDao.updateEventAggregatorStatus(cleanUnclosedStatus); return new EventProcessingResult(0, null, null, true); } final DateTime lastAggregatedDate = eventAggregatorStatus.getLastEventDate(); //If lastCleanUnclosedDate is null use the oldest date dimension as there can be //no aggregations that exist before it final DateTime lastCleanUnclosedDate; if (cleanUnclosedStatus.getLastEventDate() == null) { final DateDimension oldestDateDimension = this.dateDimensionDao.getOldestDateDimension(); lastCleanUnclosedDate = oldestDateDimension.getDate().toDateTime(); } else { lastCleanUnclosedDate = cleanUnclosedStatus.getLastEventDate(); } if (!(lastCleanUnclosedDate.isBefore(lastAggregatedDate))) { logger.debug("No events aggregated since last unclosed aggregation cleaning, skipping clean: {}", lastAggregatedDate); return new EventProcessingResult(0, lastCleanUnclosedDate, lastAggregatedDate, true); } //Switch to flush on commit to avoid flushes during queries final EntityManager entityManager = this.getEntityManager(); entityManager.flush(); entityManager.setFlushMode(FlushModeType.COMMIT); //Track the number of closed aggregations and the last date of a cleaned interval int closedAggregations = 0; int cleanedIntervals = 0; DateTime cleanUnclosedEnd; final Thread currentThread = Thread.currentThread(); final String currentName = currentThread.getName(); try { currentThread.setName(currentName + "-" + lastCleanUnclosedDate + "-" + lastAggregatedDate); //Local caches used to reduce db io final IntervalsForAggregatorHelper intervalsForAggregatorHelper = new IntervalsForAggregatorHelper(); final Map<AggregationInterval, AggregationIntervalInfo> previousIntervals = new HashMap<AggregationInterval, AggregationIntervalInfo>(); //A DateTime within the next interval to close aggregations in DateTime nextIntervalDate = lastCleanUnclosedDate; do { //Reset our goal of catching up to the last aggregated event on every iteration cleanUnclosedEnd = lastAggregatedDate; //For each interval the aggregator supports, cleanup the unclosed aggregations for (final AggregationInterval interval : intervalsForAggregatorHelper.getHandledIntervals()) { final AggregationIntervalInfo previousInterval = previousIntervals.get(interval); if (previousInterval != null && nextIntervalDate.isBefore(previousInterval.getEnd())) { logger.debug( "{} interval before {} has already been cleaned during this execution, ignoring", interval, previousInterval.getEnd()); continue; } //The END date of the last clean session will find us the next interval to clean final AggregationIntervalInfo nextIntervalToClean = intervalHelper.getIntervalInfo(interval, nextIntervalDate); previousIntervals.put(interval, nextIntervalToClean); if (nextIntervalToClean == null) { continue; } final DateTime start = nextIntervalToClean.getStart(); final DateTime end = nextIntervalToClean.getEnd(); if (!end.isBefore(lastAggregatedDate)) { logger.debug("{} interval between {} and {} is still active, ignoring", new Object[] { interval, start, end }); continue; } //Track the oldest interval end, this ensures that nothing is missed if (end.isBefore(cleanUnclosedEnd)) { cleanUnclosedEnd = end; } logger.debug("Cleaning unclosed {} aggregations between {} and {}", new Object[] { interval, start, end }); for (final IntervalAwarePortalEventAggregator<PortalEvent> portalEventAggregator : intervalAwarePortalEventAggregators) { checkShutdown(); final Class<? extends IPortalEventAggregator<?>> aggregatorType = getClass( portalEventAggregator); //Get aggregator specific interval info config final AggregatedIntervalConfig aggregatorIntervalConfig = intervalsForAggregatorHelper .getAggregatorIntervalConfig(aggregatorType); //If the aggregator is being used for the specified interval call cleanUnclosedAggregations if (aggregatorIntervalConfig.isIncluded(interval)) { closedAggregations += portalEventAggregator.cleanUnclosedAggregations(start, end, interval); } } cleanedIntervals++; } //Set the next interval to the end date from the last aggregation run nextIntervalDate = cleanUnclosedEnd; logger.debug("Closed {} aggregations across {} interval before {} with goal of {}", new Object[] { closedAggregations, cleanedIntervals, cleanUnclosedEnd, lastAggregatedDate }); //Loop until either the batchSize of cleaned aggregations has been reached or no aggregation work is done } while (closedAggregations <= cleanUnclosedAggregationsBatchSize && cleanedIntervals <= cleanUnclosedIntervalsBatchSize && cleanUnclosedEnd.isBefore(lastAggregatedDate)); } finally { currentThread.setName(currentName); } //Update the status object and store it cleanUnclosedStatus.setLastEventDate(cleanUnclosedEnd); cleanUnclosedStatus.setLastEnd(new DateTime()); eventAggregationManagementDao.updateEventAggregatorStatus(cleanUnclosedStatus); return new EventProcessingResult(closedAggregations, lastCleanUnclosedDate, lastAggregatedDate, !cleanUnclosedEnd.isBefore(lastAggregatedDate)); }
From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.java
@SuppressWarnings("unchecked") private boolean notifyStoreOperationFailedInternal(Exception failureCause) { boolean isFenced = false; LOG.error("State store operation failed ", failureCause); if (HAUtil.isHAEnabled(getConfig())) { LOG.warn("State-store fenced ! Transitioning RM to standby"); isFenced = true;//from w w w .j av a 2 s.c o m Thread standByTransitionThread = new Thread(new StandByTransitionThread()); standByTransitionThread.setName("StandByTransitionThread Handler"); standByTransitionThread.start(); } else if (YarnConfiguration.shouldRMFailFast(getConfig())) { LOG.fatal("Fail RM now due to state-store error!"); rmDispatcher.getEventHandler() .handle(new RMFatalEvent(RMFatalEventType.STATE_STORE_OP_FAILED, failureCause)); } else { LOG.warn("Skip the state-store error."); } return isFenced; }