code
stringlengths
73
34.1k
label
stringclasses
1 value
protected void fireActionPerformed () { // guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // process the listeners last to first, notifying those that are // interested in this event for (int i = listeners.length-2; i >= 0; i -= 2) ...
java
protected void addButtons (int start, int count) { Object selobj = _model.getSelectedItem(); for (int i = start; i < count; i++) { Object elem = _model.getElementAt(i); if (selobj == elem) { _selectedIndex = i; } JLabel ibut = null; ...
java
protected void removeButtons (int start, int count) { while (count-- > 0) { remove(start); } // adjust the selected index if (_selectedIndex >= start) { if (start + count > _selectedIndex) { _selectedIndex = -1; } else { ...
java
protected void updateSelection (int selidx) { // do nothing if this element is already selected if (selidx == _selectedIndex) { return; } // unhighlight the old component if (_selectedIndex != -1) { JLabel but = (JLabel)getComponent(_selectedIndex); ...
java
protected void layout (Graphics2D gfx, int iconPadding, int extraPadding) { // if we have an icon, let that dictate our size; otherwise just lay out our label all on // one line int sqwid, sqhei; if (_icon == null) { sqwid = sqhei = 0; } else { sqwid =...
java
protected void paint (Graphics2D gfx, int x, int y, Color background, Object cliData) { // turn on anti-aliasing (for our sausage lines) Object oalias = SwingUtil.activateAntiAliasing(gfx); // draw the base sausage gfx.setColor(background); drawBase(gfx, x, y); // r...
java
protected void drawBase (Graphics2D gfx, int x, int y) { gfx.fillRoundRect( x, y, _size.width - 1, _size.height - 1, _dia, _dia); }
java
protected void drawIcon (Graphics2D gfx, int x, int y, Object cliData) { if (_icon != null) { _icon.paintIcon(null, gfx, x + _xoff, y + _yoff); } }
java
protected void drawLabel (Graphics2D gfx, int x, int y) { _label.render(gfx, x + _lxoff, y + _lyoff); }
java
protected void drawBorder (Graphics2D gfx, int x, int y) { // draw the black outer border gfx.setColor(Color.black); gfx.drawRoundRect(x, y, _size.width - 1, _size.height - 1, _dia, _dia); }
java
public static String getFullColumnClassName(String className) { if (className.startsWith("java.")) { return className; } if ("String".equals(className)) { return "java.lang.String"; } else if ("Int".equals(className)) { return "java.lang.Integer"; } else if ("Double".equals(className)) { ...
java
public static void centerWindow (Window window) { Rectangle bounds; try { bounds = GraphicsEnvironment.getLocalGraphicsEnvironment(). getDefaultScreenDevice().getDefaultConfiguration().getBounds(); } catch (Throwable t) { Toolkit tk = window.getToolkit...
java
public static void drawStringCentered ( Graphics g, String str, int x, int y, int width, int height) { FontMetrics fm = g.getFontMetrics(g.getFont()); int xpos = x + ((width - fm.stringWidth(str)) / 2); int ypos = y + ((height + fm.getAscent()) / 2); g.drawString(str, xpos, y...
java
public static Point fitRectInRect (Rectangle rect, Rectangle bounds) { // Guarantee that the right and bottom edges will be contained and do our best for the top // and left edges. return new Point(Math.min(bounds.x + bounds.width - rect.width, Math.max(rect...
java
public static boolean positionRect ( Rectangle r, Rectangle bounds, Collection<? extends Shape> avoidShapes) { Point origPos = r.getLocation(); Comparator<Point> comp = createPointComparator(origPos); SortableArrayList<Point> possibles = new SortableArrayList<Point>(); // sta...
java
public static <P extends Point2D> Comparator<P> createPointComparator (final P origin) { return new Comparator<P>() { public int compare (P p1, P p2) { double dist1 = origin.distance(p1); double dist2 = origin.distance(p2); return (dist...
java
public static void applyToHierarchy (Component comp, ComponentOp op) { applyToHierarchy(comp, Integer.MAX_VALUE, op); }
java
public static void applyToHierarchy (Component comp, int depth, ComponentOp op) { if (comp == null) { return; } op.apply(comp); if (comp instanceof Container && --depth >= 0) { Container c = (Container) comp; int ccount = c.getComponentCount(); ...
java
public static Object activateAntiAliasing (Graphics2D gfx) { RenderingHints ohints = gfx.getRenderingHints(), nhints = new RenderingHints(null); nhints.add(ohints); nhints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); nhints.put(RenderingHints.KEY_TEXT_ANTI...
java
public static void restoreAntiAliasing (Graphics2D gfx, Object rock) { if (rock != null) { gfx.setRenderingHints((RenderingHints)rock); } }
java
public static void sizeToContents (JTable table) { TableModel model = table.getModel(); TableColumn column = null; Component comp = null; int ccount = table.getColumnModel().getColumnCount(), rcount = model.getRowCount(), cellHeight = 0; for (int cc = 0; cc < cco...
java
public static Cursor createImageCursor (Image img, Point hotspot) { Toolkit tk = Toolkit.getDefaultToolkit(); // for now, just report the cursor restrictions, then blindly create int w = img.getWidth(null); int h = img.getHeight(null); Dimension d = tk.getBestCursorSize(w, h...
java
public static void addDebugBorders (JPanel panel) { Color bcolor = new Color(_rando.nextInt(256), _rando.nextInt(256), _rando.nextInt(256)); panel.setBorder(BorderFactory.createLineBorder(bcolor)); for (int ii = 0; ii < panel.getComponentCount(); ii++) { Object child = panel.get...
java
public static void setFrameIcons (Frame frame, List<? extends Image> icons) { try { Method m = frame.getClass().getMethod("setIconImages", List.class); m.invoke(frame, icons); return; } catch (SecurityException e) { // Fine, fine, no reflection for us ...
java
public static JComponent createAdjustEditor () { VGroupLayout layout = new VGroupLayout( VGroupLayout.NONE, VGroupLayout.STRETCH, 3, VGroupLayout.TOP); layout.setOffAxisJustification(VGroupLayout.LEFT); JTabbedPane editor = new EditorPane(); Font font = edito...
java
public Object get (Object array, int index) { return (array == null) ? null : Array.get(array, index); }
java
public static String httpPost ( final URL url, final String submission, int timeout, final Map<String, String> requestProps) throws IOException, ServiceWaiter.TimeoutException { final ServiceWaiter<String> waiter = new ServiceWaiter<String>( (timeout < 0) ? ServiceWaiter.NO_TIMEO...
java
protected String[] inferCaller () { String self = getClass().getName(); // locate ourselves in the call stack StackTraceElement[] stack = (new Throwable()).getStackTrace(); int ii = 0; for (; ii < stack.length; ii++) { if (self.equals(stack[ii].getClassName())) {...
java
@Override public boolean isSourceModified (Resource resource) { SiteKey skey = new SiteKey(resource.getName()); // if the resource is for the default site, it is never considered to // be modified if (skey.siteId == SiteIdentifier.DEFAULT_SITE_ID) { return false; ...
java
public Series setType(SeriesType type) { if(type != null) { this.type = type.name().toLowerCase(); } else { this.type = null; } return this; }
java
private void populateDependentParameters(Report nextReport, QueryParameter parameter) { Map<String, QueryParameter> childParams = ParameterUtil.getChildDependentParameters(nextReport, parameter); // update model parameter values for every child parameter for (QueryParameter childParam : childPa...
java
public static boolean equalsText(String s1, String s2) { if (s1 == null) { if (s2 != null) { return false; } } else { if (s2 == null) { return false; } } if ((s1 != null) && (s2 != null)) { s1 = s1.replaceAll("\\s", "").toLowerCase(); s2 = s2.replaceAll("\\s", "").toLowerCase(); if ...
java
private static boolean isImage(String hexString) { boolean isImage = false; //png if (hexString.startsWith("89504e470d0a1a0a")) { isImage = true; //gif } else if (hexString.startsWith("474946383761") || hexString.startsWith("474946383961")) { isImage = true; // jpe...
java
public void layout (Graphics2D gfx, Font font) { _label.setFont(font); layout(gfx, BORDER_THICKNESS); openBounds.width = _size.width; openBounds.height = _size.height; // and closed up, we're just a circle closedBounds.height = closedBounds.width = _size.height; ...
java
@Override protected void drawBase (Graphics2D gfx, int x, int y) { if (_active) { // render the sausage super.drawBase(gfx, x, y); } else { // render the circle gfx.fillOval(x, y, closedBounds.width - 1, closedBounds.height - 1); } }
java
protected void paint (Graphics2D gfx, int x, int y, RadialMenu menu) { paint(gfx, x, y, UIManager.getColor("RadialLabelSausage.background"), menu); }
java
public static int nextPowerOfTwo (int value) { return (int)Math.pow(2, Math.ceil(Math.log(value) / Math.log(2))); }
java
public static Object[] add (Object[] list, int startIdx, Object element) { requireNotNull(element); // make sure we've got a list to work with if (list == null) { list = new Object[DEFAULT_LIST_SIZE]; } // search for a spot to insert yon element; assuming we'll ...
java
public static Object[] insert (Object[] list, int index, Object element) { requireNotNull(element); // make sure we've got a list to work with if (list == null) { list = new Object[DEFAULT_LIST_SIZE]; } // make a note of the size of the array int size = ...
java
public static int indexOfNull (Object[] list) { if (list != null) { for (int ii=0, nn = list.length; ii < nn; ii++) { if (list[ii] == null) { return ii; } } } return -1; }
java
public static Object remove (Object[] list, int index) { if (list == null) { return null; } int llength = list.length; if (llength <= index || index < 0) { return null; } Object elem = list[index]; System.arraycopy(list, index+1, list...
java
@Deprecated public static int size (Object[] list) { if (list == null) { return 0; } int llength = list.length; for (int ii = 0; ii < llength; ii++) { if (list[ii] == null) { return ii; } } return llength; }
java
public static int getSize (Object[] list) { int size = 0; for (int ii = 0, nn = (list == null) ? 0 : list.length; ii < nn; ii++) { if (list[ii] != null) { size++; } } return size; }
java
public static void main (String[] args) { Object[] list = null; String foo = "foo"; String bar = "bar"; list = ListUtil.add(list, foo); System.out.println("add(foo): " + StringUtil.toString(list)); list = ListUtil.add(list, bar); System.out.println("add(bar)...
java
public int getOrElse (int key, int defval) { Record rec = locateRecord(key); return (rec == null) ? defval : rec.value; }
java
public int removeOrElse (int key, int defval) { _modCount++; int removed = removeImpl(key, defval); checkShrink(); return removed; }
java
public void clear () { _modCount++; // abandon all of our hash chains (the joy of garbage collection) for (int i = 0; i < _buckets.length; i++) { _buckets[i] = null; } // zero out our size _size = 0; }
java
public void ensureCapacity (int minCapacity) { int size = _buckets.length; while (minCapacity > (int) (size * _loadFactor)) { size *= 2; } if (size != _buckets.length) { resizeBuckets(size); } }
java
protected Record locateRecord (int key) { int index = Math.abs(key)%_buckets.length; for (Record rec = _buckets[index]; rec != null; rec = rec.next) { if (rec.key == key) { return rec; } } return null; }
java
protected int removeImpl (int key, int defval) { int index = Math.abs(key)%_buckets.length; Record prev = null; // go through the chain looking for a match for (Record rec = _buckets[index]; rec != null; rec = rec.next) { if (rec.key == key) { if (prev ==...
java
protected void checkShrink () { if ((_buckets.length > DEFAULT_BUCKETS) && (_size < (int) (_buckets.length * _loadFactor * .125))) { resizeBuckets(Math.max(DEFAULT_BUCKETS, _buckets.length >> 1)); } }
java
public Set<IntIntEntry> entrySet () { return new AbstractSet<IntIntEntry>() { @Override public int size () { return _size; } @Override public Iterator<IntIntEntry> iterator() { return new IntEntryIterator(); } }; }
java
public void addComponent (BaseComponent comp) { if (comp instanceof InitComponent) { if (_initers == null) { throw new IllegalStateException("Too late to register InitComponent."); } _initers.add((InitComponent)comp); } if (comp instanceof ...
java
public void removeComponent (BaseComponent comp) { if (_initers != null && comp instanceof InitComponent) { _initers.remove((InitComponent)comp); } if (_downers != null && comp instanceof ShutdownComponent) { _downers.remove((ShutdownComponent)comp); } }
java
public void addInitConstraint (InitComponent lhs, Constraint constraint, InitComponent rhs) { if (lhs == null || rhs == null) { throw new IllegalArgumentException("Cannot add constraint about null component."); } InitComponent before = (constraint == Constraint.RUNS_BEFORE) ? lhs...
java
public void addShutdownConstraint (ShutdownComponent lhs, Constraint constraint, ShutdownComponent rhs) { if (lhs == null || rhs == null) { throw new IllegalArgumentException("Cannot add constraint about null component."); } ShutdownComponen...
java
public void init () { if (_initers == null) { log.warning("Refusing repeat init() request."); return; } ObserverList<InitComponent> list = _initers.toObserverList(); _initers = null; list.apply(new ObserverList.ObserverOp<InitComponent>() { ...
java
public void shutdown () { if (_downers == null) { log.warning("Refusing repeat shutdown() request."); return; } ObserverList<ShutdownComponent> list = _downers.toObserverList(); _downers = null; list.apply(new ObserverList.ObserverOp<ShutdownComponent...
java
protected Record<V> getImpl (int key) { for (Record<V> rec = _buckets[keyToIndex(key)]; rec != null; rec = rec.next) { if (rec.key == key) { return rec; } } return null; }
java
protected Record<V> removeImpl (int key, boolean checkShrink) { int index = keyToIndex(key); // go through the chain looking for a match for (Record<V> prev = null, rec = _buckets[index]; rec != null; rec = rec.next) { if (rec.key == key) { if (prev == null) { ...
java
protected final int keyToIndex (int key) { // we lift the hash-fixing function from HashMap because Sun // wasn't kind enough to make it public key += ~(key << 9); key ^= (key >>> 14); key += (key << 4); key ^= (key >>> 10); return key & (_buckets.length - ...
java
public IntSet intKeySet () { // damn Sun bastards made the 'keySet' variable with default access, so we can't share it if (_keySet == null) { _keySet = new AbstractIntSet() { public Interator interator () { return new AbstractInterator () { ...
java
public static String rehostLocation ( HttpServletRequest req, String servername) { StringBuffer buf = req.getRequestURL(); String csname = req.getServerName(); int csidx = buf.indexOf(csname); if (csidx != -1) { buf.delete(csidx, csidx + csname.length()); ...
java
public static String getServletURL (HttpServletRequest req, String path) { StringBuffer buf = req.getRequestURL(); String sname = req.getServletPath(); buf.delete(buf.length() - sname.length(), buf.length()); if (!path.startsWith("/")) { buf.append("/"); } ...
java
public void insertDatum (Object element, int row) { _data.add(row, element); _model.fireTableRowsInserted(row, row); }
java
public void updateDatum (Object element, int row) { _data.set(row, element); _model.fireTableRowsUpdated(row, row); }
java
public void removeDatum (Object element) { int dex = _data.indexOf(element); if (dex != -1) { removeDatum(dex); } }
java
public String getErrorMessage () { String msg = getMessage(); return String.valueOf(_errorCode).equals(msg) ? null : msg; }
java
public static String[] getCanonicalPathElements (File file) throws IOException { file = file.getCanonicalFile(); // If we were a file, get its parent if (!file.isDirectory()) { file = file.getParentFile(); } return file.getPath().split(File.separator); ...
java
public static String computeRelativePath (File file, File relativeTo) throws IOException { String[] realDirs = getCanonicalPathElements(file); String[] relativeToDirs = getCanonicalPathElements(relativeTo); // Eliminate the common root int common = 0; for (; common <...
java
public static int getRunPriority() { String s = System.getProperty(RUN_PRIORITY_PROPERTY); int priority = Thread.NORM_PRIORITY; if (s != null) { try { priority = Integer.parseInt(s); } catch (NumberFormatException ex) { // priority remains...
java
public static int getRecordsYield() { String s = System.getProperty(RECORDS_YIELD_PROPERTY); int records = Integer.MAX_VALUE; if (s != null) { try { records = Integer.parseInt(s); } catch (NumberFormatException ex) { // records remains Int...
java
public static int getMillisYield() { String s = System.getProperty(MILLIS_YIELD_PROPERTY); int millis = DEFAULT_MILLIS_YIELD; if (s != null) { try { millis = Integer.parseInt(s); } catch (NumberFormatException ex) { // records remains DEFA...
java
public static void createSummaryInformation(String filePath, String title) { if (filePath == null) { return; } try { File poiFilesystem = new File(filePath); InputStream is = new FileInputStream(poiFilesystem); POIFSFileSystem poifs = new POIFSFil...
java
public ClassLoader getSiteClassLoader (int siteId) throws IOException { // synchronize on the lock to ensure that only one thread per site // is concurrently executing synchronized (getLock(siteId)) { // see if we've already got one ClassLoader loader = _loade...
java
protected Object getLock (int siteId) { Object lock = null; synchronized (_locks) { lock = _locks.get(siteId); // create a lock object if we haven't one already if (lock == null) { _locks.put(siteId, lock = new Object()); } } ...
java
protected SiteResourceBundle getBundle (int siteId) throws IOException { // look up the site resource bundle for this site SiteResourceBundle bundle = _bundles.get(siteId); // if we haven't got one, create one if (bundle == null) { // obtain the string identifier...
java
public static Interval create (RunQueue runQueue, final Runnable onExpired) { // we could probably avoid all the wacky machinations internal to Interval that do the // runbuddy reposting and whatever and just create a non-runqueue interval that posts the // supplied runnable to the runqueue ...
java
public final void cancel () { IntervalTask task = _task; if (task != null) { _task = null; task.cancel(); } }
java
public static void deliverMail (String recipient, String sender, String subject, String body) throws IOException { deliverMail(new String[] { recipient }, sender, subject, body); }
java
public static void deliverMail (String[] recipients, String sender, String subject, String body, String[] headers, String[] values) throws IOException { if (recipients == null || recipients.length < 1) { throw new IO...
java
public static void deliverMail (String[] recipients, String sender, String subject, MimeMessage message) throws IOException { checkCreateSession(); try { message.setFrom(new InternetAddress(sender)); for (String recipient : recipien...
java
protected static void checkCreateSession () { if (_defaultSession == null) { // no need to sync Properties props = System.getProperties(); if (props.getProperty("mail.smtp.host") == null) { props.put("mail.smtp.host", "localhost"); } _defaultSe...
java
public Template getTemplate (String path, String encoding) throws Exception { Object siteId = get("__siteid__"); if (siteId != null) { path = siteId + ":" + path; } if (encoding == null) { return RuntimeSingleton.getRuntimeServices().getTemplate(path);...
java
@Deprecated public void putAllParameters () { Enumeration<?> e = _req.getParameterNames(); while (e.hasMoreElements()) { String param = (String)e.nextElement(); put(param, _req.getParameter(param)); } }
java
public String encodeAllParameters () { StringBuilder buf = new StringBuilder(); Enumeration<?> e = _req.getParameterNames(); while (e.hasMoreElements()) { if (buf.length() > 0) { buf.append('&'); } String param = (String) e.nextElement(); ...
java
public static DatabaseLiaison getLiaison (String url) { if (url == null) throw new NullPointerException("URL must not be null"); // see if we already have a liaison mapped for this connection DatabaseLiaison liaison = _mappings.get(url); if (liaison == null) { // scan the...
java
private XSSFCellStyle updateSubreportBandElementStyle(XSSFCellStyle cellStyle, BandElement bandElement, Object value, int gridRow, int gridColumn, int colSpan) { if (subreportCellStyle == null) { return cellStyle; } if (gridColumn == 0) { cellStyle.setBorderLeft(sub...
java
public V get (K key) { V value = null; SoftReference<V> ref = _map.get(key); if (ref != null) { value = ref.get(); if (value == null) { _map.remove(key); } } return value; }
java
public V remove (K key) { SoftReference<V> ref = _map.remove(key); return (ref == null) ? null : ref.get(); }
java
public static SiteIdentifier single (final int siteId, final String siteString) { return new SiteIdentifier() { public int identifySite (HttpServletRequest req) { return siteId; } public String getSiteString (int siteId) { return siteString; ...
java
public static String generateRandomKey (Random rand, int length) { int numKeyChars = KEY_CHARS.length(); StringBuilder buf = new StringBuilder(); for (int ii = 0; ii < length; ii++) { buf.append(KEY_CHARS.charAt(rand.nextInt(numKeyChars))); } return buf.toString()...
java
public static boolean verifyLuhn (String key) { // If there is a non digit, or it is all zeros. if (StringUtil.isBlank(key) || key.matches(".*\\D.*") || key.matches("^[0]+$")) { return false; } return (getLuhnRemainder(key) == 0); }
java
public static int getLuhnRemainder (String key) { int len = key.length(); int sum = 0; for (int multSeq = len % 2, ii=0; ii < len; ii++) { int c = key.charAt(ii) - '0'; if (ii % 2 == multSeq) { c *= 2; } sum += (c / 10) + (c % 1...
java
public static void configureDefaultHandler (Formatter formatter) { Logger logger = LogManager.getLogManager().getLogger(""); for (Handler handler : logger.getHandlers()) { handler.setFormatter(formatter); } }
java
public static void reverse (byte[] values, int offset, int length) { int aidx = offset; int bidx = offset + length - 1; while (bidx > aidx) { byte value = values[aidx]; values[aidx] = values[bidx]; values[bidx] = value; aidx++; bidx...
java
public static void shuffle (Object[] values, Random rnd) { shuffle(values, 0, values.length, rnd); }
java
public static byte[] insert (byte[] values, byte value, int index) { byte[] nvalues = new byte[values.length+1]; if (index > 0) { System.arraycopy(values, 0, nvalues, 0, index); } nvalues[index] = value; if (index < values.length) { System.arraycopy(va...
java
public static <T extends Object> T[] insert (T[] values, T value, int index) { @SuppressWarnings("unchecked") T[] nvalues = (T[])Array.newInstance(values.getClass().getComponentType(), values.length+1); if (index > 0) { System.arraycopy(values, 0, nvalues, 0, index); } ...
java
public static <T extends Object> T[] append (T[] values, T value) { return insert(values, value, values.length); }
java