/** * Performs OCR operation. * * @param imageList a list of <code>IIOImage</code> objects * @param rect the bounding rectangle defines the region of the image to be recognized. A * rectangle of zero dimension or <code>null</code> indicates the whole image. * @return the recognized text * @throws TesseractException */ public String doOCR(List<IIOImage> imageList, Rectangle rect) throws TesseractException { init(); setTessVariables(); try { StringBuilder sb = new StringBuilder(); for (IIOImage oimage : imageList) { pageNum++; try { setImage(oimage.getRenderedImage(), rect); sb.append(getOCRText()); } catch (IOException ioe) { // skip the problematic image logger.log(Level.SEVERE, ioe.getMessage(), ioe); } } if (hocr) { sb.insert(0, htmlBeginTag).append(htmlEndTag); } return sb.toString(); } finally { dispose(); } }
public ConsoleManager(GlowServer server) { this.server = server; // install Ansi code handler, which makes colors work on Windows AnsiConsole.systemInstall(); for (Handler h : logger.getHandlers()) { logger.removeHandler(h); } // used until/unless gui is created consoleHandler = new FancyConsoleHandler(); // consoleHandler.setFormatter(new DateOutputFormatter(CONSOLE_DATE)); logger.addHandler(consoleHandler); // todo: why is this here? Runtime.getRuntime().addShutdownHook(new ServerShutdownThread()); // reader must be initialized before standard streams are changed try { reader = new ConsoleReader(); } catch (IOException ex) { logger.log(Level.SEVERE, "Exception initializing console reader", ex); } reader.addCompleter(new CommandCompleter()); // set system output streams System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO), true)); System.setErr(new PrintStream(new LoggerOutputStream(Level.WARNING), true)); }
/** @param aProperties the updated properties. */ @SuppressWarnings("rawtypes") final void setProperties(final Dictionary aProperties) { final Map<String, String> newProps = new HashMap<String, String>(); Enumeration keys = aProperties.keys(); while (keys.hasMoreElements()) { final String key = (String) keys.nextElement(); if (!KNOWN_KEYS.contains(key) && !IGNORED_KEYS.contains(key)) { LOG.log(Level.WARNING, "Unknown/unsupported profile key: " + key); continue; } final String value = aProperties.get(key).toString(); newProps.put(key, value.trim()); } // Verify whether all known keys are defined... final List<String> checkedKeys = new ArrayList<String>(KNOWN_KEYS); checkedKeys.removeAll(newProps.keySet()); if (!checkedKeys.isEmpty()) { throw new IllegalArgumentException( "Profile settings not complete! Missing keys are: " + checkedKeys.toString()); } this.properties.putAll(newProps); LOG.log( Level.INFO, "New device profile settings applied for {1} ({0}) ...", // new Object[] {getType(), getDescription()}); }
/** * Create a configuration file based on the internally stored configuration. * * @return The StringBuffer object associated with the internal JSON configuration file. */ private static StringBuffer create() { Logger.log("Creating default configuration file 'config.json'...", Logger.CRITICAL); StringBuffer fileData = getLocalConfig(); try { JsonObject json = (JsonObject) new JsonParser().parse(fileData.toString()); // # Remove config version from the output // # This config string will be used internally for // # tracking versions of cingif files when writing new ones // # or receiving new ones. json.remove("config-version"); // # Write configuration file. FileOutputStream out = new FileOutputStream("config.json"); out.write(json.toString().getBytes()); out.close(); } catch (JsonParseException e) { // # Should never get here because the config file is packaged internaly... // # If it fails, probably a developer not formatting the config file properly. Logger.log( "Compiling and creating the config file failed. Ensure you have properly formatted JSON data before recompiling your extension.", Logger.CRITICAL); } catch (IOException e) { Logger.log("Failed to write the configuration file: " + e.getMessage(), Logger.CRITICAL); } return fileData; }
/* good2() reverses the bodies in the if statement */ private void good2(HttpServletRequest request, HttpServletResponse response) throws Throwable { if (IO.static_returns_t()) { Logger tcLog = Logger.getLogger("cwe_testcases_logger"); if (request.getParameter("username") == null) { return; } String username = request.getParameter("username"); if (username.matches("[a-zA-Z0-9]*")) { HttpSession session = request.getSession(true); /* FIX: logged message does not contain session id */ tcLog.log(Level.FINEST, "Username: "******" Session ID:" + session.getId()); } else { response.getWriter().println("Invalid characters"); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger tcLog = Logger.getLogger("cwe_testcases_logger"); if (request.getParameter("username") == null) { return; } String username = request.getParameter("username"); if (username.matches("[a-zA-Z0-9]*")) { HttpSession session = request.getSession(true); /* FLAW: leak session ID to debug log */ tcLog.log(Level.FINEST, "Username: "******" Session ID:" + session.getId()); } else { response.getWriter().println("Invalid characters"); } } }
public boolean intersects(int x, int y, Rectangle rectangle) { try { Rectangle up = new Rectangle(rectangle.getX(), rectangle.getY() - 2, rectangle.getWidth(), 1); Rectangle right = new Rectangle( rectangle.getX() + rectangle.getWidth() + 1, rectangle.getY(), 1, rectangle.getHeight()); Rectangle down = new Rectangle( rectangle.getX(), rectangle.getY() + rectangle.getHeight() + 1, rectangle.getWidth(), 1); Rectangle left = new Rectangle(rectangle.getX() - 2, rectangle.getY(), 1, rectangle.getHeight()); Rectangle rect = blocks[x][y].getRect(); return (rect.intersects(up) || rect.intersects(right) || rect.intersects(down) || rect.intersects(left)); } catch (NullPointerException e) { logger.log("NullPointerException in World.intersects(int, int, Rectangle)", Level.DEBUG); logger.log("Stack:", Level.DEBUG); logger.log(e.getMessage(), Level.DEBUG); } return false; }
/** Load the configuration file for our server. This method is thread-safe. */ public static synchronized void load() { // # Ensure config file not already loaded... if (configLoaded) { return; } // # Read configuration file, and assign it to our configuration JSONObject try { configuration = (JsonObject) new JsonParser().parse(readFile("config.json").toString()); } catch (JsonParseException e) { // # Someone must have modified (poorly) the JSON configuration file. Logger.log("Malformed JSON in the configuration file.", Logger.CRITICAL); } catch (FileNotFoundException e) { // # Couldn't find the config file, so we write our default one. Logger.log( "Cannot find the configuration file. Creating default config file.", Logger.CRITICAL); configuration = (JsonObject) new JsonParser().parse(create().toString()); } // # Go ahead and assign these values. This is more for developers of SmartSocket than end-user // use. try { Config.autoUpdate = configuration.getAsJsonObject("auto-update"); Config.crossdomainPolicyFile = configuration.getAsJsonObject("crossdomain-policy-file"); Config.tcpExtensions = configuration.getAsJsonObject("tcp-extensions"); Config.udpExtensions = configuration.getAsJsonObject("udp-extensions"); } catch (Exception e) { } Logger.log("Configuration loading is complete.", Logger.CRITICAL); configLoaded = true; }
/** * @param sourceFile File to read from * @return List of String objects with the shas */ public static FileRequestFileContent readRequestFile(final File sourceFile) { if (!sourceFile.isFile() || !(sourceFile.length() > 0)) { return null; } Document d = null; try { d = XMLTools.parseXmlFile(sourceFile.getPath()); } catch (final Throwable t) { logger.log(Level.SEVERE, "Exception in readRequestFile, during XML parsing", t); return null; } if (d == null) { logger.log(Level.SEVERE, "Could'nt parse the request file"); return null; } final Element rootNode = d.getDocumentElement(); if (rootNode.getTagName().equals(TAG_FrostFileRequestFile) == false) { logger.severe( "Error: xml request file does not contain the root tag '" + TAG_FrostFileRequestFile + "'"); return null; } final String timeStampStr = XMLTools.getChildElementsTextValue(rootNode, TAG_timestamp); if (timeStampStr == null) { logger.severe("Error: xml file does not contain the tag '" + TAG_timestamp + "'"); return null; } final long timestamp = Long.parseLong(timeStampStr); final List<Element> nodelist = XMLTools.getChildElementsByTagName(rootNode, TAG_shaList); if (nodelist.size() != 1) { logger.severe("Error: xml request files must contain only one element '" + TAG_shaList + "'"); return null; } final Element rootShaNode = nodelist.get(0); final List<String> shaList = new LinkedList<String>(); final List<Element> xmlKeys = XMLTools.getChildElementsByTagName(rootShaNode, TAG_sha); for (final Element el : xmlKeys) { final Text txtname = (Text) el.getFirstChild(); if (txtname == null) { continue; } final String sha = txtname.getData(); shaList.add(sha); } final FileRequestFileContent content = new FileRequestFileContent(timestamp, shaList); return content; }
/** * Sends a specific <tt>Request</tt> to the STUN server associated with this * <tt>StunCandidateHarvest</tt>. * * @param request the <tt>Request</tt> to send to the STUN server associated with this * <tt>StunCandidateHarvest</tt> * @param firstRequest <tt>true</tt> if the specified <tt>request</tt> should be sent as the first * request in the terms of STUN; otherwise, <tt>false</tt> * @return the <tt>TransactionID</tt> of the STUN client transaction through which the specified * <tt>Request</tt> has been sent to the STUN server associated with this * <tt>StunCandidateHarvest</tt> * @param transactionID the <tt>TransactionID</tt> of <tt>request</tt> because <tt>request</tt> * only has it as a <tt>byte</tt> array and <tt>TransactionID</tt> is required for the * <tt>applicationData</tt> property value * @throws StunException if anything goes wrong while sending the specified <tt>Request</tt> to * the STUN server associated with this <tt>StunCandidateHarvest</tt> */ protected TransactionID sendRequest( Request request, boolean firstRequest, TransactionID transactionID) throws StunException { if (!firstRequest && (longTermCredentialSession != null)) longTermCredentialSession.addAttributes(request); StunStack stunStack = harvester.getStunStack(); TransportAddress stunServer = harvester.stunServer; TransportAddress hostCandidateTransportAddress = hostCandidate.getTransportAddress(); if (transactionID == null) { byte[] transactionIDAsBytes = request.getTransactionID(); transactionID = (transactionIDAsBytes == null) ? TransactionID.createNewTransactionID() : TransactionID.createTransactionID(harvester.getStunStack(), transactionIDAsBytes); } synchronized (requests) { try { transactionID = stunStack.sendRequest( request, stunServer, hostCandidateTransportAddress, this, transactionID); } catch (IllegalArgumentException iaex) { if (logger.isLoggable(Level.INFO)) { logger.log( Level.INFO, "Failed to send " + request + " through " + hostCandidateTransportAddress + " to " + stunServer, iaex); } throw new StunException(StunException.ILLEGAL_ARGUMENT, iaex.getMessage(), iaex); } catch (IOException ioex) { if (logger.isLoggable(Level.INFO)) { logger.log( Level.INFO, "Failed to send " + request + " through " + hostCandidateTransportAddress + " to " + stunServer, ioex); } throw new StunException(StunException.NETWORK_ERROR, ioex.getMessage(), ioex); } requests.put(transactionID, request); } return transactionID; }
public InstanceBlock[] intersects(Rectangle rectangle) { InstanceBlock[] ret = new InstanceBlock[4]; try { for (int x = 0; x < BWIDTH; x++) { for (int y = 0; y < BHEIGHT; y++) { Block block = blocks[x][y].getBlock(); Rectangle rect = blocks[x][y].getRect(); if (block.isCollidable()) { Rectangle up = new Rectangle(rectangle.getX(), rectangle.getY() - 2, rectangle.getWidth(), 1); Rectangle right = new Rectangle( rectangle.getX() + rectangle.getWidth() + 1, rectangle.getY(), 1, rectangle.getHeight()); Rectangle down = new Rectangle( rectangle.getX(), rectangle.getY() + rectangle.getHeight() + 1, rectangle.getWidth(), 1); Rectangle left = new Rectangle(rectangle.getX() - 2, rectangle.getY(), 1, rectangle.getHeight()); if (rect.intersects(up)) { ret[Player.UP] = blocks[x][y]; } if (rect.intersects(right)) { ret[Player.RIGHT] = blocks[x][y]; } if (rect.intersects(down)) { ret[Player.DOWN] = blocks[x][y]; } if (rect.intersects(left)) { ret[Player.LEFT] = blocks[x][y]; } } } } } catch (NullPointerException e) { logger.log("NullPointerException in World.intersects(Rectangle)", Level.DEBUG); logger.log("Stack:", Level.DEBUG); logger.log(e.getMessage(), Level.DEBUG); } return ret; }
/** Generate a local password and save it in the local-password file. */ public void postConstruct() { logger.fine("Generating local password"); SecureRandom random = new SecureRandom(); byte[] pwd = new byte[PASSWORD_BYTES]; random.nextBytes(pwd); password = toHex(pwd); File localPasswordFile = new File(env.getConfigDirPath(), LOCAL_PASSWORD_FILE); PrintWriter w = null; try { if (!localPasswordFile.exists()) { localPasswordFile.createNewFile(); /* * XXX - There's a security hole here. * Between the time the file is created and the permissions * are changed to prevent others from opening it, someone * else could open it and wait for the data to be written. * Java needs the ability to create a file that's readable * only by the owner; coming in JDK 7. */ localPasswordFile.setWritable(false, false); // take from all localPasswordFile.setWritable(true, true); // owner only localPasswordFile.setReadable(false, false); // take from all localPasswordFile.setReadable(true, true); // owner only } w = new PrintWriter(localPasswordFile); w.println(password); } catch (IOException ex) { // ignore errors logger.log(Level.FINE, "Exception writing local password file", ex); } finally { if (w != null) w.close(); } }
public void removeThread(WorkerThread thread) { threads.remove(thread); Logger.log(Level.DEBUG, Messages.getString("connection_closed", Settings.getLocale())); if (FancyFileServer.getGUI() != null) { FancyFileServer.getGUI().updateConnectionsCounter(); } }
/** * Creates a <tt>ServerReflexiveCandidate</tt> using {@link #hostCandidate} as its base and the * <tt>XOR-MAPPED-ADDRESS</tt> attribute in <tt>response</tt> for the actual * <tt>TransportAddress</tt> of the new candidate. If the message is malformed and/or does not * contain the corresponding attribute, this method simply has no effect. * * @param response the STUN <tt>Response</tt> which is supposed to contain the address we should * use for the new candidate */ protected void createServerReflexiveCandidate(Response response) { TransportAddress addr = getMappedAddress(response); if (addr != null) { ServerReflexiveCandidate srvrRflxCand = createServerReflexiveCandidate(addr); if (srvrRflxCand != null) { try { addCandidate(srvrRflxCand); } finally { // Free srvrRflxCand if it has not been consumed. if (!containsCandidate(srvrRflxCand)) { try { srvrRflxCand.free(); } catch (Exception ex) { if (logger.isLoggable(Level.FINE)) { logger.log( Level.FINE, "Failed to free" + " ServerReflexiveCandidate: " + srvrRflxCand, ex); } } } } } } }
/** * Obtain a new Node from a type that matches the given string. It will try to correctly detect * RealVar and constant nodes. The Node is cloned and initialized, so it can be used separatedly * * @param name The type of the requested Node. It must coincide with one of the class names of * available Nodes, unless it represents a variable or constant terminal * @param currentGlobalDepth The depth of the requested Node in the Tree */ public Node newNode(String name, int currentGlobalDepth) { System.out.println(name); Node outNode = null; if (name.startsWith("X")) { outNode = new RealVar(Integer.parseInt(name.substring("X".length(), name.length()))); } else if (name.startsWith("angle")) { outNode = new Angle(Integer.parseInt(name.substring("angle".length(), name.length()))); } else if (name.substring(0, 1).matches("\\d")) { outNode = new RealConstant(Double.parseDouble(name)); } else if (name.equals("true")) { outNode = new LogicConstant(1); } else if (name.equals("false")) { outNode = new LogicConstant(0); } else { List<Node> all = new ArrayList<Node>(); for (int i = 0; i < nodeSets.length; i++) { all.addAll(nodeSets[i].getAll()); } for (Node n : all) { if (name.equals(n.name())) { try { outNode = (Node) n.clone(); } catch (CloneNotSupportedException e) { Logger.log(e); } break; } } } outNode.setCurrentDepth(currentGlobalDepth); return outNode; }
/** * Reads a base class overrride from a resource file * * @param binaryClassName * @param fileName */ private void registerBaseClassOverride(String binaryClassName, String fileName) { try { Method mDefineClass = ClassLoader.class.getDeclaredMethod( "defineClass", String.class, byte[].class, int.class, int.class); mDefineClass.setAccessible(true); InputStream resourceInputStream = LiteLoader.class.getResourceAsStream("/classes/" + fileName + ".bin"); if (resourceInputStream != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (int readBytes = resourceInputStream.read(); readBytes >= 0; readBytes = resourceInputStream.read()) { outputStream.write(readBytes); } byte[] data = outputStream.toByteArray(); outputStream.close(); resourceInputStream.close(); logger.info("Defining class override for " + binaryClassName); mDefineClass.invoke( Minecraft.class.getClassLoader(), binaryClassName, data, 0, data.length); } else { logger.info("Error defining class override for " + binaryClassName + ", file not found"); } } catch (Throwable th) { logger.log(Level.WARNING, "Error defining class override for " + binaryClassName, th); } }
/** Initialise mod hooks */ private void initHooks() { try { // Chat hook if ((chatListeners.size() > 0 || chatFilters.size() > 0) && !chatHooked) { chatHooked = true; HookChat.Register(); HookChat.RegisterPacketHandler(this); } // Login hook if ((preLoginListeners.size() > 0 || loginListeners.size() > 0) && !loginHooked) { loginHooked = true; ModUtilities.registerPacketOverride(1, HookLogin.class); HookLogin.loader = this; } // Plugin channels hook if (pluginChannelListeners.size() > 0 && !pluginChannelHooked) { pluginChannelHooked = true; HookPluginChannels.Register(); HookPluginChannels.RegisterPacketHandler(this); } // Tick hook if (!tickHooked) { tickHooked = true; PrivateFields.minecraftProfiler.SetFinal(minecraft, new HookProfiler(this, logger)); } } catch (Exception ex) { logger.log(Level.WARNING, "Error creating hooks", ex); ex.printStackTrace(); } }
void _pickInitial() throws MongoException { if (_curAddress != null) return; // we need to just get a server to query for ismaster _pickCurrent(); try { _logger.info("current address beginning of _pickInitial: " + _curAddress); DBObject im = isMasterCmd(); if (_isMaster(im)) return; synchronized (_allHosts) { Collections.shuffle(_allHosts); for (ServerAddress a : _allHosts) { if (_curAddress == a) continue; _logger.info("remote [" + _curAddress + "] -> [" + a + "]"); _set(a); im = isMasterCmd(); if (_isMaster(im)) return; _logger.severe("switched to: " + a + " but isn't master"); } throw new MongoException("can't find master"); } } catch (Exception e) { _logger.log(Level.SEVERE, "can't pick initial master, using random one", e); } }
private void updateOutput() { try { setOutputStream(new FileOutputStream(filename, true)); } catch (IOException ex) { logger.log(Level.SEVERE, "Unable to open " + filename + " for writing", ex); } }
public void draw() { try { for (int x = 0; x < BWIDTH; x++) for (int y = 0; y < BHEIGHT; y++) { if (!(blocks[x][y].getBlock() == Block.air)) blocks[x][y].draw(); } if (player != null) { player.draw(); } } catch (NullPointerException e) { logger.log("NullPointerException in World.intersects(Rectangle)", Level.DEBUG); logger.log("Stack:", Level.DEBUG); logger.log(e.getMessage(), Level.DEBUG); } }
/** * Copies the properties of a specific <tt>DatagramPacket</tt> to another <tt>DatagramPacket</tt>. * The property values are not cloned. * * @param src the <tt>DatagramPacket</tt> which is to have its properties copied to <tt>dest</tt> * @param dest the <tt>DatagramPacket</tt> which is to have its properties set to the value of the * respective properties of <tt>src</tt> */ public static void copy(DatagramPacket src, DatagramPacket dest) { synchronized (dest) { dest.setAddress(src.getAddress()); dest.setPort(src.getPort()); byte[] srcData = src.getData(); if (srcData == null) dest.setLength(0); else { byte[] destData = dest.getData(); if (destData == null) dest.setLength(0); else { int destOffset = dest.getOffset(); int destLength = destData.length - destOffset; int srcLength = src.getLength(); if (destLength >= srcLength) destLength = srcLength; else if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, "Truncating received DatagramPacket data!"); } System.arraycopy(srcData, src.getOffset(), destData, destOffset, destLength); dest.setLength(destLength); } } } }
/** * Configures this instance to use the file identified as its backing. * * @param spec file path * @throws java.io.IOException if the file cannot be opened */ public void configure(String spec) throws IOException { fileName = spec; try { image = new RandomAccessFile(fileName, "rw"); readOnly = false; } catch (IOException e) { try { image = new RandomAccessFile(fileName, "r"); readOnly = true; LOGGING.log(Level.INFO, "opened {0} as read-only", fileName); } catch (IOException f) { LOGGING.log(Level.WARNING, "failed to open file", f); throw f; } } }
/** * Performs OCR operation. * * @param bi a buffered image * @param rect the bounding rectangle defines the region of the image to be recognized. A * rectangle of zero dimension or <code>null</code> indicates the whole image. * @return the recognized text * @throws TesseractException */ public String doOCR(BufferedImage bi, Rectangle rect) throws TesseractException { try { return doOCR(ImageIOHelper.getIIOImageList(bi), rect); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); throw new TesseractException(e); } }
/** * stores the data to a HTML file * * @param aFile file object */ private void storeToHtmlFile(final File aFile, final UARTDataSet aDataSet) { try { toHtmlPage(aFile, aDataSet); } catch (final IOException exception) { // Make sure to handle IO-interrupted exceptions properly! if (!HostUtils.handleInterruptedException(exception)) { LOG.log(Level.WARNING, "HTML export failed!", exception); } } }
/** Initialise the mods which were loaded */ private void initMods() { loadedModsList = ""; int loadedModsCount = 0; for (Iterator<LiteMod> iter = mods.iterator(); iter.hasNext(); ) { LiteMod mod = iter.next(); try { logger.info("Initialising mod " + mod.getName() + " version " + mod.getVersion()); mod.init(); if (mod instanceof Tickable) { addTickListener((Tickable) mod); } if (mod instanceof InitCompleteListener) { addInitListener((InitCompleteListener) mod); } if (mod instanceof RenderListener) { addRenderListener((RenderListener) mod); } if (mod instanceof ChatFilter) { addChatFilter((ChatFilter) mod); } if (mod instanceof ChatListener && !(mod instanceof ChatFilter)) { addChatListener((ChatListener) mod); } if (mod instanceof PreLoginListener) { addPreLoginListener((PreLoginListener) mod); } if (mod instanceof LoginListener) { addLoginListener((LoginListener) mod); } if (mod instanceof PluginChannelListener) { addPluginChannelListener((PluginChannelListener) mod); } loadedModsList += String.format("\n - %s version %s", mod.getName(), mod.getVersion()); loadedModsCount++; } catch (Throwable th) { logger.log(Level.WARNING, "Error initialising mod '" + mod.getName(), th); iter.remove(); } } loadedModsList = String.format("%s loaded mod(s)%s", loadedModsCount, loadedModsList); }
@Override public synchronized void flush() { if (rotate) { String newFilename = calculateFilename(); if (!filename.equals(newFilename)) { filename = newFilename; logger.log(Level.INFO, "Log rotating to {0}...", filename); updateOutput(); } } super.flush(); }
/** Verify and invoke main if present in the specified class. */ public static void invokeApplicationMain(Class mainClass, String[] args) throws InvocationTargetException, IllegalAccessException, ClassNotFoundException { String err = localStrings.getLocalString("utility.no.main", "", new Object[] {mainClass}); // determine the main method using reflection // verify that it is public static void and takes // String[] as the only argument Method mainMethod = null; try { mainMethod = mainClass.getMethod("main", new Class[] {String[].class}); } catch (NoSuchMethodException msme) { _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility", msme); throw new ClassNotFoundException(err); } // check modifiers: public static int modifiers = mainMethod.getModifiers(); if (!Modifier.isPublic(modifiers) || !Modifier.isStatic(modifiers)) { err = localStrings.getLocalString( "utility.main.notpublicorstatic", "The main method is either not public or not static"); _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notpublicorstatic"); throw new ClassNotFoundException(err); } // check return type and exceptions if (!mainMethod.getReturnType().equals(Void.TYPE)) { err = localStrings.getLocalString( "utility.main.notvoid", "The main method's return type is not void "); _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notvoid"); throw new ClassNotFoundException(err); } // build args to the main and call it Object params[] = new Object[1]; params[0] = args; mainMethod.invoke(null, params); }
private static StringBuffer getLocalConfig() { InputStream localConfigFileStream = null; try { // # Grab the file from our resources package. URL localConfigFile = Config.class.getResource("/net/smartsocket/resources/config.json"); localConfigFileStream = localConfigFile.openStream(); } catch (Exception e) { Logger.log( "Having a hard time locating internal config file. The program may not work properly.", Logger.CRITICAL); } return readFile(localConfigFileStream); }
@Override public void run() { byte[] buf = new byte[100]; try { int len; while ((len = in.read(buf)) > 0) { String output = new String(buf, 0, len); Thread t = Thread.currentThread(); System.out.println( "thread " + t.getName() + " " + t.getId() + ", read " + len + " bytes: " + output); } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to read", e); } finally { try { in.close(); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to close", e); } } }
protected void stopScheduler() { try { SchedulerFactory f = DefaultSchedulerFactory.getInstance(); Scheduler s = f.getScheduler(); s.stop(null, null); } catch (IOException ex) { // Log info: { String message = "Failure to stop scheduler!"; log.log(Level.SEVERE, message, ex); } throw new RuntimeException(ex); } catch (Throwable ex) { // Log info: { String message = "Failure to stop scheduler!"; log.log(Level.SEVERE, message, ex); } throw new RuntimeException(ex); } }
protected void stopTerminal() { try { TerminalFactory f = DefaultTerminalFactory.getInstance(); Terminal t = f.getTerminal(); t.stop(); } catch (IOException ex) { // Log info: { String message = "Failure to stop terminal!"; log.log(Level.SEVERE, message, ex); } throw new RuntimeException(ex); } catch (Throwable ex) { // Log info: { String message = "Failure to stop terminal!"; log.log(Level.SEVERE, message, ex); } throw new RuntimeException(ex); } }