code
stringlengths
73
34.1k
label
stringclasses
1 value
public String fixedCheckbox (String name, boolean value) { StringBuilder buf = new StringBuilder(); buf.append("<input type=\"checkbox\""); buf.append(" name=\"").append(name).append("\""); if (value) { buf.append(_useXHTML ? " checked=\"checked\"" : " checked"); ...
java
public String option ( String name, String value, String item, Object defaultValue) { String selectedValue = getValue(name, defaultValue); return fixedOption(name, value, item, selectedValue); }
java
public String fixedOption ( String name, String value, String item, Object selectedValue) { StringBuilder buf = new StringBuilder(); buf.append("<option value=\"").append(value).append("\""); if (selectedValue.equals(value)) { buf.append(" selected"); } bu...
java
public String textarea (String name, String extra, Object defaultValue) { return fixedTextarea(name, extra, getValue(name, defaultValue)); }
java
public String fixedTextarea (String name, String extra, Object value) { StringBuilder buf = new StringBuilder(); buf.append("<textarea name=\"").append(name).append("\""); if (!StringUtil.isBlank(extra)) { buf.append(" ").append(extra); } buf.append(">"); ...
java
protected String input (String type, String name, String extra, Object defaultValue) { return fixedInput(type, name, getValue(name, defaultValue), extra); }
java
protected String fixedInput ( String type, String name, Object value, String extra) { StringBuilder buf = new StringBuilder(); buf.append("<input type=\"").append(type).append("\""); buf.append(" name=\"").append(name).append("\""); buf.append(" value=\"").append(value).appen...
java
protected String getValue (String name, Object defaultValue) { String value = getParameter(name); if (StringUtil.isBlank(value)) { if (defaultValue == null) { value = ""; } else { value = String.valueOf(defaultValue); } } ...
java
public Site insertNewSite (String siteString) throws PersistenceException { if (_sitesByString.containsKey(siteString)) { return null; } // add it to the db Site site = new Site(); site.siteString = siteString; _repo.insertNewSite(site); ...
java
protected void checkReloadSites () { long now = System.currentTimeMillis(); boolean reload = false; synchronized (this) { reload = (now - _lastReload > RELOAD_INTERVAL); if (reload) { _lastReload = now; } } if (reload) { ...
java
public V setValue (V value) { V oldValue = _value; _value = value; return oldValue; }
java
@ReplacedBy("com.google.common.collect.Ordering.natural().nullsLast()") public static final <T extends Comparable<?>> Comparator<T> comparable () { @SuppressWarnings("unchecked") Comparator<T> comp = (Comparator<T>)COMPARABLE; return comp; }
java
protected boolean checkedApply (ObserverOp<T> obop, T obs) { try { return obop.apply(obs); } catch (Throwable thrown) { log.warning("ObserverOp choked during notification", "op", obop, "obs", observerForLog(obs), thrown); // if they booched it,...
java
public Object get (int key) { int size = _keys.length, start = key % size; for (int ii = 0; ii < size; ii++) { int idx = (ii + start) % size; if (_keys[idx] == key) { return _values[idx]; } } return null; }
java
public Object remove (int key) { int size = _keys.length, start = key % size; for (int ii = 0; ii < size; ii++) { int idx = (ii + start) % size; if (_keys[idx] == key) { Object value = _values[idx]; _keys[idx] = -1; _values[idx]...
java
public int size () { int size = 0; for (int ii = 0, ll = _keys.length; ii < ll; ii++) { if (_keys[ii] != -1) { size++; } } return size; }
java
public static Iterable<String> getParameterNames (HttpServletRequest req) { List<String> params = new ArrayList<String>(); Enumeration<?> iter = req.getParameterNames(); while (iter.hasMoreElements()) { params.add((String)iter.nextElement()); } return params; ...
java
public static float requireFloatParameter ( HttpServletRequest req, String name, String invalidDataMessage) throws DataValidationException { return parseFloatParameter(getParameter(req, name, false), invalidDataMessage); }
java
public static IntSet getIntParameters ( HttpServletRequest req, String name, String invalidDataMessage) throws DataValidationException { IntSet ints = new ArrayIntSet(); String[] values = req.getParameterValues(name); if (values != null) { for (int ii = 0; ii < va...
java
public static Set<String> getParameters (HttpServletRequest req, String name) { Set<String> set = new HashSet<String>(); String[] values = req.getParameterValues(name); if (values != null) { for (int ii = 0; ii < values.length; ii++) { if (!StringUtil.isBlank(valu...
java
public static String requireParameter ( HttpServletRequest req, String name, String missingDataMessage) throws DataValidationException { String value = getParameter(req, name, true); if (StringUtil.isBlank(value)) { throw new DataValidationException(missingDataMessage); ...
java
public static String requireParameter ( HttpServletRequest req, String name, String missingDataMessage, int maxLength) throws DataValidationException { return StringUtil.truncate( requireParameter(req, name, missingDataMessage), maxLength); }
java
public static boolean parameterEquals (HttpServletRequest req, String name, String value) { return value.equals(getParameter(req, name, false)); }
java
protected static int parseIntParameter (String value, String invalidDataMessage) throws DataValidationException { try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { throw new DataValidationException(invalidDataMessage); } }
java
protected static long parseLongParameter (String value, String invalidDataMessage) throws DataValidationException { try { return Long.parseLong(value); } catch (NumberFormatException nfe) { throw new DataValidationException(invalidDataMessage); } }
java
protected static float parseFloatParameter (String value, String invalidDataMessage) throws DataValidationException { try { return Float.parseFloat(value); } catch (NumberFormatException nfe) { throw new DataValidationException(invalidDataMessage); } }
java
protected static Date parseDateParameter (String value, String invalidDataMessage) throws DataValidationException { try { synchronized (_dparser) { return _dparser.parse(value); } } catch (ParseException pe) { throw new DataValidationExcept...
java
public static <T> T pickRandom (T[] values) { return (values == null || values.length == 0) ? null : values[getInt(values.length)]; }
java
public static <T> T pickRandom (List<T> values) { int size = values.size(); if (size == 0) { throw new IllegalArgumentException( "Must have at least one element [size=" + size + "]"); } return values.get(getInt(size)); }
java
public void requestCompleted (final T result) { apply(new ObserverOp<ResultListener<T>>() { public boolean apply (ResultListener<T> observer) { observer.requestCompleted(result); return true; } }); }
java
public void requestFailed (final Exception cause) { apply(new ObserverOp<ResultListener<T>>() { public boolean apply (ResultListener<T> observer) { observer.requestFailed(cause); return true; } }); }
java
public static String filterColors (String txt) { if (txt == null) return null; return COLOR_PATTERN.matcher(txt).replaceAll(""); }
java
public static String escapeColors (String txt) { if (txt == null) return null; return COLOR_PATTERN.matcher(txt).replaceAll("#''$1"); }
java
private static String unescapeColors (String txt, boolean restore) { if (txt == null) return null; String prefix = restore ? "#" : "%"; return ESCAPED_PATTERN.matcher(txt).replaceAll(prefix + "$1"); }
java
public boolean setText (String text) { // the Java text stuff freaks out in a variety of ways if it is asked to deal with the // empty string, so we fake blank labels by just using a space if (StringUtil.isBlank(text)) { text = " "; } // if there is no change the...
java
public void setTargetWidth (int targetWidth) { if (targetWidth <= 0) { throw new IllegalArgumentException( "Invalid target width '" + targetWidth + "'"); } _constraints.width = targetWidth; _constraints.height = 0; invalidate("setTargetWidth"); ...
java
public void setTargetHeight (int targetHeight) { if (targetHeight <= 0) { throw new IllegalArgumentException( "Invalid target height '" + targetHeight + "'"); } _constraints.width = 0; _constraints.height = targetHeight; invalidate("setTargetHeight...
java
protected AttributedCharacterIterator textIterator (Graphics2D gfx) { // first set up any attributes that apply to the entire text Font font = (_font == null) ? gfx.getFont() : _font; HashMap<TextAttribute,Object> map = new HashMap<TextAttribute,Object>(); map.put(TextAttribute.FONT,...
java
protected void addAttributes (AttributedString text) { // add any color attributes for specific segments if (_rawText != null) { Matcher m = COLOR_PATTERN.matcher(_rawText); int startSeg = 0, endSeg = 0; Color lastColor = null; while (m.find()) { ...
java
protected Rectangle2D getBounds (TextLayout layout) { if (RunAnywhere.isMacOS()) { return layout.getOutline(null).getBounds(); } else { return layout.getBounds(); } }
java
static void overwrite(StringBuffer sb, int pos, String s) { int len = s.length(); for (int i = 0; i < len; i++) { sb.setCharAt(pos + i, s.charAt(i)); } }
java
public static void parse (DefaultHandler handler, InputStream in) throws IOException, ParserConfigurationException, SAXException { XMLReader xr = _pfactory.newSAXParser().getXMLReader(); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(in...
java
public LogBuilder append (Object... args) { if (args != null && args.length > 1) { for (int ii = 0, nn = args.length - (args.length % 2); ii < nn; ii += 2) { if (_hasArgs) { _log.append(", "); } else { if (_log.length() > 0)...
java
protected void openLog (boolean freakout) { try { // create our file writer to which we'll log FileOutputStream fout = new FileOutputStream(_logPath, true); OutputStreamWriter writer = new OutputStreamWriter(fout, "UTF8"); _logWriter = new PrintWriter(new Buff...
java
protected synchronized void checkRollOver () { // check to see if we should roll over the log String newDayStamp = _dayFormat.format(new Date()); // hey! we need to roll it over! if (!newDayStamp.equals(_dayStamp)) { log("log_closed"); _logWriter.close(); ...
java
protected void scheduleNextRolloverCheck () { Calendar cal = Calendar.getInstance(); // schedule the next check for the next hour mark long nextCheck = (1000L - cal.get(Calendar.MILLISECOND)) + (59L - cal.get(Calendar.SECOND)) * 1000L + (59L - cal.get(Calendar.MINUTE...
java
@Override public void init (ExtendedProperties config) { // the web framework was kind enough to slip this into the runtime when it started up _sctx = (ServletContext)rsvc.getApplicationAttribute("ServletContext"); if (_sctx == null) { rsvc.getLog().warn("ServletContextResour...
java
public <V> FailureListener<V> retype (Class<V> klass) { @SuppressWarnings("unchecked") FailureListener<V> casted = (FailureListener<V>)this; return casted; }
java
public void transition (Class<?> clazz, String name, Transition trans) throws PersistenceException { if (!isTransitionApplied(clazz, name) && noteTransition(clazz, name)) { try { trans.run(); } catch (PersistenceException e) { try { ...
java
public boolean isTransitionApplied (Class<?> clazz, final String name) throws PersistenceException { final String cname = clazz.getName(); return execute(new Operation<Boolean>() { public Boolean invoke (Connection conn, DatabaseLiaison liaison) throws SQLExceptio...
java
public boolean noteTransition (Class<?> clazz, final String name) throws PersistenceException { final String cname = clazz.getName(); return executeUpdate(new Operation<Boolean>() { public Boolean invoke (Connection conn, DatabaseLiaison liaison) throws SQLExcepti...
java
public void clearTransition (Class<?> clazz, final String name) throws PersistenceException { final String cname = clazz.getName(); executeUpdate(new Operation<Void>() { public Void invoke (Connection conn, DatabaseLiaison liaison) throws SQLException, Persistence...
java
protected void registerColumnType(String columnType, int jdbcType) { columnTypeMatchers.add(new ColumnTypeMatcher(columnType)); jdbcTypes.put(columnType, jdbcType); }
java
public void setLabel (String label) { _label.setText(label); _label.setVisible(!StringUtil.isBlank(label)); }
java
public void setValue (int value) { _slider.setValue(value); _value.setText(Integer.toString(value)); }
java
public String penniesToDollars (int pennies) { float decimal = pennies / 100f; // if the pennies is a whole number of dollars, then we return just the string number if (pennies % 100 == 0) { return String.format("%.0f", decimal); } // otherwise we always return tw...
java
public String quote (Date date) { return (date == null) ? null : escape(String.valueOf(date)); }
java
public static String jigger (String text) { if (text == null) { return null; } try { return new String(text.getBytes("UTF8"), "8859_1"); } catch (UnsupportedEncodingException uee) { log.warning("Jigger failed", uee); return text; ...
java
public static boolean createTableIfMissing ( Connection conn, String table, String[] definition, String postamble) throws SQLException { if (tableExists(conn, table)) { return false; } Statement stmt = conn.createStatement(); try { stmt.execut...
java
public static String getIndexName (Connection conn, String table, String column) throws SQLException { ResultSet rs = conn.getMetaData().getIndexInfo("", "", table, false, true); while (rs.next()) { String tname = rs.getString("TABLE_NAME");...
java
public static boolean isColumnNullable (Connection conn, String table, String column) throws SQLException { ResultSet rs = getColumnMetaData(conn, table, column); try { return rs.getString("IS_NULLABLE").equals("YES"); } finally...
java
public static String getColumnDefaultValue (Connection conn, String table, String column) throws SQLException { ResultSet rs = getColumnMetaData(conn, table, column); try { return rs.getString("COLUMN_DEF"); } finally { rs.close(); } }
java
public static boolean dropIndex (Connection conn, String table, String cname, String iname) throws SQLException { if (!tableContainsIndex(conn, table, cname, iname)) { return false; } String update = "ALTER TABLE " + table + " DROP INDEX " + iname; PreparedStatem...
java
public static void dropPrimaryKey (Connection conn, String table) throws SQLException { String update = "ALTER TABLE " + table + " DROP PRIMARY KEY"; PreparedStatement stmt = null; try { stmt = conn.prepareStatement(update); if (stmt.executeUpdate() == 1) { ...
java
public static String genAuthCode (User user) { // concatenate a bunch of secret stuff together StringBuilder buf = new StringBuilder(); buf.append(user.password); buf.append(System.currentTimeMillis()); buf.append(Math.random()); // and MD5 hash it return Str...
java
public static String legacyEncrypt (String username, String password, boolean ignoreUserCase) { if (ignoreUserCase) { username = username.toLowerCase(); } return Crypt.crypt(StringUtil.truncate(username, 2), password); }
java
public static <A, B, C> Triple<A, B, C> newTriple (A a, B b, C c) { return new Triple<A, B, C>(a, b, c); }
java
protected void paintBackground (Graphics g) { // simply fill our background color g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); }
java
protected void paintBox (Graphics g, Rectangle box) { // just draw the box in our foreground color g.setColor(getForeground()); g.drawRect(box.x, box.y, box.width, box.height); }
java
protected void updateBox () { int hmin = _horz.getMinimum(); int vmin = _vert.getMinimum(); _hFactor = (_active.width) / (float) (_horz.getMaximum() - hmin); _vFactor = (_active.height) / (float) (_vert.getMaximum() - vmin); _box.x = _active.x + Math.round((_horz.getValue() ...
java
public int[] toIntArray (int[] target, int offset) { System.arraycopy(_values, 0, target, offset, _size); return target; }
java
public short[] toShortArray () { short[] values = new short[_size]; for (int ii = 0; ii < _size; ii++) { values[ii] = (short)_values[ii]; } return values; }
java
public Interator interator () { return new AbstractInterator() { public boolean hasNext () { return (_pos < _size); } public int nextInt () { if (_pos >= _size) { throw new NoSuchElementException(); } ...
java
protected void removeDuplicates () { if (_size > 1) { int last = _values[0]; for (int ii = 1; ii < _size; ) { if (_values[ii] == last) { // shift everything down 1 _size--; System.arraycopy(_values, ii + 1, _values, ii, _size - ...
java
public void add (Object value) { _list[_lastPos++ % _list.length] = value; // keep last pos cycling from keepCount to 2*keepCount-1 if (_lastPos == 2*_list.length) { _lastPos = _list.length; } }
java
public static String getMessage (Throwable ex) { String msg = DEFAULT_ERROR_MSG; for (int i = 0; i < _keys.size(); i++) { Class<?> cl = _keys.get(i); if (cl.isInstance(ex)) { msg = _values.get(i); break; } } return m...
java
public static void close (Reader in) { if (in != null) { try { in.close(); } catch (IOException ioe) { log.warning("Error closing reader", "reader", in, "cause", ioe); } } }
java
public static void close (Writer out) { if (out != null) { try { out.close(); } catch (IOException ioe) { log.warning("Error closing writer", "writer", out, "cause", ioe); } } }
java
protected void newPage() { if (!bean.isSubreport()) { try { stream.print("</table>\n"); stream.println("<p style=\"page-break-before: always\"></p>\n"); if (bean.getReportLayout().isUseSize()) { stream.print("<table>"); } else { stream.print("<table style='width:10...
java
public boolean checkCall (String warning) { if (_firstCall == null) { _firstCall = new Exception( "---- First call (at " + _format.format(new Date()) + ") ----"); return false; } log.warning(warning, new Exception()); log.warning("First call:"...
java
protected Properties loadConfiguration (ServletConfig config) throws IOException { Properties props = loadVelocityProps(config); // if we failed to create our application for whatever reason; bail if (_app == null) { return props; } // let the applicatio...
java
@SuppressWarnings("rawtypes") // our super class declares a bare Class public Object methodException (Class clazz, String method, Exception e) throws Exception { log.warning("Exception", "class", clazz.getName(), "method", method, e); return ""; }
java
protected Template selectTemplate (int siteId, InvocationContext ctx) throws ResourceNotFoundException, ParseErrorException, Exception { String path = ctx.getRequest().getServletPath(); if (_usingSiteLoading) { // if we're using site resource loading, we need to prefix the path w...
java
protected void mergeTemplate (Template template, InvocationContext context) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, UnsupportedEncodingException, IOException, Exception { HttpServletResponse response = context.getResponse(); ServletOut...
java
protected Logic resolveLogic (String path) { // look for a cached logic instance String lclass = _app.generateClass(path); Logic logic = _logic.get(lclass); if (logic == null) { logic = instantiateLogic(path, lclass); // if something failed, use a dummy in i...
java
protected Logic instantiateLogic (String path, String lclass) { try { Class<?> pcl = Class.forName(lclass); return (Logic)pcl.newInstance(); } catch (ClassNotFoundException cnfe) { // nothing interesting to report } catch (Throwable t) { log.warnin...
java
public void addTask (ExecutorTask task) { for (int ii=0, nn=_queue.size(); ii < nn; ii++) { ExecutorTask taskOnQueue = _queue.get(ii); if (taskOnQueue.merge(task)) { return; } } // otherwise, add it on _queue.add(task); //...
java
protected void checkNext () { _executingNow = !_queue.isEmpty(); if (_executingNow) { // start up a thread to execute the task in question ExecutorTask task = _queue.remove(0); final ExecutorThread thread = new ExecutorThread(task); thread.start(); ...
java
public static String[] getMACAddresses () { String [] cmds; if (RunAnywhere.isWindows()) { cmds = WINDOWS_CMDS; } else { cmds = UNIX_CMDS; } return parseMACs(tryCommands(cmds)); }
java
protected static String[] parseMACs (String text) { if (text == null) { return new String[0]; } Matcher m = MACRegex.matcher(text); ArrayList<String> list = new ArrayList<String>(); while (m.find()) { String mac = m.group(1).toUpperCase(); ...
java
protected static String tryCommands (String[] cmds) { if (cmds == null) { return null; } String output; for (int ii = 0; ii < cmds.length; ii++) { output = runCommand(cmds[ii]); if (output != null) { return output; } ...
java
protected static String runCommand (String cmd) { try { Process p = Runtime.getRuntime().exec(cmd); BufferedReader cin = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuilder buffer= new StringBuilder(); String line = ""; wh...
java
public static void copyRow(XSSFSheet srcSheet, XSSFSheet destSheet, int parentSheetRow, int parentSheetColumn, XSSFRow srcRow, XSSFRow destRow, Map<Integer, CellStyle> styleMap) { // manage a list of merged zone in order to not insert two times a // merged zone Set<CellRangeAddressWrapper> mergedRegions = new ...
java
public static void copyCell(XSSFCell oldCell, XSSFCell newCell, Map<Integer, CellStyle> styleMap) { if (styleMap != null) { if (oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()) { newCell.setCellStyle(oldCell.getCellStyle()); } else { int stHashCode = oldCell.getCellStyle().ha...
java
public String connect (String hostname, int port) throws IOException, CDDBException { return connect(hostname, port, CLIENT_NAME, CLIENT_VERSION); }
java
public String connect (String hostname, int port, String clientName, String clientVersion) throws IOException, CDDBException { // obtain the necessary information we'll need to identify // ourselves to the CDDB server String localhost = InetAddress.getLocalHost().getHostName(); ...
java
public String[] lscat() throws IOException, CDDBException { // sanity check if (_sock == null) { throw new CDDBException(500, "Not connected"); } // make the request Response rsp = request("cddb lscat"); // anything other than an OK response earn...
java
public Entry[] query (String discid, int[] frameOffsets, int length) throws IOException, CDDBException { // sanity check if (_sock == null) { throw new CDDBException(500, "Not connected"); } // construct the query parameter StringBuilder req = new StringB...
java
protected final void append ( ArrayList<String> list, int index, String value) { // expand the list as necessary while (list.size() <= index) { list.add(""); } list.set(index, list.get(index) + value); }
java
protected Response request (String req) throws IOException { System.err.println("REQ:" + req); // send the request to the server _out.println(req); _out.flush(); // now read the response String rspstr = _in.readLine(); // if they closed the connectio...
java