public Bitmap getBitmap(String fileId, String size, boolean fromUrl) { File file = fileCache.getFile(fileId + size); // from SD cache Bitmap bitmap = decodeFile(file, size); if (bitmap != null) { return bitmap; } // from web try { bitmap = null; if (fromUrl) { InputStream is = ConnectionHandler.httpGetRequest(fileId, UsersManagement.getLoginUser().getId()); OutputStream os = new FileOutputStream(file); Utils.copyStream(is, os); os.close(); is.close(); } else { CouchDB.downloadFile(fileId, file); } bitmap = decodeFile(file, size); return bitmap; // return ConnectionHandler.getBitmapObject(url); } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
/** Destroy all services. */ public void destroy() { XLog log = new XLog(LogFactory.getLog(getClass())); log.trace("Shutting down"); boolean deleteRuntimeDir = false; if (conf != null) { deleteRuntimeDir = conf.getBoolean(CONF_DELETE_RUNTIME_DIR, false); } if (services != null) { List<Service> list = new ArrayList<Service>(services.values()); Collections.reverse(list); for (Service service : list) { try { log.trace("Destroying service[{0}]", service.getInterface()); if (service.getInterface() == XLogService.class) { log.info("Shutdown"); } service.destroy(); } catch (Throwable ex) { log.error( "Error destroying service[{0}], {1}", service.getInterface(), ex.getMessage(), ex); } } } if (deleteRuntimeDir) { try { IOUtils.delete(new File(runtimeDir)); } catch (IOException ex) { log.error("Error deleting runtime directory [{0}], {1}", runtimeDir, ex.getMessage(), ex); } } services = null; conf = null; SERVICES = null; }
public Bitmap getBitmap(String url) { File f = fileCache.getFile(url); // from SD cache Bitmap bitmap = decodeFile(f); if (bitmap != null) { Logger.error("ImageLoader", "fileCache.returnBitmap : " + url); return bitmap; } // from web try { bitmap = null; InputStream is = ConnectionHandler.httpGetRequest(url, UsersManagement.getLoginUser().getId()); OutputStream os = new FileOutputStream(f); Utils.copyStream(is, os); os.close(); is.close(); // conn.disconnect(); bitmap = decodeFile(f); return bitmap; // return ConnectionHandler.getBitmapObject(url); } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
@Test /** Single SBMLTestCase: Can be read and is network created ? */ public void testSingleTestCase() throws Exception { logger.info(String.format("SBMLTestCase: %s", resource)); final NetworkTestSupport nts = new NetworkTestSupport(); final CyNetworkFactory networkFactory = nts.getNetworkFactory(); final CyNetworkViewFactory viewFactory = null; TaskMonitor taskMonitor = null; // read SBML String[] tokens = resource.split("/"); String fileName = tokens[2]; InputStream instream = getClass().getResourceAsStream(resource); CyNetwork[] networks; try { // Reader can be tested without service adapter, SBMLReaderTask readerTask = new SBMLReaderTask(instream, fileName, networkFactory, null, null); readerTask.run(taskMonitor); networks = readerTask.getNetworks(); assertFalse(readerTask.getError()); } catch (Throwable t) { networks = null; t.printStackTrace(); } // Networks could be read assertNotNull(networks); assertTrue(networks.length >= 1); }
@Test public void testGetNhinPatientDiscoveryProxyHappy() { try { NhinPatientDiscoveryProxyObjectFactory proxyFactory = new NhinPatientDiscoveryProxyObjectFactory() { @Override protected Log createLogger() { return mockLog; } @Override protected <T extends Object> T getBean(String beanName, Class<T> type) { return type.cast(mockProxy); } // protected ApplicationContext createApplicationContext() // { // return appContext; // } // @Override // protected ApplicationContext getContext() // { // return appContext; // } }; NhinPatientDiscoveryProxy proxy = proxyFactory.getNhinPatientDiscoveryProxy(); assertNotNull("NhinPatientDiscoveryProxy was null", proxy); } catch (Throwable t) { System.out.println( "Error running testGetNhinPatientDiscoveryProxyHappy test: " + t.getMessage()); t.printStackTrace(); fail("Error running testGetNhinPatientDiscoveryProxyHappy test: " + t.getMessage()); } }
/** * Parses a given .svg for nodes * * @return <b>bothNodeLists</b> an Array with two NodeLists */ public static NodeList[] parseSVG(Date date) { /* As it has to return two things, it can not return them * directly but has to encapsulate it in another object. */ NodeList[] bothNodeLists = new NodeList[2]; ; try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); String SVGFileName = "./draw_map_svg.svg"; File svgMap = new File(SVGFileName); System.out.println("Parsing the svg"); // Status message #1 Parsing System.out.println("This should not longer than 30 seconds"); // Status message #2 Parsing Document doc = docBuilder.parse(SVGFileName); // "text" is the actual planet/warplanet NodeList listOfPlanetsAsXMLNode = doc.getElementsByTagName("text"); // "line" is the line drawn by a warplanet. Used for calculation of warplanet coordinates. NodeList listOfLinesAsXMLNode = doc.getElementsByTagName("line"); bothNodeLists[0] = listOfPlanetsAsXMLNode; bothNodeLists[1] = listOfLinesAsXMLNode; // normalize text representation doc.getDocumentElement().normalize(); // Build the fileName the .svg should be renamed to, using the dateStringBuilder String newSVGFileName = MapTool.dateStringBuilder(MapTool.getKosmorDate(date), date); newSVGFileName = newSVGFileName.concat(" - Map - kosmor.com - .svg"); // Making sure the directory does exist, if not, it is created File svgdir = new File("svg"); if (!svgdir.exists() || !svgdir.isDirectory()) { svgdir.mkdir(); } svgMap.renameTo(new File(svgdir + "\\" + newSVGFileName)); System.out.println("Done parsing"); // Status message #3 Parsing } catch (SAXParseException err) { System.out.println( "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage()); } catch (SAXException e) { Exception x = e.getException(); ((x == null) ? e : x).printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } return bothNodeLists; }
/** Marshall the given parameter object, and output to a SdkJsonGenerator */ public void marshall(UniqueProblem uniqueProblem, StructuredJsonGenerator jsonGenerator) { if (uniqueProblem == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { jsonGenerator.writeStartObject(); if (uniqueProblem.getMessage() != null) { jsonGenerator.writeFieldName("message").writeValue(uniqueProblem.getMessage()); } java.util.List<Problem> problemsList = uniqueProblem.getProblems(); if (problemsList != null) { jsonGenerator.writeFieldName("problems"); jsonGenerator.writeStartArray(); for (Problem problemsListValue : problemsList) { if (problemsListValue != null) { ProblemJsonMarshaller.getInstance().marshall(problemsListValue, jsonGenerator); } } jsonGenerator.writeEndArray(); } jsonGenerator.writeEndObject(); } catch (Throwable t) { throw new SdkClientException("Unable to marshall request to JSON: " + t.getMessage(), t); } }
/** * Tests that a service that fails in the constructor has the error passed to the error service */ @Test public void testServiceFailsInConstructor() { ServiceLocator locator = LocatorHelper.getServiceLocator( RecordingErrorService.class, ServiceFailsInConstructor.class); ActiveDescriptor<?> serviceDescriptor = locator.getBestDescriptor( BuilderHelper.createContractFilter(ServiceFailsInConstructor.class.getName())); Assert.assertNotNull(serviceDescriptor); try { locator.getService(ServiceFailsInConstructor.class); Assert.fail("Should have failed"); } catch (MultiException me) { Assert.assertTrue(me.getMessage().contains(ERROR_STRING)); } List<ErrorInformation> errors = locator.getService(RecordingErrorService.class).getAndClearErrors(); Assert.assertEquals(1, errors.size()); ErrorInformation ei = errors.get(0); Assert.assertEquals(ErrorType.SERVICE_CREATION_FAILURE, ei.getErrorType()); Assert.assertEquals(serviceDescriptor, ei.getDescriptor()); Assert.assertNull(ei.getInjectee()); Throwable associatedException = ei.getAssociatedException(); Assert.assertTrue(associatedException.getMessage().contains(ERROR_STRING)); }
public void run() { StringBuffer data = new StringBuffer(); Print.logDebug("Client:InputThread started"); while (true) { data.setLength(0); boolean timeout = false; try { if (this.readTimeout > 0L) { this.socket.setSoTimeout((int) this.readTimeout); } ClientSocketThread.socketReadLine(this.socket, -1, data); } catch (InterruptedIOException ee) { // SocketTimeoutException ee) { // error("Read interrupted (timeout) ..."); if (getRunStatus() != THREAD_RUNNING) { break; } timeout = true; // continue; } catch (Throwable t) { Print.logError("Client:InputThread - " + t); t.printStackTrace(); break; } if (!timeout || (data.length() > 0)) { ClientSocketThread.this.handleMessage(data.toString()); } } synchronized (this.threadLock) { this.isRunning = false; Print.logDebug("Client:InputThread stopped"); this.threadLock.notify(); } }
/** ** Main client thread loop */ public void run() { this.setRunStatus(THREAD_RUNNING); this.threadStarted(); try { this.openSocket(); this.inputThread = new InputThread(this.socket, this.readTimeout, this.ioThreadLock); this.outputThread = new OutputThread(this.socket, this.ioThreadLock); this.inputThread.start(); this.outputThread.start(); synchronized (this.ioThreadLock) { while (this.inputThread.isRunning() || this.outputThread.isRunning()) { try { this.ioThreadLock.wait(); } catch (Throwable t) { } } } } catch (NoRouteToHostException nrthe) { Print.logInfo("Client:ControlThread - Unable to reach " + this.host + ":" + this.port); nrthe.printStackTrace(); } catch (Throwable t) { Print.logInfo("Client:ControlThread - " + t); t.printStackTrace(); } finally { this.closeSocket(); } this.setRunStatus(THREAD_STOPPED); this.threadStopped(); }
private void deferExpired() { for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) { JedisPool jedisPool = entry.getValue(); try { Jedis jedis = jedisPool.getResource(); try { RedisRegistryUtil.publishToJedis(jedis, getRegistered(), root, expirePeriod); if (admin) { clean(jedis); } if (!replicate) { break; // 如果服务器端已同步数据,只需写入单台机器 } } finally { jedisPool.returnResource(jedis); } } catch (Throwable t) { logger.warn( "Failed to write provider heartbeat to redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t); } } }
/** * Use reflection to invoke the requested method. Cache the method object to speed up the process * will be invoked * * @param methodName The method to call. * @param params The arguments passed to the called method. */ private Object doPrivileged(final String methodName, final Object[] params) { try { return invokeMethod(context, methodName, params); } catch (Throwable t) { throw new RuntimeException(t.getMessage()); } }
public void run() { // on mac os x 10.5.x, when i run a 'sudo' command, i need to write // the admin password out immediately; that's why this code is // here. if (sudoIsRequested) { // doSleep(500); printWriter.println(adminPassword); printWriter.flush(); } BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = bufferedReader.readLine()) != null) { outputBuffer.append(line + "\n"); } } catch (IOException ioe) { ioe.printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { // ignore this one } } }
public static void load() { libraryNames = PlatformDependencies.currentLibraryNames; libraryExtensions = PlatformDependencies.currentLibraryExtension; String dir = ""; try { dir = PropertiesBean.getProperty(PropertiesNames.RESOURCES_DIR /*"dirs.resources"*/); } catch (NoSuchPropertyException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.warning(e.toString()); dir = ".\\resources"; } for (int i = 0; i < libraryNames.length; ++i) { String latestLib = getLatestFileName(dir, libraryNames[i], libraryExtensions); try { System.load(latestLib); logger.fine("loaded " + latestLib); // debug } catch (Throwable e1) { logger.warning("Error While loading library " + latestLib + ": " + e1.toString()); } } // // initialize ResourceManager with resources from resources directory // ResourceManager.addResources(dir); }
private Bitmap getBitmap(String url) { File f = fileCache.getFile(url); // from SD cache Bitmap b = decodeFile(f); if (b != null) return b; // from web try { Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(f); Utils.CopyStream(is, os); os.close(); conn.disconnect(); bitmap = decodeFile(f); return bitmap; } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
protected Set<Class> processJarUrl(URL url, String basepath, Class clazz) throws IOException { Set<Class> set = new HashSet<Class>(); String path = url.getFile().substring(5, url.getFile().indexOf("!")); JarFile jar = new JarFile(path); for (Enumeration entries = jar.entries(); entries.hasMoreElements(); ) { JarEntry entry = (JarEntry) entries.nextElement(); if (entry.getName().startsWith(basepath) && entry.getName().endsWith(".class")) { try { String name = entry.getName(); // Ignore anonymous // TODO RM what about the other anonymous classes like $2, $3 ? if (name.contains("$1")) { continue; } URL classURL = classLoader.getResource(name); ClassReader reader = new ClassReader(classURL.openStream()); ClassScanner visitor = getScanner(clazz); reader.accept(visitor, 0); if (visitor.isMatch()) { Class c = loadClass(visitor.getClassName()); if (c != null) { set.add(c); } } } catch (Exception e) { if (logger.isDebugEnabled()) { Throwable t = ExceptionHelper.getRootException(e); logger.debug(String.format("%s: caused by: %s", e.toString(), t.toString())); } } } } return set; }
/** Tests that a third-party service that fails in dispose */ @Test public void testFailingInDisposeThirdPartyService() { ServiceLocator locator = LocatorHelper.getServiceLocator(RecordingErrorService.class); AlwaysFailInDisposeActiveDescriptor thirdPartyDescriptor = new AlwaysFailInDisposeActiveDescriptor(); ServiceLocatorUtilities.addOneDescriptor(locator, thirdPartyDescriptor); ActiveDescriptor<?> serviceDescriptor = locator.getBestDescriptor( BuilderHelper.createContractFilter(SimpleService.class.getName())); Assert.assertNotNull(serviceDescriptor); ServiceHandle<SimpleService> handle = locator.getServiceHandle(SimpleService.class); Assert.assertNotNull(handle); Assert.assertNotNull(handle.getService()); handle.destroy(); List<ErrorInformation> errors = locator.getService(RecordingErrorService.class).getAndClearErrors(); Assert.assertEquals(1, errors.size()); ErrorInformation ei = errors.get(0); Assert.assertEquals(ErrorType.SERVICE_DESTRUCTION_FAILURE, ei.getErrorType()); Assert.assertEquals(serviceDescriptor, ei.getDescriptor()); Assert.assertNull(ei.getInjectee()); Throwable associatedException = ei.getAssociatedException(); Assert.assertTrue(associatedException.getMessage().contains(ERROR_STRING)); }
public static void main(String[] args) { try { int port = DEFAULT_SERVER_PORT; File systemDir = null; if (args.length > 0) { try { port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Error parsing port: " + e.getMessage()); System.exit(-1); } systemDir = new File(args[1]); } final Server server = new Server( systemDir, System.getProperty(GlobalOptions.USE_MEMORY_TEMP_CACHE_OPTION) != null); initLoggers(); server.start(port); System.out.println("Server classpath: " + System.getProperty("java.class.path")); System.err.println(SERVER_SUCCESS_START_MESSAGE + port); } catch (Throwable e) { System.err.println(SERVER_ERROR_START_MESSAGE + e.getMessage()); e.printStackTrace(System.err); System.exit(-1); } }
/** Marshall the given parameter object, and output to a SdkJsonGenerator */ public void marshall( VaultNotificationConfig vaultNotificationConfig, StructuredJsonGenerator jsonGenerator) { if (vaultNotificationConfig == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } try { jsonGenerator.writeStartObject(); if (vaultNotificationConfig.getSNSTopic() != null) { jsonGenerator.writeFieldName("SNSTopic").writeValue(vaultNotificationConfig.getSNSTopic()); } java.util.List<String> eventsList = vaultNotificationConfig.getEvents(); if (eventsList != null) { jsonGenerator.writeFieldName("Events"); jsonGenerator.writeStartArray(); for (String eventsListValue : eventsList) { if (eventsListValue != null) { jsonGenerator.writeValue(eventsListValue); } } jsonGenerator.writeEndArray(); } jsonGenerator.writeEndObject(); } catch (Throwable t) { throw new AmazonClientException("Unable to marshall request to JSON: " + t.getMessage(), t); } }
public void compileCorrectFiles( BindingContext bindingContext, List<JetFile> files, CompilationErrorHandler errorHandler, boolean annotate) { ClosureAnnotator closureAnnotator = !annotate ? null : new ClosureAnnotator(bindingContext, files); typeMapper = new JetTypeMapper(standardLibrary, bindingContext, closureAnnotator); bindingContexts.push(bindingContext); try { for (JetFile namespace : files) { try { generateNamespace(namespace); } catch (Throwable e) { errorHandler.reportException(e, namespace.getContainingFile().getVirtualFile().getUrl()); DiagnosticUtils.throwIfRunningOnServer(e); if (ApplicationManager.getApplication().isInternal()) { e.printStackTrace(); } } } } finally { bindingContexts.pop(); typeMapper = null; } }
public static final String format(Throwable toss) { StringWriter sw = new StringWriter(); // Improved nested exception handling PrintWriter pw = new PrintWriter(sw) { boolean stop = false; @Override public void print(String s) { if (s.startsWith("Caused by")) stop = true; else if (!s.startsWith(" ") && !s.startsWith("\t")) stop = false; if (!stop) super.print(s); } @Override public void println() { if (!stop) super.println(); } }; for (Throwable t = toss; t != null; ) { t.printStackTrace(pw); t = t.getCause(); if (t != null) pw.append("Caused by: "); } return sw.toString(); }
public Object execute(Environment environment) throws Exception { log.debug("handling job " + jobDbid + " exception: " + exception.getMessage()); // load the job from the db DbSession dbSession = environment.get(DbSession.class); if (dbSession == null) { throw new JbpmException("no job-session configured to handle job"); } JobImpl job = dbSession.get(JobImpl.class, jobDbid); // serialize the stack trace StringWriter sw = new StringWriter(); exception.printStackTrace(new PrintWriter(sw)); if (job != null) { // decrement the number of retries int decrementedRetries = job.getRetries() - 1; log.debug("decrementing retries to " + decrementedRetries + " for " + job); job.release(); job.setRetries(decrementedRetries); job.setException(sw.toString()); // notify the job executor after the transaction is completed Transaction transaction = environment.get(Transaction.class); JobExecutor jobExecutor = environment.get(JobExecutor.class); if ((transaction != null) && (jobExecutor != null)) { log.trace("registering job executor notifier with " + transaction); transaction.registerSynchronization(new JobAddedNotification(jobExecutor)); } } return null; }
@Test public void testGetConfigFileName() { try { final ApplicationContext mockContext = context.mock(ApplicationContext.class); NhinPatientDiscoveryProxyObjectFactory proxyFactory = new NhinPatientDiscoveryProxyObjectFactory() { @Override protected Log createLogger() { return mockLog; } @Override protected String getConfigFileName() { return "TEST_CONFIG_FILE_NAME"; } @Override protected ApplicationContext getContext() { return mockContext; } }; assertEquals("Config file name", "TEST_CONFIG_FILE_NAME", proxyFactory.getConfigFileName()); } catch (Throwable t) { System.out.println("Error running testGetConfigFileName test: " + t.getMessage()); t.printStackTrace(); fail("Error running testGetConfigFileName test: " + t.getMessage()); } }
protected Object reifyCall( String className, String methodName, Class<?>[] parameterTypes, Object[] effectiveParameters, short priority) { try { return this.proxy.reify( MethodCall.getComponentMethodCall( Class.forName(className).getDeclaredMethod(methodName, parameterTypes), effectiveParameters, null, (String) null, null, priority)); // functional interface name is null } catch (NoSuchMethodException e) { throw new ProActiveRuntimeException(e.toString()); } catch (ClassNotFoundException e) { throw new ProActiveRuntimeException(e.toString()); } catch (Throwable e) { throw new ProActiveRuntimeException(e.toString()); } }
/** * Unregisters all JSP page servlets for a plugin. * * @param webXML the web.xml file containing JSP page names to servlet class file mappings. */ public static void unregisterServlets(File webXML) { if (!webXML.exists()) { Log.error( "Could not unregister plugin servlets, file " + webXML.getAbsolutePath() + " does not exist."); return; } // Find the name of the plugin directory given that the webXML file // lives in plugins/[pluginName]/web/web.xml String pluginName = webXML.getParentFile().getParentFile().getParentFile().getName(); try { SAXReader saxReader = new SAXReader(false); saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); Document doc = saxReader.read(webXML); // Find all <servelt-mapping> entries to discover name to URL mapping. List names = doc.selectNodes("//servlet-mapping"); for (int i = 0; i < names.size(); i++) { Element nameElement = (Element) names.get(i); String url = nameElement.element("url-pattern").getTextTrim(); // Destroy the servlet than remove from servlets map. GenericServlet servlet = servlets.get(pluginName + url); if (servlet != null) { servlet.destroy(); } servlets.remove(pluginName + url); servlet = null; } } catch (Throwable e) { Log.error(e.getMessage(), e); } }
/** * Print a log entry in the knapsack style. * * @param bundle * @param sr * @param level * @param msg * @param throwable */ public static void doKnapsackLog( Bundle bundle, ServiceReference sr, int level, String msg, Throwable throwable) { if (dateFormatter == null) dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); StringBuilder sb = new StringBuilder(); sb.append(dateFormatter.format(new Date(System.currentTimeMillis()))); sb.append(' '); getLevelLabel(level, sb); sb.append(' '); sb.append(msg); sb.append(StringConstants.TAB); getBundleLabel(bundle, sb); // Check for an exception, if available display it. if (throwable != null) { sb.append(throwable.getMessage()); sb.append(StringConstants.CRLF); StringWriter sWriter = new StringWriter(); PrintWriter pw = new PrintWriter(sWriter); throwable.printStackTrace(pw); sb.append(sWriter.toString()); } System.out.println(sb.toString()); }
private void persist(PersistAction persistAction, String successMessage) { if (selected != null) { setEmbeddableKeys(); try { if (persistAction != PersistAction.DELETE) { getFacade().edit(selected); } else { getFacade().remove(selected); } JsfUtil.addSuccessMessage(successMessage); } catch (EJBException ex) { String msg = ""; Throwable cause = ex.getCause(); if (cause != null) { msg = cause.getLocalizedMessage(); } if (msg.length() > 0) { JsfUtil.addErrorMessage(msg); } else { JsfUtil.addErrorMessage( ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } catch (Exception ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); JsfUtil.addErrorMessage( ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } }
public int sendAlarm(final AlarmInfo alarmInfo) { AlarmType type = alarmInfo.type; String id = alarmInfo.getId(); String extraInfo = alarmInfo.getExtraInfo(); if (terminationToken.isToShutdown()) { // 记录告警信息 System.err.println("rejected alarm:" + id + "," + extraInfo); return -1; } int duplicateSubmissionCount = 0; try { AtomicInteger prevSubmittedCounter; prevSubmittedCounter = submittedAlarmRegistry.putIfAbsent( type.toString() + ':' + id + '@' + extraInfo, new AtomicInteger(0)); if (null == prevSubmittedCounter) { terminationToken.reservations.incrementAndGet(); alarmQueue.put(alarmInfo); } else { // 故障未恢复,不用重复发送告警信息给服务器,故仅增加计数 duplicateSubmissionCount = prevSubmittedCounter.incrementAndGet(); } } catch (Throwable t) { t.printStackTrace(); } return duplicateSubmissionCount; }
@Override public String doNotNullMarshall(final Object o, final MarshallingSession ctx) { Throwable cause = getCause(((Throwable) o)); String message = null; if (cause != null) { message = cause.getMessage(); } return "{\"" + SerializationParts.ENCODED_TYPE + "\":\"" + RuntimeException.class.getName() + "\"," + "\"" + SerializationParts.OBJECT_ID + "\":\"" + o.hashCode() + "\"," + "\"" + "message" + "\":\"" + ((cause != null) ? MarshallUtil.jsonStringEscape(cause.getClass().getName()) : "") + ((message != null) ? ":" + MarshallUtil.jsonStringEscape(message) : "") + "\"}"; }
static { // check if we have JAI and or ImageIO // if these classes are here, then the runtine environment has // access to JAI and the JAI ImageI/O toolbox. boolean available = true; try { Class.forName("javax.media.jai.JAI"); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); available = false; } JAIAvailable = available; available = true; try { Class<?> clazz = Class.forName("com.sun.media.imageioimpl.plugins.tiff.TIFFImageReaderSpi"); readerSpi = (ImageReaderSpi) clazz.newInstance(); Class<?> clazz1 = Class.forName("com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriterSpi"); writerSpi = (ImageWriterSpi) clazz1.newInstance(); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); readerSpi = null; writerSpi = null; available = false; } TiffAvailable = available; final HashSet<String> tempSet = new HashSet<String>(2); tempSet.add(".tfw"); tempSet.add(".tiffw"); tempSet.add(".wld"); TIFF_WORLD_FILE_EXT = Collections.unmodifiableSet(tempSet); }