List of usage examples for java.lang InterruptedException toString
public String toString()
From source file:org.apache.accumulo.server.tabletserver.Tablet.java
void initiateClose(boolean saveState, boolean queueMinC, boolean disableWrites) { if (!saveState && queueMinC) { throw new IllegalArgumentException( "Not saving state on close and requesting minor compactions queue does not make sense"); }/*from w ww . ja v a 2 s. c o m*/ log.debug("initiateClose(saveState=" + saveState + " queueMinC=" + queueMinC + " disableWrites=" + disableWrites + ") " + getExtent()); MinorCompactionTask mct = null; synchronized (this) { if (closed || closing || closeComplete) { String msg = "Tablet " + getExtent() + " already"; if (closed) msg += " closed"; if (closing) msg += " closing"; if (closeComplete) msg += " closeComplete"; throw new IllegalStateException(msg); } // enter the closing state, no splits, minor, or major compactions can start // should cause running major compactions to stop closing = true; this.notifyAll(); // determines if inserts and queries can still continue while minor compacting closed = disableWrites; // wait for major compactions to finish, setting closing to // true should cause any running major compactions to abort while (majorCompactionInProgress) { try { this.wait(50); } catch (InterruptedException e) { log.error(e.toString()); } } while (updatingFlushID) { try { this.wait(50); } catch (InterruptedException e) { log.error(e.toString()); } } if (!saveState || tabletMemory.getMemTable().getNumEntries() == 0) { return; } tabletMemory.waitForMinC(); try { mct = prepareForMinC(getFlushID(), MinorCompactionReason.CLOSE); } catch (NoNodeException e) { throw new RuntimeException(e); } if (queueMinC) { tabletResources.executeMinorCompaction(mct); return; } } // do minor compaction outside of synch block so that tablet can be read and written to while // compaction runs mct.run(); }
From source file:org.apache.accumulo.server.tabletserver.Tablet.java
synchronized void completeClose(boolean saveState, boolean completeClose) throws IOException { if (!closing || closeComplete || closeCompleting) { throw new IllegalStateException("closing = " + closing + " closed = " + closed + " closeComplete = " + closeComplete + " closeCompleting = " + closeCompleting); }//www. j a v a 2 s .c om log.debug("completeClose(saveState=" + saveState + " completeClose=" + completeClose + ") " + getExtent()); // ensure this method is only called once, also guards against multiple // threads entering the method at the same time closeCompleting = true; closed = true; // modify dataSourceDeletions so scans will try to switch data sources and fail because the tablet is closed dataSourceDeletions.incrementAndGet(); for (ScanDataSource activeScan : activeScans) { activeScan.interrupt(); } // wait for reads and writes to complete while (writesInProgress > 0 || activeScans.size() > 0) { try { this.wait(50); } catch (InterruptedException e) { log.error(e.toString()); } } tabletMemory.waitForMinC(); if (saveState && tabletMemory.getMemTable().getNumEntries() > 0) { try { prepareForMinC(getFlushID(), MinorCompactionReason.CLOSE).run(); } catch (NoNodeException e) { throw new RuntimeException(e); } } if (saveState) { // at this point all tablet data is flushed, so do a consistency check RuntimeException err = null; for (int i = 0; i < 5; i++) { try { closeConsistencyCheck(); err = null; } catch (RuntimeException t) { err = t; log.error("Consistency check fails, retrying " + t); UtilWaitThread.sleep(500); } } if (err != null) { ProblemReports.getInstance().report(new ProblemReport(extent.getTableId().toString(), ProblemType.TABLET_LOAD, this.extent.toString(), err)); log.error( "Tablet closed consistency check has failed for " + this.extent + " giving up and closing"); } } try { tabletMemory.getMemTable().delete(0); } catch (Throwable t) { log.error("Failed to delete mem table : " + t.getMessage(), t); } tabletMemory = null; // close map files tabletResources.close(); log.log(TLevel.TABLET_HIST, extent + " closed"); acuTableConf.removeObserver(configObserver); closeComplete = completeClose; }
From source file:org.apache.accumulo.tserver.Tablet.java
synchronized void completeClose(boolean saveState, boolean completeClose) throws IOException { if (!closing || closeComplete || closeCompleting) { throw new IllegalStateException("closing = " + closing + " closed = " + closed + " closeComplete = " + closeComplete + " closeCompleting = " + closeCompleting); }/*from w w w .j a va2s.c o m*/ log.debug("completeClose(saveState=" + saveState + " completeClose=" + completeClose + ") " + getExtent()); // ensure this method is only called once, also guards against multiple // threads entering the method at the same time closeCompleting = true; closed = true; // modify dataSourceDeletions so scans will try to switch data sources and fail because the tablet is closed dataSourceDeletions.incrementAndGet(); for (ScanDataSource activeScan : activeScans) { activeScan.interrupt(); } // wait for reads and writes to complete while (writesInProgress > 0 || activeScans.size() > 0) { try { this.wait(50); } catch (InterruptedException e) { log.error(e.toString()); } } tabletMemory.waitForMinC(); if (saveState && tabletMemory.getMemTable().getNumEntries() > 0) { try { prepareForMinC(getFlushID(), MinorCompactionReason.CLOSE).run(); } catch (NoNodeException e) { throw new RuntimeException(e); } } if (saveState) { // at this point all tablet data is flushed, so do a consistency check RuntimeException err = null; for (int i = 0; i < 5; i++) { try { closeConsistencyCheck(); err = null; } catch (RuntimeException t) { err = t; log.error("Consistency check fails, retrying " + t); UtilWaitThread.sleep(500); } } if (err != null) { ProblemReports.getInstance().report(new ProblemReport(extent.getTableId().toString(), ProblemType.TABLET_LOAD, this.extent.toString(), err)); log.error( "Tablet closed consistency check has failed for " + this.extent + " giving up and closing"); } } try { tabletMemory.getMemTable().delete(0); } catch (Throwable t) { log.error("Failed to delete mem table : " + t.getMessage(), t); } tabletMemory = null; // close map files tabletResources.close(); log.log(TLevel.TABLET_HIST, extent + " closed"); acuTableConf.getNamespaceConfiguration().removeObserver(configObserver); acuTableConf.removeObserver(configObserver); closeComplete = completeClose; }
From source file:com.marklogic.client.functionaltest.TestSparqlQueryManager.java
@Test public void testExecuteUpdateCreateSilent() throws IOException, SAXException, ParserConfigurationException { System.out.println("In SPARQL Query Manager Test testExecuteUpdateCreateSilent method"); // Form a query SPARQLQueryManager sparqlQmgr = writeclient.newSPARQLQueryManager(); StringBuffer sparqlCreateGraphQuery = new StringBuffer().append("CREATE GRAPH <DOMICLE>;"); sparqlCreateGraphQuery.append(newline); SPARQLQueryDefinition qdef = sparqlQmgr.newQueryDefinition(sparqlCreateGraphQuery.toString()); // Create an empty graph. sparqlQmgr.executeUpdate(qdef);//from w ww. java 2s . co m qdef = null; // Insert triple into graph using INSERT DATA StringBuffer sparqlInsertData = new StringBuffer().append("PREFIX : <http://example.org/>"); sparqlInsertData.append(newline); sparqlInsertData.append("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "); sparqlInsertData.append(newline); sparqlInsertData.append("PREFIX foaf: <http://xmlns.com/foaf/0.1/>"); sparqlInsertData.append("INSERT DATA { GRAPH <DOMICLE> { "); sparqlInsertData.append(newline); sparqlInsertData.append(":alice rdf:type foaf:Person ."); sparqlInsertData.append(newline); sparqlInsertData.append(":alice foaf:name \"Alice\" . "); sparqlInsertData.append(newline); sparqlInsertData.append(":bob rdf:type foaf:Person . "); sparqlInsertData.append(newline); sparqlInsertData.append("} } "); qdef = sparqlQmgr.newQueryDefinition(sparqlInsertData.toString()); // Insert Data into the empty graph. sparqlQmgr.executeUpdate(qdef); // Wait for index try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } qdef = null; //Check for EXIST. StringBuffer sparqlExists = new StringBuffer(); sparqlExists.append("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"); sparqlExists.append(newline); sparqlExists.append("PREFIX foaf: <http://xmlns.com/foaf/0.1/>"); sparqlExists.append(newline); sparqlExists.append("SELECT ?person "); sparqlExists.append(newline); sparqlExists.append("FROM <DOMICLE>"); sparqlExists.append(newline); sparqlExists.append("WHERE"); sparqlExists.append(newline); sparqlExists.append("{"); sparqlExists.append("?person rdf:type foaf:Person ."); sparqlExists.append(newline); sparqlExists.append("FILTER EXISTS { ?person foaf:name ?name }"); sparqlExists.append(newline); sparqlExists.append("}"); qdef = sparqlQmgr.newQueryDefinition(sparqlExists.toString()); // Perform Exists query. JsonNode jsonResults = sparqlQmgr.executeSelect(qdef, new JacksonHandle()).get(); JsonNode jsonBindingsNodes = jsonResults.path("results").path("bindings"); // Should have 1 node returned. assertEquals("One result not returned from testExecuteUpdateCreateSilent method ", 1, jsonBindingsNodes.size()); Iterator<JsonNode> nameNodesItr = jsonBindingsNodes.elements(); JsonNode jsonPersonNode = null; if (nameNodesItr.hasNext()) { jsonPersonNode = nameNodesItr.next(); assertEquals("Exist query solution returned is incorrect", "http://example.org/alice", jsonPersonNode.path("person").path("value").asText()); } qdef = null; // Test to see if FailedRequestException is thrown. qdef = sparqlQmgr.newQueryDefinition(sparqlCreateGraphQuery.toString()); String expectedException = "FailedRequestException"; String exception = ""; try { // Create same graph. sparqlQmgr.executeUpdate(qdef); } catch (Exception e) { exception = e.toString(); } System.out.println(exception); assertTrue("Test testExecuteUpdateCreateSilent exception is not thrown", exception.contains(expectedException)); qdef = null; // Create the same graph again silently. Should not expect exception. StringBuffer sparqlCreateGraphSilentQuery = new StringBuffer().append("CREATE SILENT GRAPH <DOMICLE>;"); sparqlCreateGraphQuery.append(newline); qdef = sparqlQmgr.newQueryDefinition(sparqlCreateGraphSilentQuery.toString()); String expectedSilentException = ""; String exceptionSilent = ""; try { // Create same graph. sparqlQmgr.executeUpdate(qdef); } catch (Exception e) { exceptionSilent = e.toString(); } assertTrue("Test testExecuteUpdateCreateSilent exception is not thrown", exceptionSilent.equals(expectedSilentException)); qdef = null; // Verify the EXISTS again. Should have one solution returned. qdef = sparqlQmgr.newQueryDefinition(sparqlExists.toString()); // Perform Exists query again JsonNode jsonResultsSil = sparqlQmgr.executeSelect(qdef, new JacksonHandle()).get(); JsonNode jsonBindingsNodesSilent = jsonResultsSil.path("results").path("bindings"); // Should have 1 node returned. assertEquals("One result not returned from testExecuteUpdateCreateSilent method ", 1, jsonBindingsNodesSilent.size()); Iterator<JsonNode> nameNodesSilentItr = jsonBindingsNodesSilent.elements(); JsonNode jsonPersonNodeSilent = null; if (nameNodesSilentItr.hasNext()) { jsonPersonNodeSilent = nameNodesSilentItr.next(); assertEquals("Exist query solution returned is incorrect", "http://example.org/alice", jsonPersonNodeSilent.path("person").path("value").asText()); } }
From source file:ru.iris.events.EventsService.java
public EventsService() { Status status = new Status("Events"); if (status.checkExist()) { status.running();//w ww. j av a 2 s . c o m } else { status.addIntoDB("Events", "Service that listen for events and exec scripts as needed"); } try { events = Ebean.find(Event.class).findList(); // take pause to save/remove new entity try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } // load all scripts, compile and put into map compiledScriptMap = loadAndCompile(events); // Pass jsonmessaging instance to js engine Bindings bindings = new SimpleBindings(); bindings.put("jsonMessaging", jsonMessaging); bindings.put("LOGGER", scriptLogger); // subscribe to events from db for (Event event : events) { jsonMessaging.subscribe(event.getSubject()); LOGGER.debug("Subscribe to subject: " + event.getSubject()); } // command launch jsonMessaging.subscribe("event.command"); // scripts jsonMessaging.subscribe("event.script.get"); jsonMessaging.subscribe("event.script.save"); jsonMessaging.subscribe("event.script.delete"); jsonMessaging.subscribe("event.script.list"); jsonMessaging.subscribe("event.reload"); jsonMessaging.setNotification(new JsonNotification() { @Override public void onNotification(JsonEnvelope envelope) { LOGGER.debug("Got envelope with subject: " + envelope.getSubject()); try { // Get script content if (envelope.getObject() instanceof EventGetScriptAdvertisement) { LOGGER.debug("Return JS script to: " + envelope.getReceiverInstance()); EventGetScriptAdvertisement advertisement = envelope.getObject(); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/" + advertisement.getName()); else jsFile = new File("./scripts/" + advertisement.getName()); jsonMessaging.response(envelope, new EventResponseGetScriptAdvertisement(FileUtils.readFileToString(jsFile))); } // Save new/existing script else if (envelope.getObject() instanceof EventResponseSaveScriptAdvertisement) { EventResponseSaveScriptAdvertisement advertisement = envelope.getObject(); LOGGER.debug("Request to save changes: " + advertisement.getName()); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/" + advertisement.getName()); else jsFile = new File("./scripts/" + advertisement.getName()); FileUtils.writeStringToFile(jsFile, advertisement.getBody()); LOGGER.info("Restart event service (reason: script change)"); reloadService(); } // Remove script else if (envelope.getObject() instanceof EventRemoveScriptAdvertisement) { EventRemoveScriptAdvertisement advertisement = envelope.getObject(); LOGGER.debug("Request to remove script: " + advertisement.getName()); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/" + advertisement.getName()); else jsFile = new File("./scripts/" + advertisement.getName()); FileUtils.forceDelete(jsFile); LOGGER.info("Restart event service (reason: script removed)"); reloadService(); } // List available scripts else if (envelope.getObject() instanceof EventListScriptsAdvertisement) { EventListScriptsAdvertisement advertisement = envelope.getObject(); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/"); else jsFile = new File("./scripts/"); EventResponseListScriptsAdvertisement response = new EventResponseListScriptsAdvertisement(); response.setScripts( (List<File>) FileUtils.listFiles(jsFile, new String[] { "js" }, false)); jsonMessaging.response(envelope, response); } // Check command and launch script else if (envelope.getObject() instanceof CommandAdvertisement) { CommandAdvertisement advertisement = envelope.getObject(); bindings.put("advertisement", envelope.getObject()); if (compiledCommandScriptMap.get(advertisement.getScript()) == null) { LOGGER.debug("Compile command script: " + advertisement.getScript()); File jsFile = new File("./scripts/command/" + advertisement.getScript()); CompiledScript compile = engine.compile(FileUtils.readFileToString(jsFile)); compiledCommandScriptMap.put(advertisement.getScript(), compile); LOGGER.debug("Launch compiled command script: " + advertisement.getScript()); compile.eval(bindings); } else { LOGGER.info("Launch compiled command script: " + advertisement.getScript()); compiledCommandScriptMap.get(advertisement.getScript()).eval(bindings); } } else if (envelope.getObject() instanceof EventChangesAdvertisement) { reloadService(); } else { for (Event event : events) { if (envelope.getSubject().equals(event.getSubject()) || wildCardMatch(event.getSubject(), envelope.getSubject())) { LOGGER.debug("Run compiled script: " + event.getScript()); try { bindings.put("advertisement", envelope.getObject()); CompiledScript script = compiledScriptMap.get(event.getScript()); if (script != null) script.eval(bindings); else LOGGER.error("Error! Script " + event.getScript() + " is NULL!"); } catch (ScriptException e) { LOGGER.error("Error in script scripts/command/" + event.getScript() + ": " + e.toString()); e.printStackTrace(); } } } } } catch (ScriptException | IOException e) { LOGGER.error("Error in script: " + e.toString()); e.printStackTrace(); } } }); jsonMessaging.start(); } catch (final RuntimeException t) { LOGGER.error("Error in Events!"); status.crashed(); t.printStackTrace(); } }
From source file:com.cloud.hypervisor.xen.resource.CitrixResourceBase.java
protected Answer execute(PoolEjectCommand cmd) { Connection conn = getConnection(); String hostuuid = cmd.getHostuuid(); try {// w w w . j a va2 s .c o m Map<Host, Host.Record> hostrs = Host.getAllRecords(conn); boolean found = false; for (Host.Record hr : hostrs.values()) { if (hr.uuid.equals(hostuuid)) { found = true; } } if (!found) { s_logger.debug("host " + hostuuid + " has already been ejected from pool " + _host.pool); return new Answer(cmd); } Pool pool = Pool.getAll(conn).iterator().next(); Pool.Record poolr = pool.getRecord(conn); Host.Record masterRec = poolr.master.getRecord(conn); if (hostuuid.equals(masterRec.uuid)) { s_logger.debug("This is last host to eject, so don't need to eject: " + hostuuid); return new Answer(cmd); } Host host = Host.getByUuid(conn, hostuuid); // remove all tags cloud stack add before eject Host.Record hr = host.getRecord(conn); Iterator<String> it = hr.tags.iterator(); while (it.hasNext()) { String tag = it.next(); if (tag.startsWith("vmops-version-")) { it.remove(); } } // eject from pool try { Pool.eject(conn, host); try { Thread.sleep(10 * 1000); } catch (InterruptedException e) { } } catch (XenAPIException e) { String msg = "Unable to eject host " + _host.uuid + " due to " + e.toString(); s_logger.warn(msg); host.destroy(conn); } return new Answer(cmd); } catch (XenAPIException e) { String msg = "XenAPIException Unable to destroy host " + _host.uuid + " in xenserver database due to " + e.toString(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } catch (Exception e) { String msg = "Exception Unable to destroy host " + _host.uuid + " in xenserver database due to " + e.getMessage(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } }
From source file:org.nuclos.client.main.MainController.java
void init() throws CommonPermissionException, BackingStoreException { debugFrame = new SwingDebugFrame(this); try {/*w w w . j a v a2 s. co m*/ // force to load real permission (tp) SecurityCache.getInstance().revalidate(); cmdExecuteRport = createEntityAction(NuclosEntity.REPORTEXECUTION); /** @todo this is a workaround - because Main.getMainController() is called to get the user name */ Main.getInstance().setMainController(this); LOG.debug(">>> read user rights..."); loginController.increaseLoginProgressBar(StartUp.PROGRESS_INIT_SECURITYCACHE); if (!getSecurityCache().isActionAllowed(Actions.ACTION_SYSTEMSTART)) { throw new CommonPermissionException(getSpringLocaleDelegate().getMessage("MainController.23", "Sie haben nicht das Recht, {0} zu benutzen.", ApplicationProperties.getInstance().getName())); } loginController.increaseLoginProgressBar(StartUp.PROGRESS_READ_ATTRIBUTES); // DefaultCollectableEntityProvider.setInstance(NuclosCollectableEntityProvider.getInstance()); Thread threadGenericObjectMetaDataCache = new Thread("MainController.readMetaData") { @Override public void run() { LOG.debug(">>> read metadata..."); // GenericObjectMetaDataCache.getInstance(); SpringApplicationContextHolder.getBean(GenericObjectMetaDataCache.class); } }; loginController.increaseLoginProgressBar(StartUp.PROGRESS_READ_LOMETA); Thread threadSearchFilterCache = new Thread("MainController.readSearchFilter") { @Override public void run() { LOG.debug(">>> read searchfilter..."); // SearchFilterCache.getInstance(); SpringApplicationContextHolder.getBean(SearchFilterCache.class); } }; loginController.increaseLoginProgressBar(StartUp.PROGRESS_READ_SEARCHFILTER); Thread threadRuleCache = new Thread("MainController.readRules") { @Override public void run() { LOG.debug(">>> read rules..."); // RuleCache.getInstance(); SpringApplicationContextHolder.getBean(RuleCache.class); } }; loginController.increaseLoginProgressBar(StartUp.PROGRESS_READ_RULES); List<Thread> lstCacheThreads = new ArrayList<Thread>(); lstCacheThreads.add(threadGenericObjectMetaDataCache); lstCacheThreads.add(threadSearchFilterCache); lstCacheThreads.add(threadRuleCache); threadGenericObjectMetaDataCache.start(); threadSearchFilterCache.start(); threadRuleCache.start(); for (Thread t : lstCacheThreads) { try { t.join(); } catch (InterruptedException e) { // do noting here LOG.warn("MainController: " + e); } } // !!! init messagelisteners here. // initialzing chaches in these threads will cause an deadlock situation at realSubscribe in TopicNotificationReceiver. // genericObjectMetaDataCache.initMessageListener(); // searchFilterCache.initMessageListener(); // ruleCache.initMessageListener(); SpringApplicationContextHolder.getBean(GenericObjectMetaDataCache.class).initMessageListener(); SpringApplicationContextHolder.getBean(SearchFilterCache.class).initMessageListener(); SpringApplicationContextHolder.getBean(RuleCache.class).initMessageListener(); LOG.debug(">>> create mainframe..."); // this.frm = new MainFrame(this.getUserName(), this.getNuclosServerName()); setMainFrame(SpringApplicationContextHolder.getBean(MainFrameSpringComponent.class).getMainFrame()); final MainFrame frm = getMainFrame(); frm.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); // Attention: Do not use ListenerUtil here! (tp) frm.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent ev) { cmdWindowClosing(new ResultListener<Boolean>() { @Override public void done(Boolean result) { } }); } }); loginController.increaseLoginProgressBar(StartUp.PROGRESS_CREATE_MAINFRAME); LOG.debug(">>> init client communication..."); this.notificationdlg = new NuclosNotificationDialog(frm); getTopicNotificationReceiver().subscribe(JMSConstants.TOPICNAME_RULENOTIFICATION, messagelistener); loginController.increaseLoginProgressBar(StartUp.PROGRESS_INIT_NOTIFICATION); LOG.debug(">>> setup menus..."); this.setupMenus(); loginController.increaseLoginProgressBar(StartUp.PROGRESS_CREATE_MAINMENU); LOG.debug(">>> create explorer controller..."); this.ctlExplorer = new ExplorerController(); LOG.debug(">>> create task controller..."); this.ctlTasks = new TaskController(getUserName()); this.ctlTasks.setExplorerController(ctlExplorer); this.ctlExplorer.setTaskController(ctlTasks); initActions(); LOG.debug(">>> restore last workspace..."); try { Main.getInstance().getMainFrame().readMainFramePreferences(prefs); getRestoreUtils().restoreWorkspaceThreaded(MainFrame.getLastWorkspaceIdFromPreferences(), MainFrame.getLastWorkspaceFromPreferences(), MainFrame.getLastAlwaysOpenWorkspaceIdFromPreferences(), MainFrame.getLastAlwaysOpenWorkspaceFromPreferences()); } catch (Exception ex) { final String sMessage = getSpringLocaleDelegate().getMessage("MainController.4", "Die in der letzten Sitzung ge\u00f6ffneten Fenster konnten nicht wiederhergestellt werden."); Errors.getInstance().showExceptionDialog(null, sMessage, ex); } finally { loginController.increaseLoginProgressBar(StartUp.PROGRESS_RESTORE_WORKSPACE); } LOG.debug(">>> show mainFrame..."); frm.setVisible(true); try { LOG.debug(">>> restore last controllers (for migration only)..."); reopenAllControllers(ClientPreferences.getUserPreferences()); } catch (Exception ex) { final String sMessage = getSpringLocaleDelegate().getMessage("MainController.4", "Die in der letzten Sitzung ge\u00f6ffneten Fenster konnten nicht wiederhergestellt werden."); Errors.getInstance().showExceptionDialog(null, sMessage, ex); } LOG.debug(">>> restore task views (for migration only)..."); try { ctlTasks.restoreGenericObjectTaskViewsFromPreferences(); } catch (Exception ex) { final String sMessage = getSpringLocaleDelegate().getMessage("tasklist.error.restore", "Die Aufgabenlisten konnten nicht wiederhergestellt werden."); LOG.error(sMessage, ex); Errors.getInstance().showExceptionDialog(null, sMessage, ex); } Thread theadTaskController = new Thread("MainController.refreshTasks") { @Override public void run() { LOG.debug(">>> refresh tasks..."); ctlTasks.run(); } }; theadTaskController.start(); /* Release note HACK: Caused by: java.lang.NullPointerException at org.nuclos.client.help.releasenotes.ReleaseNotesController.showNuclosReleaseNotesNotice(ReleaseNotesController.java:148) at org.nuclos.client.help.releasenotes.ReleaseNotesController.showReleaseNotesIfNewVersion(ReleaseNotesController.java:161) at org.nuclos.client.main.MainController.showReleaseNotesIfNewVersion(MainController.java:1752) at org.nuclos.client.main.MainController.<init>(MainController.java:382) */ while (getHomePane() == null) { Thread.sleep(200); } // Show the release notes for this version, if the user hasn't seen it yet. showReleaseNotesIfNewVersion(); // Debug purposes final String sKeyWindowShow = "CtlShiftF11"; frm.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_F11, (KeyEvent.SHIFT_DOWN_MASK | KeyEvent.CTRL_DOWN_MASK)), sKeyWindowShow); frm.getRootPane().getActionMap().put(sKeyWindowShow, new AbstractAction() { @Override public void actionPerformed(ActionEvent ev) { debugFrame.showComponentDetails(frm.findComponentAt(frm.getMousePosition())); } }); //Call wikipage final String sKeyWikiShow = "CtlShiftF1"; frm.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_F1, (KeyEvent.SHIFT_DOWN_MASK | KeyEvent.CTRL_DOWN_MASK)), sKeyWikiShow); frm.getRootPane().getActionMap().put(sKeyWikiShow, new AbstractAction() { @Override public void actionPerformed(ActionEvent ev) { Component fundComponent = frm.getFocusOwner() != null ? frm.getFocusOwner() : frm.findComponentAt(frm.getMousePosition()); CollectController<?> clctctrl = getControllerForTab(UIUtils.getTabForComponent(fundComponent)); WikiController wikiCtrl = WikiController.getInstance(); wikiCtrl.openURLinBrowser(wikiCtrl.getWikiPageForComponent(fundComponent, clctctrl)); } }); } catch (Throwable e) { LOG.fatal("Creating MainController failed, this is fatal: " + e.toString(), e); throw new ExceptionInInitializerError(e); } }
From source file:org.metawatch.manager.MetaWatchService.java
private void readFromDevice() { if (MetaWatchService.fakeWatch) { try {//from ww w.j a va 2 s . c om Thread.sleep(10000); } catch (InterruptedException e) { } return; } try { byte[] bytes = new byte[256]; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "before blocking read"); // Do a proper read loop int haveread = 0; int lengthtoread = 4; while ((lengthtoread - haveread) != 0) { haveread += inputStream.read(bytes, haveread, lengthtoread - haveread); if (haveread > 1) { lengthtoread = bytes[1]; } } // print received String str = "received: "; int len = (bytes[1] & 0xFF); if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "packet length: " + len); for (int i = 0; i < len; i++) { // str+= Byte.toString(bytes[i]) + ", "; str += "0x" + Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1) + ", "; } if (Preferences.logging) Log.d(MetaWatchStatus.TAG, str); /* * switch (bytes[2]) { case eMessageType.GetDeviceTypeResponse.msg: if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "received: device type response"); break; case eMessageType.NvalOperationResponseMsg.msg: if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "received: nval response"); break; case eMessageType.StatusChangeEvent.msg: if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "received: status change event"); break; } */ /* * if (bytes[2] == 0x31) { // nval response if (bytes[3] == 0x00) // success if (bytes[4] == 0x00) // set to 12 hour format Protocol.setNvalTime(true); } */ if (bytes[2] == eMessageType.NvalOperationResponseMsg.msg) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): NvalOperationResponseMsg"); // Do something here? } else if (bytes[2] == eMessageType.StatusChangeEvent.msg) { // status // change // event if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): status change"); if (bytes[4] == 0x01) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): mode changed"); synchronized (Notification.getInstance().modeChanged) { Notification.getInstance().modeChanged.notify(); } } else if (bytes[4] == 0x11) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): scroll request notification"); synchronized (Notification.getInstance().scrollRequest) { Notification.getInstance().scrollRequest.notify(); } } else if (bytes[4] == 0x10) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): scroll complete."); } else if (bytes[4] == 0x02) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): mode timeout."); // The watch switches back to idle mode (showing the initial // page) after 10 minutes // Activate the last used idle page in this case Idle.getInstance().toPage(MetaWatchService.this, 0); Idle.getInstance().toIdle(MetaWatchService.this); Idle.getInstance().updateIdle(MetaWatchService.this, true); } } else if (bytes[2] == eMessageType.ButtonEventMsg.msg) { // button // press if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): button event"); pressedButton(bytes[3] & 0xFF); // } else if (bytes[2] == eMessageType.GetDeviceTypeResponse.msg) { // device // type if (bytes[4] == 1 || bytes[4] == 4) { watchType = WatchType.ANALOG; watchGen = WatchGen.GEN1; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): device type response; analog watch (gen1)"); NavigationManagement.processWatchConnection(this); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); boolean displaySplash = sharedPreferences.getBoolean("DisplaySplashScreen", false); if (displaySplash) { Protocol.getInstance(MetaWatchService.this).sendOledBitmap( Utils.getBitmap(this, "splash_16_0.bmp"), WatchBuffers.NOTIFICATION, 0); Protocol.getInstance(MetaWatchService.this).sendOledBitmap( Utils.getBitmap(this, "splash_16_1.bmp"), WatchBuffers.NOTIFICATION, 1); } } else { watchType = WatchType.DIGITAL; if (bytes[4] == 5 || bytes[4] == 6) { watchGen = WatchGen.GEN2; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): device type response; Strata/Frame (gen2)"); } else { watchGen = WatchGen.GEN1; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): device type response; digital watch (gen1)"); } Protocol.getInstance(MetaWatchService.this).configureMode(); Protocol.getInstance(MetaWatchService.this).setNvalLcdInvert(Preferences.invertLCD); Protocol.getInstance(MetaWatchService.this).configureIdleBufferSize(true); // Disable built in action for Right top immediate Protocol.getInstance(MetaWatchService.this).disableButton(0, 0, WatchBuffers.IDLE); Protocol.getInstance(MetaWatchService.this).disableButton(0, 0, WatchBuffers.APPLICATION); Protocol.getInstance(MetaWatchService.this).disableButton(0, 0, WatchBuffers.NOTIFICATION); NavigationManagement.processWatchConnection(this); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); boolean displaySplash = sharedPreferences.getBoolean("DisplaySplashScreen", false); if (displaySplash) { Notification.getInstance().addBitmapNotification(this, Utils.getBitmap(this, "splash.png"), new VibratePattern(false, 0, 0, 0), 10000, "Splash"); } // In 10 seconds update the date and time format // Well after the entire connection process, and Idle update on the watch new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { Protocol.getInstance(MetaWatchService.this).setTimeDateFormat(MetaWatchService.this); } }, 10000); } Protocol.getInstance(MetaWatchService.this).getRealTimeClock(); SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(MetaWatchService.this); /* Notify watch on connection if requested. */ boolean notifyOnConnect = sharedPreferences.getBoolean("NotifyWatchOnConnect", false); if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.connect(): notifyOnConnect=" + notifyOnConnect); if (notifyOnConnect) { NotificationBuilder.createOtherNotification(MetaWatchService.this, null, "MetaWatch", getResources().getString(R.string.connection_connected), 1); } Idle.getInstance().activateButtons(this); } else if (bytes[2] == eMessageType.ReadBatteryVoltageResponse.msg) { boolean powerGood = bytes[4] > 0; boolean batteryCharging = bytes[5] > 0; float batterySense = (((int) bytes[7] << 8) + (int) bytes[6]) / 1000.0f; float batteryAverage = (((int) bytes[9] << 8) + (int) bytes[8]) / 1000.0f; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): received battery voltage response." + " power_good=" + powerGood + " battery_charging=" + batteryCharging + " battery_sense=" + batterySense + " battery_average=" + batteryAverage); String voltageFrequencyString = PreferenceManager.getDefaultSharedPreferences(this) .getString("collectWatchVoltage", "0"); final int voltageFrequency = Integer.parseInt(voltageFrequencyString); if (voltageFrequency > 0) { File sdcard = Environment.getExternalStorageDirectory(); File csv = new File(sdcard, "metawatch_voltage.csv"); boolean fileExists = csv.exists(); FileWriter fw = new FileWriter(csv, true); if (fileExists == false) { fw.write("Date,Sense,Average\n"); } Date date = new Date(); fw.write("\"" + date.toString() + "\"," + batterySense + "," + batteryAverage + "\n"); fw.flush(); fw.close(); } } else if (bytes[2] == eMessageType.ReadLightSensorResponse.msg) { float lightSense = (((int) bytes[1] << 8) + (int) bytes[0]) / 1000.0f; float lightAverage = (((int) bytes[3] << 8) + (int) bytes[2]) / 1000.0f; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): received light sensor response." + " light_sense=" + lightSense + " light_average=" + lightAverage); } else if (bytes[2] == eMessageType.GetRealTimeClockResponse.msg) { long timeNow = System.currentTimeMillis(); long roundTrip = timeNow - Monitors.getInstance().getRTCTimestamp; if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): received rtc response." + " round trip= " + roundTrip); Monitors.getInstance().rtcOffset = (int) (roundTrip / 2000); Protocol.getInstance(MetaWatchService.this).setRealTimeClock(MetaWatchService.this); } else { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, "MetaWatchService.readFromDevice(): Unknown message : 0x" + Integer.toString((bytes[2] & 0xff) + 0x100, 16).substring(1) + ", "); } } catch (IOException e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); resetConnection(); } catch (Exception e) { if (Preferences.logging) Log.d(MetaWatchStatus.TAG, e.toString()); resetConnection(); } }