proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/menu/Menu.java
|
Menu
|
onActivated
|
class Menu extends MenuItem {
private final List<MenuItem> subItems;
/**
* Creates a menu with the specified label
* @param label Label to use for the menu item that will trigger this menu to pop up
*/
public Menu(String label) {
super(label);
this.subItems = new ArrayList<>();
}
/**
* Adds a new menu item to this menu, this can be either a regular {@link MenuItem} or another {@link Menu}
* @param menuItem The item to add to this menu
* @return Itself
*/
public Menu add(MenuItem menuItem) {
synchronized (subItems) {
subItems.add(menuItem);
}
return this;
}
@Override
protected boolean onActivated() {<FILL_FUNCTION_BODY>}
}
|
boolean result = true;
if (subItems.isEmpty()) {
return result;
}
final MenuPopupWindow popupMenu = new MenuPopupWindow(this);
final AtomicBoolean popupCancelled = new AtomicBoolean(false);
for (MenuItem menuItem : subItems) {
popupMenu.addMenuItem(menuItem);
}
if (getParent() instanceof MenuBar) {
final MenuBar menuBar = (MenuBar) getParent();
popupMenu.addWindowListener(new WindowListenerAdapter() {
@Override
public void onUnhandledInput(Window basePane, KeyStroke keyStroke, AtomicBoolean hasBeenHandled) {
if (keyStroke.getKeyType() == KeyType.ARROW_LEFT) {
int thisMenuIndex = menuBar.getChildrenList().indexOf(Menu.this);
if (thisMenuIndex > 0) {
popupMenu.close();
Menu nextSelectedMenu = menuBar.getMenu(thisMenuIndex - 1);
nextSelectedMenu.takeFocus();
nextSelectedMenu.onActivated();
}
} else if (keyStroke.getKeyType() == KeyType.ARROW_RIGHT) {
int thisMenuIndex = menuBar.getChildrenList().indexOf(Menu.this);
if (thisMenuIndex >= 0 && thisMenuIndex < menuBar.getMenuCount() - 1) {
popupMenu.close();
Menu nextSelectedMenu = menuBar.getMenu(thisMenuIndex + 1);
nextSelectedMenu.takeFocus();
nextSelectedMenu.onActivated();
}
}
}
});
}
popupMenu.addWindowListener(new WindowListenerAdapter() {
@Override
public void onUnhandledInput(Window basePane, KeyStroke keyStroke, AtomicBoolean hasBeenHandled) {
if (keyStroke.getKeyType() == KeyType.ESCAPE) {
popupCancelled.set(true);
popupMenu.close();
}
}
});
((WindowBasedTextGUI) getTextGUI()).addWindowAndWait(popupMenu);
result = !popupCancelled.get();
return result;
| 215
| 551
| 766
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, java.lang.Runnable) ,public java.lang.String getLabel() <variables>private final non-sealed java.lang.Runnable action,private java.lang.String label
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/menu/MenuBar.java
|
MenuBar
|
previousFocus
|
class MenuBar extends AbstractComponent<MenuBar> implements Container {
private static final int EXTRA_PADDING = 0;
private final List<Menu> menus;
/**
* Creates a new menu bar
*/
public MenuBar() {
this.menus = new CopyOnWriteArrayList<>();
}
/**
* Adds a new drop-down menu to the menu bar, at the end
* @param menu Menu to add to the menu bar
* @return Itself
*/
public MenuBar add(Menu menu) {
menus.add(menu);
menu.onAdded(this);
return this;
}
@Override
public int getChildCount() {
return getMenuCount();
}
@Override
public List<Component> getChildrenList() {
return new ArrayList<>(menus);
}
@Override
public Collection<Component> getChildren() {
return getChildrenList();
}
@Override
public boolean containsComponent(Component component) {
return menus.contains(component);
}
@Override
public synchronized boolean removeComponent(Component component) {
boolean hadMenu = menus.remove(component);
if (hadMenu) {
component.onRemoved(this);
}
return hadMenu;
}
@Override
public synchronized Interactable nextFocus(Interactable fromThis) {
if (menus.isEmpty()) {
return null;
}
else if (fromThis == null) {
return menus.get(0);
}
else if (!menus.contains(fromThis) || menus.indexOf(fromThis) == menus.size() - 1) {
return null;
}
else {
return menus.get(menus.indexOf(fromThis) + 1);
}
}
@Override
public Interactable previousFocus(Interactable fromThis) {<FILL_FUNCTION_BODY>}
@Override
public boolean handleInput(KeyStroke key) {
return false;
}
/**
* Returns the drop-down menu at the specified index. This method will throw an Array
* @param index Index of the menu to return
* @return The drop-down menu at the specified index
* @throws IndexOutOfBoundsException if the index is out of range
*/
public Menu getMenu(int index) {
return menus.get(index);
}
/**
* Returns the number of menus this menu bar currently has
* @return The number of menus this menu bar currently has
*/
public int getMenuCount() {
return menus.size();
}
@Override
protected ComponentRenderer<MenuBar> createDefaultRenderer() {
return new DefaultMenuBarRenderer();
}
@Override
public synchronized void updateLookupMap(InteractableLookupMap interactableLookupMap) {
for (Menu menu: menus) {
interactableLookupMap.add(menu);
}
}
@Override
public TerminalPosition toBasePane(TerminalPosition position) {
// Assume the menu is always at the top of the content panel
return position;
}
public boolean isEmptyMenuBar() {
return false;
}
/**
* The default implementation for rendering a {@link MenuBar}
*/
public class DefaultMenuBarRenderer implements ComponentRenderer<MenuBar> {
@Override
public TerminalSize getPreferredSize(MenuBar menuBar) {
int maxHeight = 1;
int totalWidth = EXTRA_PADDING;
for (int i = 0; i < menuBar.getMenuCount(); i++) {
Menu menu = menuBar.getMenu(i);
TerminalSize preferredSize = menu.getPreferredSize();
maxHeight = Math.max(maxHeight, preferredSize.getRows());
totalWidth += preferredSize.getColumns();
}
totalWidth += EXTRA_PADDING;
return new TerminalSize(totalWidth, maxHeight);
}
@Override
public void drawComponent(TextGUIGraphics graphics, MenuBar menuBar) {
// Reset the area
graphics.applyThemeStyle(getThemeDefinition().getNormal());
graphics.fill(' ');
int leftPosition = EXTRA_PADDING;
TerminalSize size = graphics.getSize();
int remainingSpace = size.getColumns() - EXTRA_PADDING;
for (int i = 0; i < menuBar.getMenuCount() && remainingSpace > 0; i++) {
Menu menu = menuBar.getMenu(i);
TerminalSize preferredSize = menu.getPreferredSize();
menu.setPosition(menu.getPosition()
.withColumn(leftPosition)
.withRow(0));
int finalWidth = Math.min(preferredSize.getColumns(), remainingSpace);
menu.setSize(menu.getSize()
.withColumns(finalWidth)
.withRows(size.getRows()));
remainingSpace -= finalWidth + EXTRA_PADDING;
leftPosition += finalWidth + EXTRA_PADDING;
TextGUIGraphics componentGraphics = graphics.newTextGraphics(menu.getPosition(), menu.getSize());
menu.draw(componentGraphics);
}
}
}
}
|
if (menus.isEmpty()) {
return null;
}
else if (fromThis == null) {
return menus.get(menus.size() - 1);
}
else if (!menus.contains(fromThis) || menus.indexOf(fromThis) == 0) {
return null;
}
else {
return menus.get(menus.indexOf(fromThis) - 1);
}
| 1,336
| 113
| 1,449
|
<methods>public void <init>() ,public synchronized com.googlecode.lanterna.gui2.menu.MenuBar addTo(com.googlecode.lanterna.gui2.Panel) ,public final synchronized void draw(com.googlecode.lanterna.gui2.TextGUIGraphics) ,public com.googlecode.lanterna.gui2.BasePane getBasePane() ,public com.googlecode.lanterna.TerminalPosition getGlobalPosition() ,public com.googlecode.lanterna.gui2.LayoutData getLayoutData() ,public com.googlecode.lanterna.gui2.Container getParent() ,public com.googlecode.lanterna.TerminalPosition getPosition() ,public final com.googlecode.lanterna.TerminalSize getPreferredSize() ,public synchronized ComponentRenderer<com.googlecode.lanterna.gui2.menu.MenuBar> getRenderer() ,public com.googlecode.lanterna.TerminalSize getSize() ,public com.googlecode.lanterna.gui2.TextGUI getTextGUI() ,public synchronized com.googlecode.lanterna.graphics.Theme getTheme() ,public com.googlecode.lanterna.graphics.ThemeDefinition getThemeDefinition() ,public boolean hasParent(com.googlecode.lanterna.gui2.Container) ,public void invalidate() ,public boolean isInside(com.googlecode.lanterna.gui2.Container) ,public boolean isInvalid() ,public boolean isVisible() ,public synchronized void onAdded(com.googlecode.lanterna.gui2.Container) ,public synchronized void onRemoved(com.googlecode.lanterna.gui2.Container) ,public synchronized com.googlecode.lanterna.gui2.menu.MenuBar setLayoutData(com.googlecode.lanterna.gui2.LayoutData) ,public synchronized com.googlecode.lanterna.gui2.menu.MenuBar setPosition(com.googlecode.lanterna.TerminalPosition) ,public final synchronized com.googlecode.lanterna.gui2.menu.MenuBar setPreferredSize(com.googlecode.lanterna.TerminalSize) ,public com.googlecode.lanterna.gui2.menu.MenuBar setRenderer(ComponentRenderer<com.googlecode.lanterna.gui2.menu.MenuBar>) ,public synchronized com.googlecode.lanterna.gui2.menu.MenuBar setSize(com.googlecode.lanterna.TerminalSize) ,public synchronized com.googlecode.lanterna.gui2.Component setTheme(com.googlecode.lanterna.graphics.Theme) ,public com.googlecode.lanterna.gui2.menu.MenuBar setVisible(boolean) ,public com.googlecode.lanterna.TerminalPosition toBasePane(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition toGlobal(com.googlecode.lanterna.TerminalPosition) ,public synchronized com.googlecode.lanterna.gui2.Border withBorder(com.googlecode.lanterna.gui2.Border) <variables>private ComponentRenderer<com.googlecode.lanterna.gui2.menu.MenuBar> defaultRenderer,private com.googlecode.lanterna.TerminalSize explicitPreferredSize,private boolean invalid,private com.googlecode.lanterna.gui2.LayoutData layoutData,private ComponentRenderer<com.googlecode.lanterna.gui2.menu.MenuBar> overrideRenderer,private com.googlecode.lanterna.gui2.Container parent,private com.googlecode.lanterna.TerminalPosition position,private com.googlecode.lanterna.TerminalSize size,private com.googlecode.lanterna.graphics.Theme themeOverride,private ComponentRenderer<com.googlecode.lanterna.gui2.menu.MenuBar> themeRenderer,private com.googlecode.lanterna.graphics.Theme themeRenderersTheme,private boolean visible
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/menu/MenuItem.java
|
DefaultMenuItemRenderer
|
getPreferredSize
|
class DefaultMenuItemRenderer extends MenuItemRenderer {
@Override
public TerminalPosition getCursorLocation(MenuItem component) {
return null;
}
@Override
public TerminalSize getPreferredSize(MenuItem component) {<FILL_FUNCTION_BODY>}
@Override
public void drawComponent(TextGUIGraphics graphics, MenuItem menuItem) {
ThemeDefinition themeDefinition = menuItem.getThemeDefinition();
if (menuItem.isFocused()) {
graphics.applyThemeStyle(themeDefinition.getSelected());
}
else {
graphics.applyThemeStyle(themeDefinition.getNormal());
}
final String label = menuItem.getLabel();
final String leadingCharacter = label.substring(0, 1);
graphics.fill(' ');
graphics.putString(1, 0, label);
if (menuItem instanceof Menu && !(menuItem.getParent() instanceof MenuBar)) {
graphics.putString(graphics.getSize().getColumns() - 2, 0, String.valueOf(Symbols.TRIANGLE_RIGHT_POINTING_BLACK));
}
if (!label.isEmpty()) {
if (menuItem.isFocused()) {
graphics.applyThemeStyle(themeDefinition.getActive());
}
else {
graphics.applyThemeStyle(themeDefinition.getPreLight());
}
graphics.putString(1, 0, leadingCharacter);
}
}
}
|
int preferredWidth = TerminalTextUtils.getColumnWidth(component.getLabel()) + 2;
if (component instanceof Menu && !(component.getParent() instanceof MenuBar)) {
preferredWidth += 2;
}
return TerminalSize.ONE.withColumns(preferredWidth);
| 366
| 70
| 436
|
<methods>public com.googlecode.lanterna.TerminalPosition getCursorLocation() ,public com.googlecode.lanterna.gui2.InputFilter getInputFilter() ,public InteractableRenderer<com.googlecode.lanterna.gui2.menu.MenuItem> getRenderer() ,public final synchronized com.googlecode.lanterna.gui2.Interactable.Result handleInput(com.googlecode.lanterna.input.KeyStroke) ,public boolean isActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isEnabled() ,public boolean isFocusable() ,public boolean isFocused() ,public boolean isKeyboardActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseDown(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseDrag(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseMove(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseUp(com.googlecode.lanterna.input.KeyStroke) ,public final void onEnterFocus(com.googlecode.lanterna.gui2.Interactable.FocusChangeDirection, com.googlecode.lanterna.gui2.Interactable) ,public final void onLeaveFocus(com.googlecode.lanterna.gui2.Interactable.FocusChangeDirection, com.googlecode.lanterna.gui2.Interactable) ,public synchronized com.googlecode.lanterna.gui2.menu.MenuItem setEnabled(boolean) ,public synchronized com.googlecode.lanterna.gui2.menu.MenuItem setInputFilter(com.googlecode.lanterna.gui2.InputFilter) ,public com.googlecode.lanterna.gui2.menu.MenuItem takeFocus() <variables>private boolean enabled,private boolean inFocus,private com.googlecode.lanterna.gui2.InputFilter inputFilter
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/table/DefaultTableCellRenderer.java
|
DefaultTableCellRenderer
|
getPreferredSize
|
class DefaultTableCellRenderer<V> implements TableCellRenderer<V> {
@Override
public TerminalSize getPreferredSize(Table<V> table, V cell, int columnIndex, int rowIndex) {<FILL_FUNCTION_BODY>}
@Override
public void drawCell(Table<V> table, V cell, int columnIndex, int rowIndex, TextGUIGraphics textGUIGraphics) {
boolean isSelected = (table.getSelectedColumn() == columnIndex && table.getSelectedRow() == rowIndex) ||
(table.getSelectedRow() == rowIndex && !table.isCellSelection());
applyStyle(table, cell, columnIndex, rowIndex, isSelected, textGUIGraphics);
beforeRender(table, cell, columnIndex, rowIndex, isSelected, textGUIGraphics);
render(table, cell, columnIndex, rowIndex, isSelected, textGUIGraphics);
afterRender(table, cell, columnIndex, rowIndex, isSelected, textGUIGraphics);
}
/**
* Called by the cell renderer to setup all the styling (colors and SGRs) before rendering the cell. This method
* exists as protected in order to make it easier to extend and customize {@link DefaultTableCellRenderer}. Unless
* {@link DefaultTableCellRenderer#drawCell(Table, Object, int, int, TextGUIGraphics)} it overridden, it will be
* called when the cell is rendered.
* @param table Table the cell belongs to
* @param cell Cell being rendered
* @param columnIndex Column index of the cell being rendered
* @param rowIndex Row index of the cell being rendered
* @param isSelected Set to {@code true} if the cell is currently selected by the user
* @param textGUIGraphics {@link TextGUIGraphics} object to set the style on, this will be used in the rendering later
*/
protected void applyStyle(Table<V> table, V cell, int columnIndex, int rowIndex, boolean isSelected, TextGUIGraphics textGUIGraphics) {
ThemeDefinition themeDefinition = table.getThemeDefinition();
if(isSelected) {
if(table.isFocused()) {
textGUIGraphics.applyThemeStyle(themeDefinition.getActive());
}
else {
textGUIGraphics.applyThemeStyle(themeDefinition.getSelected());
}
}
else {
textGUIGraphics.applyThemeStyle(themeDefinition.getNormal());
}
}
/**
* Called by the cell renderer to prepare the cell area before rendering the cell. In the default implementation
* it will clear the area with whitespaces. This method exists as protected in order to make it easier to extend and
* customize {@link DefaultTableCellRenderer}. Unless
* {@link DefaultTableCellRenderer#drawCell(Table, Object, int, int, TextGUIGraphics)} it overridden, it will be
* called when the cell is rendered, after setting up the styling but before the cell content text is drawn.
* @param table Table the cell belongs to
* @param cell Cell being rendered
* @param columnIndex Column index of the cell being rendered
* @param rowIndex Row index of the cell being rendered
* @param isSelected Set to {@code true} if the cell is currently selected by the user
* @param textGUIGraphics {@link TextGUIGraphics} object for the cell, already having been prepared with styling
*/
protected void beforeRender(Table<V> table, V cell, int columnIndex, int rowIndex, boolean isSelected, TextGUIGraphics textGUIGraphics) {
textGUIGraphics.fill(' ');
}
/**
* Called by the cell renderer to draw the content of the cell into the assigned area. In the default implementation
* it will transform the content to multilines are draw them one by one. This method exists as protected in order to
* make it easier to extend and customize {@link DefaultTableCellRenderer}. Unless
* {@link DefaultTableCellRenderer#drawCell(Table, Object, int, int, TextGUIGraphics)} it overridden, it will be
* called when the cell is rendered, after setting up the styling and preparing the cell.
* @param table Table the cell belongs to
* @param cell Cell being rendered
* @param columnIndex Column index of the cell being rendered
* @param rowIndex Row index of the cell being rendered
* @param isSelected Set to {@code true} if the cell is currently selected by the user
* @param textGUIGraphics {@link TextGUIGraphics} object for the cell, already having been prepared with styling
*/
protected void render(Table<V> table, V cell, int columnIndex, int rowIndex, boolean isSelected, TextGUIGraphics textGUIGraphics) {
String[] lines = getContent(cell);
int rowCount = 0;
for(String line: lines) {
textGUIGraphics.putString(0, rowCount++, line);
}
}
/**
* Called by the cell renderer after the cell content has been drawn into the assigned area. In the default
* implementation it will do nothing. This method exists as protected in order to make it easier to extend and
* customize {@link DefaultTableCellRenderer}. Unless
* {@link DefaultTableCellRenderer#drawCell(Table, Object, int, int, TextGUIGraphics)} it overridden, it will be
* called after the cell has been rendered but before the table moves on to the next cell.
* @param table Table the cell belongs to
* @param cell Cell being rendered
* @param columnIndex Column index of the cell being rendered
* @param rowIndex Row index of the cell being rendered
* @param isSelected Set to {@code true} if the cell is currently selected by the user
* @param textGUIGraphics {@link TextGUIGraphics} object for the cell, already having been prepared with styling
*/
protected void afterRender(Table<V> table, V cell, int columnIndex, int rowIndex, boolean isSelected, TextGUIGraphics textGUIGraphics) {
}
/**
* Turns a cell into a multiline string, as an array.
* @param cell Cell to turn into string content
* @return The cell content turned into a multiline string, where each element in the array is one row.
*/
protected String[] getContent(V cell) {
String[] lines;
if(cell == null) {
lines = new String[] { "" };
}
else {
lines = cell.toString().split("\r?\n");
}
return lines;
}
}
|
String[] lines = getContent(cell);
int maxWidth = 0;
for(String line: lines) {
int length = TerminalTextUtils.getColumnWidth(line);
if(maxWidth < length) {
maxWidth = length;
}
}
return new TerminalSize(maxWidth, lines.length);
| 1,621
| 84
| 1,705
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/table/DefaultTableHeaderRenderer.java
|
DefaultTableHeaderRenderer
|
drawHeader
|
class DefaultTableHeaderRenderer<V> implements TableHeaderRenderer<V> {
@Override
public TerminalSize getPreferredSize(Table<V> table, String label, int columnIndex) {
if(label == null) {
return TerminalSize.ZERO;
}
return new TerminalSize(TerminalTextUtils.getColumnWidth(label), 1);
}
@Override
public void drawHeader(Table<V> table, String label, int index, TextGUIGraphics textGUIGraphics) {<FILL_FUNCTION_BODY>}
}
|
ThemeDefinition themeDefinition = table.getThemeDefinition();
textGUIGraphics.applyThemeStyle(themeDefinition.getCustom("HEADER", themeDefinition.getNormal()));
textGUIGraphics.putString(0, 0, label);
| 141
| 62
| 203
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/input/AltAndCharacterPattern.java
|
AltAndCharacterPattern
|
match
|
class AltAndCharacterPattern implements CharacterPattern {
@Override
public Matching match(List<Character> seq) {<FILL_FUNCTION_BODY>}
}
|
int size = seq.size();
if (size > 2 || seq.get(0) != KeyDecodingProfile.ESC_CODE) {
return null; // nope
}
if (size == 1) {
return Matching.NOT_YET; // maybe later
}
if ( Character.isISOControl(seq.get(1)) ) {
return null; // nope
}
KeyStroke ks = new KeyStroke(seq.get(1), false, true);
return new Matching( ks ); // yep
| 44
| 143
| 187
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/input/BasicCharacterPattern.java
|
BasicCharacterPattern
|
match
|
class BasicCharacterPattern implements CharacterPattern {
private final KeyStroke result;
private final char[] pattern;
/**
* Creates a new BasicCharacterPattern that matches a particular sequence of characters into a {@code KeyStroke}
* @param result {@code KeyStroke} that this pattern will translate to
* @param pattern Sequence of characters that translates into the {@code KeyStroke}
*/
public BasicCharacterPattern(KeyStroke result, char... pattern) {
this.result = result;
this.pattern = pattern;
}
/**
* Returns the characters that makes up this pattern, as an array that is a copy of the array used internally
* @return Array of characters that defines this pattern
*/
public char[] getPattern() {
return Arrays.copyOf(pattern, pattern.length);
}
/**
* Returns the keystroke that this pattern results in
* @return The keystoke this pattern will return if it matches
*/
public KeyStroke getResult() {
return result;
}
@Override
public Matching match(List<Character> seq) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BasicCharacterPattern)) {
return false;
}
BasicCharacterPattern other = (BasicCharacterPattern) obj;
return Arrays.equals(this.pattern, other.pattern);
}
@Override
public int hashCode() {
int hash = 3;
hash = 53 * hash + Arrays.hashCode(this.pattern);
return hash;
}
}
|
int size = seq.size();
if(size > pattern.length) {
return null; // nope
}
for (int i = 0; i < size; i++) {
if (pattern[i] != seq.get(i)) {
return null; // nope
}
}
if (size == pattern.length) {
return new Matching( getResult() ); // yep
} else {
return Matching.NOT_YET; // maybe later
}
| 408
| 133
| 541
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/input/CtrlAltAndCharacterPattern.java
|
CtrlAltAndCharacterPattern
|
match
|
class CtrlAltAndCharacterPattern implements CharacterPattern {
@Override
public Matching match(List<Character> seq) {<FILL_FUNCTION_BODY>}
}
|
int size = seq.size();
if (size > 2 || seq.get(0) != KeyDecodingProfile.ESC_CODE) {
return null; // nope
}
if (size == 1) {
return Matching.NOT_YET; // maybe later
}
char ch = seq.get(1);
if (ch < 32 && ch != 0x08) {
// Control-chars: exclude Esc(^[), but still include ^\, ^], ^^ and ^_
char ctrlCode;
switch (ch) {
case KeyDecodingProfile.ESC_CODE: return null; // nope
case 0: /* ^@ */ ctrlCode = ' '; break;
case 28: /* ^\ */ ctrlCode = '\\'; break;
case 29: /* ^] */ ctrlCode = ']'; break;
case 30: /* ^^ */ ctrlCode = '^'; break;
case 31: /* ^_ */ ctrlCode = '_'; break;
default: ctrlCode = (char)('a' - 1 + ch);
}
KeyStroke ks = new KeyStroke( ctrlCode, true, true);
return new Matching( ks ); // yep
} else if (ch == 0x7f || ch == 0x08) {
KeyStroke ks = new KeyStroke( KeyType.BACKSPACE, false, true);
return new Matching( ks ); // yep
} else {
return null; // nope
}
| 45
| 397
| 442
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/input/CtrlAndCharacterPattern.java
|
CtrlAndCharacterPattern
|
match
|
class CtrlAndCharacterPattern implements CharacterPattern {
@Override
public Matching match(List<Character> seq) {<FILL_FUNCTION_BODY>}
}
|
int size = seq.size(); char ch = seq.get(0);
if (size != 1) {
return null; // nope
}
if (ch < 32) {
// Control-chars: exclude lf,cr,Tab,Esc(^[), but still include ^\, ^], ^^ and ^_
char ctrlCode;
switch (ch) {
case '\n': case '\r': case '\t': case 0x08:
case KeyDecodingProfile.ESC_CODE: return null; // nope
case 0: /* ^@ */ ctrlCode = ' '; break;
case 28: /* ^\ */ ctrlCode = '\\'; break;
case 29: /* ^] */ ctrlCode = ']'; break;
case 30: /* ^^ */ ctrlCode = '^'; break;
case 31: /* ^_ */ ctrlCode = '_'; break;
default: ctrlCode = (char)('a' - 1 + ch);
}
KeyStroke ks = new KeyStroke( ctrlCode, true, false);
return new Matching( ks ); // yep
} else {
return null; // nope
}
| 43
| 313
| 356
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/input/InputDecoder.java
|
InputDecoder
|
getNextCharacter
|
class InputDecoder {
private final Reader source;
private final List<CharacterPattern> bytePatterns;
private final List<Character> currentMatching;
private boolean seenEOF;
private int timeoutUnits;
/**
* Creates a new input decoder using a specified Reader as the source to read characters from
* @param source Reader to read characters from, will be wrapped by a BufferedReader
*/
public InputDecoder(final Reader source) {
this.source = new BufferedReader(source);
this.bytePatterns = new ArrayList<>();
this.currentMatching = new ArrayList<>();
this.seenEOF = false;
this.timeoutUnits = 0; // default is no wait at all
}
/**
* Adds another key decoding profile to this InputDecoder, which means all patterns from the profile will be used
* when decoding input.
* @param profile Profile to add
*/
public void addProfile(KeyDecodingProfile profile) {
for (CharacterPattern pattern : profile.getPatterns()) {
synchronized(bytePatterns) {
//If an equivalent pattern already exists, remove it first
bytePatterns.remove(pattern);
bytePatterns.add(pattern);
}
}
}
/**
* Returns a collection of all patterns registered in this InputDecoder.
* @return Collection of patterns in the InputDecoder
*/
public synchronized Collection<CharacterPattern> getPatterns() {
synchronized(bytePatterns) {
return new ArrayList<>(bytePatterns);
}
}
/**
* Removes one pattern from the list of patterns in this InputDecoder
* @param pattern Pattern to remove
* @return {@code true} if the supplied pattern was found and was removed, otherwise {@code false}
*/
public boolean removePattern(CharacterPattern pattern) {
synchronized(bytePatterns) {
return bytePatterns.remove(pattern);
}
}
/**
* Sets the number of 1/4-second units for how long to try to get further input
* to complete an escape-sequence for a special Key.
*
* Negative numbers are mapped to 0 (no wait at all), and unreasonably high
* values are mapped to a maximum of 240 (1 minute).
* @param units New timeout to use, in 250ms units
*/
public void setTimeoutUnits(int units) {
timeoutUnits = (units < 0) ? 0 :
(units > 240) ? 240 :
units;
}
/**
* queries the current timeoutUnits value. One unit is 1/4 second.
* @return The timeout this InputDecoder will use when waiting for additional input, in units of 1/4 seconds
*/
public int getTimeoutUnits() {
return timeoutUnits;
}
/**
* Reads and decodes the next key stroke from the input stream
* @param blockingIO If set to {@code true}, the call will not return until it has read at least one {@link KeyStroke}
* @return Key stroke read from the input stream, or {@code null} if none
* @throws IOException If there was an I/O error when reading from the input stream
*/
public synchronized KeyStroke getNextCharacter(boolean blockingIO) throws IOException {<FILL_FUNCTION_BODY>}
private Matching getBestMatch(List<Character> characterSequence) {
boolean partialMatch = false;
KeyStroke bestMatch = null;
synchronized(bytePatterns) {
for(CharacterPattern pattern : bytePatterns) {
Matching res = pattern.match(characterSequence);
if (res != null) {
if (res.partialMatch) { partialMatch = true; }
if (res.fullMatch != null) { bestMatch = res.fullMatch; }
}
}
}
return new Matching(partialMatch, bestMatch);
}
}
|
KeyStroke bestMatch = null;
int bestLen = 0;
int curLen = 0;
while(true) {
if ( curLen < currentMatching.size() ) {
// (re-)consume characters previously read:
curLen++;
}
else {
// If we already have a bestMatch but a chance for a longer match
// then we poll for the configured number of timeout units:
// It would be much better, if we could just read with a timeout,
// but lacking that, we wait 1/4s units and check for readiness.
if (bestMatch != null) {
int timeout = getTimeoutUnits();
while (timeout > 0 && ! source.ready() ) {
try {
timeout--; Thread.sleep(250);
} catch (InterruptedException e) { timeout = 0; }
}
}
// if input is available, we can just read a char without waiting,
// otherwise, for readInput() with no bestMatch found yet,
// we have to wait blocking for more input:
if ( source.ready() || ( blockingIO && bestMatch == null ) ) {
int readChar = source.read();
if (readChar == -1) {
seenEOF = true;
if(currentMatching.isEmpty()) {
return new KeyStroke(KeyType.EOF);
}
break;
}
currentMatching.add( (char)readChar );
curLen++;
} else { // no more available input at this time.
// already found something:
if (bestMatch != null) {
break; // it's something...
}
// otherwise: no KeyStroke yet
return null;
}
}
List<Character> curSub = currentMatching.subList(0, curLen);
Matching matching = getBestMatch( curSub );
// fullMatch found...
if (matching.fullMatch != null) {
bestMatch = matching.fullMatch;
bestLen = curLen;
if (! matching.partialMatch) {
// that match and no more
break;
} else {
// that match, but maybe more
//noinspection UnnecessaryContinue
continue;
}
}
// No match found yet, but there's still potential...
else if ( matching.partialMatch ) {
//noinspection UnnecessaryContinue
continue;
}
// no longer match possible at this point:
else {
if (bestMatch != null ) {
// there was already a previous full-match, use it:
break;
} else { // invalid input!
// remove the whole fail and re-try finding a KeyStroke...
curSub.clear(); // or just 1 char? currentMatching.remove(0);
curLen = 0;
//noinspection UnnecessaryContinue
continue;
}
}
}
//Did we find anything? Otherwise return null
if(bestMatch == null) {
if(seenEOF) {
currentMatching.clear();
return new KeyStroke(KeyType.EOF);
}
return null;
}
List<Character> bestSub = currentMatching.subList(0, bestLen );
bestSub.clear(); // remove matched characters from input
return bestMatch;
| 991
| 847
| 1,838
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/input/MouseAction.java
|
MouseAction
|
toString
|
class MouseAction extends KeyStroke {
private final MouseActionType actionType;
private final int button;
private final TerminalPosition position;
/**
* Constructs a MouseAction based on an action type, a button and a location on the screen
* @param actionType The kind of mouse event
* @param button Which button is involved (no button = 0, left button = 1, middle (wheel) button = 2,
* right button = 3, scroll wheel up = 4, scroll wheel down = 5)
* @param position Where in the terminal is the mouse cursor located
*/
public MouseAction(MouseActionType actionType, int button, TerminalPosition position) {
super(KeyType.MOUSE_EVENT, false, false);
this.actionType = actionType;
this.button = button;
this.position = position;
}
/**
* Returns the mouse action type so the caller can determine which kind of action was performed.
* @return The action type of the mouse event
*/
public MouseActionType getActionType() {
return actionType;
}
/**
* Which button was involved in this event. Please note that for CLICK_RELEASE events, there is no button
* information available (getButton() will return 0). The standard xterm mapping is:
* <ul>
* <li>No button = 0</li>
* <li>Left button = 1</li>
* <li>Middle (wheel) button = 2</li>
* <li>Right button = 3</li>
* <li>Wheel up = 4</li>
* <li>Wheel down = 5</li>
* </ul>
* @return The button which is clicked down when this event was generated
*/
public int getButton() {
return button;
}
/**
* The location of the mouse cursor when this event was generated.
* @return Location of the mouse cursor
*/
public TerminalPosition getPosition() {
return position;
}
public boolean isMouseDown() {
return actionType == MouseActionType.CLICK_DOWN;
}
public boolean isMouseDrag() {
return actionType == MouseActionType.DRAG;
}
public boolean isMouseMove() {
return actionType == MouseActionType.MOVE;
}
public boolean isMouseUp() {
return actionType == MouseActionType.CLICK_RELEASE;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MouseAction{actionType=" + actionType + ", button=" + button + ", position=" + position + '}';
| 644
| 35
| 679
|
<methods>public void <init>(com.googlecode.lanterna.input.KeyType) ,public void <init>(com.googlecode.lanterna.input.KeyType, boolean, boolean) ,public void <init>(com.googlecode.lanterna.input.KeyType, boolean, boolean, boolean) ,public void <init>(java.lang.Character, boolean, boolean) ,public void <init>(java.lang.Character, boolean, boolean, boolean) ,public boolean equals(java.lang.Object) ,public static com.googlecode.lanterna.input.KeyStroke fromString(java.lang.String) ,public java.lang.Character getCharacter() ,public long getEventTime() ,public com.googlecode.lanterna.input.KeyType getKeyType() ,public int hashCode() ,public boolean isAltDown() ,public boolean isCtrlDown() ,public boolean isShiftDown() ,public java.lang.String toString() <variables>private final non-sealed boolean altDown,private final non-sealed java.lang.Character character,private final non-sealed boolean ctrlDown,private final non-sealed long eventTime,private final non-sealed com.googlecode.lanterna.input.KeyType keyType,private final non-sealed boolean shiftDown
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/input/MouseCharacterPattern.java
|
MouseCharacterPattern
|
match
|
class MouseCharacterPattern implements CharacterPattern {
private static final char[] PATTERN = { KeyDecodingProfile.ESC_CODE, '[', 'M' };
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// some terminals, for example XTerm, issue mouse down when it
// should be mouse move, after first click then they correctly issues
// mouse move, do some coercion here to force the correct action
private boolean isMouseDown = false;
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
@Override
public Matching match(List<Character> seq) {<FILL_FUNCTION_BODY>}
}
|
int size = seq.size();
if (size > 6) {
return null; // nope
}
// check first 3 chars:
for (int i = 0; i < 3; i++) {
if ( i >= size ) {
return Matching.NOT_YET; // maybe later
}
if ( seq.get(i) != PATTERN[i] ) {
return null; // nope
}
}
if (size < 6) {
return Matching.NOT_YET; // maybe later
}
MouseActionType actionType = null;
int part = (seq.get(3) & 0x3) + 1;
int button = part;
if(button == 4) {
//If last two bits are both set, it means button click release
button = 0;
}
int actionCode = (seq.get(3) & 0x60) >> 5;
switch(actionCode) {
case(1):
if(button > 0) {
actionType = MouseActionType.CLICK_DOWN;
isMouseDown = true;
}
else {
actionType = MouseActionType.CLICK_RELEASE;
isMouseDown = false;
}
break;
case(2): case(0):
if(button == 0) {
actionType = MouseActionType.MOVE;
}
else {
actionType = MouseActionType.DRAG;
}
break;
case(3):
if(button == 1) {
actionType = MouseActionType.SCROLL_UP;
button = 4;
}
else {
actionType = MouseActionType.SCROLL_DOWN;
button = 5;
}
break;
}
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// coerce action types:
// when in between CLICK_DOWN and CLICK_RELEASE coerce MOVE to DRAG
// when not between CLICK_DOWN and CLICK_RELEASE coerce DRAG to MOVE
if (isMouseDown) {
if (actionType == MouseActionType.MOVE) {
actionType = MouseActionType.DRAG;
}
} else {
if (actionType == MouseActionType.DRAG) {
actionType = MouseActionType.MOVE;
}
}
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TerminalPosition pos = new TerminalPosition( seq.get(4) - 33, seq.get(5) - 33 );
MouseAction ma = new MouseAction(actionType, button, pos );
return new Matching( ma ); // yep
| 170
| 699
| 869
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/input/NormalCharacterPattern.java
|
NormalCharacterPattern
|
match
|
class NormalCharacterPattern implements CharacterPattern {
@Override
public Matching match(List<Character> seq) {<FILL_FUNCTION_BODY>}
/**
* From http://stackoverflow.com/questions/220547/printable-char-in-java
* @param c character to test
* @return True if this is a 'normal', printable character, false otherwise
*/
private static boolean isPrintableChar(char c) {
if (Character.isISOControl(c)) { return false; }
Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
return block != null && block != Character.UnicodeBlock.SPECIALS;
}
}
|
if (seq.size() != 1) {
return null; // nope
}
char ch = seq.get(0);
if (isPrintableChar(ch)) {
KeyStroke ks = new KeyStroke(ch, false, false);
return new Matching( ks );
} else {
return null; // nope
}
| 181
| 96
| 277
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/input/ScreenInfoCharacterPattern.java
|
ScreenInfoCharacterPattern
|
tryToAdopt
|
class ScreenInfoCharacterPattern extends EscapeSequenceCharacterPattern {
public ScreenInfoCharacterPattern() {
useEscEsc = false; // stdMap and finMap don't matter here.
}
protected KeyStroke getKeyStrokeRaw(char first,int num1,int num2,char last,boolean bEsc) {
if (first != '[' || last != 'R' || num1 == 0 || num2 == 0 || bEsc) {
return null; // nope
}
if (num1 == 1 && num2 <= 8) {
return null; // nope: much more likely it's an F3 with modifiers
}
TerminalPosition pos = new TerminalPosition(num2, num1);
return new ScreenInfoAction(pos); // yep
}
public static ScreenInfoAction tryToAdopt(KeyStroke ks) {<FILL_FUNCTION_BODY>}
}
|
if(ks == null) {
return null;
}
switch (ks.getKeyType()) {
case CURSOR_LOCATION: return (ScreenInfoAction)ks;
case F3: // reconstruct position from F3's modifiers.
if (ks instanceof KeyStroke.RealF3) { return null; }
int col = 1 + (ks.isAltDown() ? ALT : 0)
+ (ks.isCtrlDown() ? CTRL : 0)
+ (ks.isShiftDown()? SHIFT: 0);
TerminalPosition pos = new TerminalPosition(col,1);
return new ScreenInfoAction(pos);
default: return null;
}
| 225
| 180
| 405
|
<methods>public void <init>() ,public com.googlecode.lanterna.input.CharacterPattern.Matching match(List<java.lang.Character>) <variables>public static final int ALT,public static final int CTRL,public static final int SHIFT,protected final Map<java.lang.Character,com.googlecode.lanterna.input.KeyType> finMap,protected final Map<java.lang.Integer,com.googlecode.lanterna.input.KeyType> stdMap,protected boolean useEscEsc
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/screen/AbstractScreen.java
|
AbstractScreen
|
setCursorPosition
|
class AbstractScreen implements Screen {
private TerminalPosition cursorPosition;
private ScreenBuffer backBuffer;
private ScreenBuffer frontBuffer;
private final TextCharacter defaultCharacter;
//How to deal with \t characters
private TabBehaviour tabBehaviour;
//Current size of the screen
private TerminalSize terminalSize;
//Pending resize of the screen
private TerminalSize latestResizeRequest;
public AbstractScreen(TerminalSize initialSize) {
this(initialSize, DEFAULT_CHARACTER);
}
/**
* Creates a new Screen on top of a supplied terminal, will query the terminal for its size. The screen is initially
* blank. You can specify which character you wish to be used to fill the screen initially; this will also be the
* character used if the terminal is enlarged and you don't set anything on the new areas.
*
* @param initialSize Size to initially create the Screen with (can be resized later)
* @param defaultCharacter What character to use for the initial state of the screen and expanded areas
*/
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public AbstractScreen(TerminalSize initialSize, TextCharacter defaultCharacter) {
this.frontBuffer = new ScreenBuffer(initialSize, defaultCharacter);
this.backBuffer = new ScreenBuffer(initialSize, defaultCharacter);
this.defaultCharacter = defaultCharacter;
this.cursorPosition = new TerminalPosition(0, 0);
this.tabBehaviour = TabBehaviour.ALIGN_TO_COLUMN_4;
this.terminalSize = initialSize;
this.latestResizeRequest = null;
}
/**
* @return Position where the cursor will be located after the screen has been refreshed or {@code null} if the
* cursor is not visible
*/
@Override
public TerminalPosition getCursorPosition() {
return cursorPosition;
}
/**
* Moves the current cursor position or hides it. If the cursor is hidden and given a new position, it will be
* visible after this method call.
*
* @param position 0-indexed column and row numbers of the new position, or if {@code null}, hides the cursor
*/
@Override
public void setCursorPosition(TerminalPosition position) {<FILL_FUNCTION_BODY>}
@Override
public void setTabBehaviour(TabBehaviour tabBehaviour) {
if(tabBehaviour != null) {
this.tabBehaviour = tabBehaviour;
}
}
@Override
public TabBehaviour getTabBehaviour() {
return tabBehaviour;
}
@Override
public void setCharacter(TerminalPosition position, TextCharacter screenCharacter) {
setCharacter(position.getColumn(), position.getRow(), screenCharacter);
}
@Override
public TextGraphics newTextGraphics() {
return new ScreenTextGraphics(this) {
@Override
public TextGraphics drawImage(TerminalPosition topLeft, TextImage image, TerminalPosition sourceImageTopLeft, TerminalSize sourceImageSize) {
backBuffer.copyFrom(image, sourceImageTopLeft.getRow(), sourceImageSize.getRows(), sourceImageTopLeft.getColumn(), sourceImageSize.getColumns(), topLeft.getRow(), topLeft.getColumn());
return this;
}
};
}
@Override
public synchronized void setCharacter(int column, int row, TextCharacter screenCharacter) {
//It would be nice if we didn't have to care about tabs at this level, but we have no such luxury
if(screenCharacter.is('\t')) {
//Swap out the tab for a space
screenCharacter = screenCharacter.withCharacter(' ');
//Now see how many times we have to put spaces...
for(int i = 0; i < tabBehaviour.replaceTabs("\t", column).length(); i++) {
backBuffer.setCharacterAt(column + i, row, screenCharacter);
}
}
else {
//This is the normal case, no special character
backBuffer.setCharacterAt(column, row, screenCharacter);
}
}
@Override
public synchronized TextCharacter getFrontCharacter(TerminalPosition position) {
return getFrontCharacter(position.getColumn(), position.getRow());
}
@Override
public TextCharacter getFrontCharacter(int column, int row) {
return getCharacterFromBuffer(frontBuffer, column, row);
}
@Override
public synchronized TextCharacter getBackCharacter(TerminalPosition position) {
return getBackCharacter(position.getColumn(), position.getRow());
}
@Override
public TextCharacter getBackCharacter(int column, int row) {
return getCharacterFromBuffer(backBuffer, column, row);
}
@Override
public void refresh() throws IOException {
refresh(RefreshType.AUTOMATIC);
}
@Override
public void close() throws IOException {
stopScreen();
}
@Override
public synchronized void clear() {
backBuffer.setAll(defaultCharacter);
}
@Override
public synchronized TerminalSize doResizeIfNecessary() {
TerminalSize pendingResize = getAndClearPendingResize();
if(pendingResize == null) {
return null;
}
backBuffer = backBuffer.resize(pendingResize, defaultCharacter);
frontBuffer = frontBuffer.resize(pendingResize, defaultCharacter);
return pendingResize;
}
@Override
public TerminalSize getTerminalSize() {
return terminalSize;
}
/**
* Returns the front buffer connected to this screen, don't use this unless you know what you are doing!
* @return This Screen's front buffer
*/
protected ScreenBuffer getFrontBuffer() {
return frontBuffer;
}
/**
* Returns the back buffer connected to this screen, don't use this unless you know what you are doing!
* @return This Screen's back buffer
*/
protected ScreenBuffer getBackBuffer() {
return backBuffer;
}
private synchronized TerminalSize getAndClearPendingResize() {
if(latestResizeRequest != null) {
terminalSize = latestResizeRequest;
latestResizeRequest = null;
return terminalSize;
}
return null;
}
/**
* Tells this screen that the size has changed and it should, at next opportunity, resize itself and its buffers
* @param newSize New size the 'real' terminal now has
*/
protected void addResizeRequest(TerminalSize newSize) {
latestResizeRequest = newSize;
}
private TextCharacter getCharacterFromBuffer(ScreenBuffer buffer, int column, int row) {
return buffer.getCharacterAt(column, row);
}
@Override
public String toString() {
return getBackBuffer().toString();
}
/**
* Performs the scrolling on its back-buffer.
*/
@Override
public void scrollLines(int firstLine, int lastLine, int distance) {
getBackBuffer().scrollLines(firstLine, lastLine, distance);
}
}
|
if(position == null) {
//Skip any validation checks if we just want to hide the cursor
this.cursorPosition = null;
return;
}
if(position.getColumn() < 0) {
position = position.withColumn(0);
}
if(position.getRow() < 0) {
position = position.withRow(0);
}
if(position.getColumn() >= terminalSize.getColumns()) {
position = position.withColumn(terminalSize.getColumns() - 1);
}
if(position.getRow() >= terminalSize.getRows()) {
position = position.withRow(terminalSize.getRows() - 1);
}
this.cursorPosition = position;
| 1,805
| 184
| 1,989
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/screen/ScreenBuffer.java
|
ScreenBuffer
|
isVeryDifferent
|
class ScreenBuffer implements TextImage {
private final BasicTextImage backend;
/**
* Creates a new ScreenBuffer with a given size and a TextCharacter to initially fill it with
* @param size Size of the buffer
* @param filler What character to set as the initial content of the buffer
*/
public ScreenBuffer(TerminalSize size, TextCharacter filler) {
this(new BasicTextImage(size, filler));
}
private ScreenBuffer(BasicTextImage backend) {
this.backend = backend;
}
@Override
public ScreenBuffer resize(TerminalSize newSize, TextCharacter filler) {
BasicTextImage resizedBackend = backend.resize(newSize, filler);
return new ScreenBuffer(resizedBackend);
}
boolean isVeryDifferent(ScreenBuffer other, int threshold) {<FILL_FUNCTION_BODY>}
///////////////////////////////////////////////////////////////////////////////
// Delegate all TextImage calls (except resize) to the backend BasicTextImage
@Override
public TerminalSize getSize() {
return backend.getSize();
}
@Override
public TextCharacter getCharacterAt(TerminalPosition position) {
return backend.getCharacterAt(position);
}
@Override
public TextCharacter getCharacterAt(int column, int row) {
return backend.getCharacterAt(column, row);
}
@Override
public void setCharacterAt(TerminalPosition position, TextCharacter character) {
backend.setCharacterAt(position, character);
}
@Override
public void setCharacterAt(int column, int row, TextCharacter character) {
backend.setCharacterAt(column, row, character);
}
@Override
public void setAll(TextCharacter character) {
backend.setAll(character);
}
@Override
public TextGraphics newTextGraphics() {
return backend.newTextGraphics();
}
@Override
public void copyTo(TextImage destination) {
if(destination instanceof ScreenBuffer) {
//This will allow the BasicTextImage's copy method to use System.arraycopy (micro-optimization?)
destination = ((ScreenBuffer)destination).backend;
}
backend.copyTo(destination);
}
@Override
public void copyTo(TextImage destination, int startRowIndex, int rows, int startColumnIndex, int columns, int destinationRowOffset, int destinationColumnOffset) {
if(destination instanceof ScreenBuffer) {
//This will allow the BasicTextImage's copy method to use System.arraycopy (micro-optimization?)
destination = ((ScreenBuffer)destination).backend;
}
backend.copyTo(destination, startRowIndex, rows, startColumnIndex, columns, destinationRowOffset, destinationColumnOffset);
}
/**
* Copies the content from a TextImage into this buffer.
* @param source Source to copy content from
* @param startRowIndex Which row in the source image to start copying from
* @param rows How many rows to copy
* @param startColumnIndex Which column in the source image to start copying from
* @param columns How many columns to copy
* @param destinationRowOffset The row offset in this buffer of where to place the copied content
* @param destinationColumnOffset The column offset in this buffer of where to place the copied content
*/
public void copyFrom(TextImage source, int startRowIndex, int rows, int startColumnIndex, int columns, int destinationRowOffset, int destinationColumnOffset) {
source.copyTo(backend, startRowIndex, rows, startColumnIndex, columns, destinationRowOffset, destinationColumnOffset);
}
@Override
public void scrollLines(int firstLine, int lastLine, int distance) {
backend.scrollLines(firstLine, lastLine, distance);
}
@Override
public String toString() {
return backend.toString();
}
}
|
if(!getSize().equals(other.getSize())) {
throw new IllegalArgumentException("Can only call isVeryDifferent comparing two ScreenBuffers of the same size!"
+ " This is probably a bug in Lanterna.");
}
int differences = 0;
for(int y = 0; y < getSize().getRows(); y++) {
for(int x = 0; x < getSize().getColumns(); x++) {
if(!getCharacterAt(x, y).equals(other.getCharacterAt(x, y))) {
if(++differences >= threshold) {
return true;
}
}
}
}
return false;
| 974
| 166
| 1,140
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/screen/ScreenTextGraphics.java
|
ScreenTextGraphics
|
setCharacter
|
class ScreenTextGraphics extends AbstractTextGraphics {
private final Screen screen;
/**
* Creates a new {@code ScreenTextGraphics} targeting the specified screen
* @param screen Screen we are targeting
*/
ScreenTextGraphics(Screen screen) {
super();
this.screen = screen;
}
@Override
public TextGraphics setCharacter(int columnIndex, int rowIndex, TextCharacter textCharacter) {<FILL_FUNCTION_BODY>}
@Override
public TextCharacter getCharacter(int column, int row) {
return screen.getBackCharacter(column, row);
}
@Override
public TerminalSize getSize() {
return screen.getTerminalSize();
}
}
|
//Let the screen do culling
screen.setCharacter(columnIndex, rowIndex, textCharacter);
return this;
| 182
| 34
| 216
|
<methods>public com.googlecode.lanterna.graphics.TextGraphics clearModifiers() ,public transient com.googlecode.lanterna.graphics.TextGraphics disableModifiers(com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics drawImage(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.graphics.TextImage) ,public com.googlecode.lanterna.graphics.TextGraphics drawImage(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.graphics.TextImage, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(int, int, int, int, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(int, int, int, int, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public transient com.googlecode.lanterna.graphics.TextGraphics enableModifiers(com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics fill(char) ,public com.googlecode.lanterna.graphics.TextGraphics fillRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, char) ,public com.googlecode.lanterna.graphics.TextGraphics fillRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics fillTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics fillTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public EnumSet<com.googlecode.lanterna.SGR> getActiveModifiers() ,public com.googlecode.lanterna.TextColor getBackgroundColor() ,public com.googlecode.lanterna.TextCharacter getCharacter(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TextColor getForegroundColor() ,public com.googlecode.lanterna.screen.TabBehaviour getTabBehaviour() ,public com.googlecode.lanterna.graphics.TextGraphics newTextGraphics(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize) throws java.lang.IllegalArgumentException,public synchronized com.googlecode.lanterna.graphics.TextGraphics putCSIStyledString(int, int, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putCSIStyledString(com.googlecode.lanterna.TerminalPosition, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putString(com.googlecode.lanterna.TerminalPosition, java.lang.String) ,public transient com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String, com.googlecode.lanterna.SGR, com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String, Collection<com.googlecode.lanterna.SGR>) ,public transient com.googlecode.lanterna.graphics.TextGraphics putString(com.googlecode.lanterna.TerminalPosition, java.lang.String, com.googlecode.lanterna.SGR, com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics setBackgroundColor(com.googlecode.lanterna.TextColor) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(int, int, char) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics setForegroundColor(com.googlecode.lanterna.TextColor) ,public synchronized com.googlecode.lanterna.graphics.TextGraphics setModifiers(EnumSet<com.googlecode.lanterna.SGR>) ,public com.googlecode.lanterna.graphics.TextGraphics setStyleFrom(StyleSet<?>) ,public com.googlecode.lanterna.graphics.TextGraphics setTabBehaviour(com.googlecode.lanterna.screen.TabBehaviour) <variables>protected final non-sealed EnumSet<com.googlecode.lanterna.SGR> activeModifiers,protected com.googlecode.lanterna.TextColor backgroundColor,protected com.googlecode.lanterna.TextColor foregroundColor,private final non-sealed com.googlecode.lanterna.graphics.ShapeRenderer shapeRenderer,protected com.googlecode.lanterna.screen.TabBehaviour tabBehaviour
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/AbstractTerminal.java
|
AbstractTerminal
|
onResized
|
class AbstractTerminal implements Terminal {
private final List<TerminalResizeListener> resizeListeners;
private TerminalSize lastKnownSize;
protected AbstractTerminal() {
this.resizeListeners = new ArrayList<>();
this.lastKnownSize = null;
}
@Override
public void addResizeListener(TerminalResizeListener listener) {
if (listener != null) {
resizeListeners.add(listener);
}
}
@Override
public void removeResizeListener(TerminalResizeListener listener) {
if (listener != null) {
resizeListeners.remove(listener);
}
}
/**
* Call this method when the terminal has been resized or the initial size of the terminal has been discovered. It
* will trigger all resize listeners, but only if the size has changed from before.
*
* @param columns Number of columns in the new size
* @param rows Number of rows in the new size
*/
protected synchronized void onResized(int columns, int rows) {
onResized(new TerminalSize(columns, rows));
}
/**
* Call this method when the terminal has been resized or the initial size of the terminal has been discovered. It
* will trigger all resize listeners, but only if the size has changed from before.
*
* @param newSize Last discovered terminal size
*/
protected synchronized void onResized(TerminalSize newSize) {<FILL_FUNCTION_BODY>}
@Override
public TextGraphics newTextGraphics() throws IOException {
return new TerminalTextGraphics(this);
}
}
|
if (lastKnownSize == null || !lastKnownSize.equals(newSize)) {
lastKnownSize = newSize;
for (TerminalResizeListener resizeListener : resizeListeners) {
resizeListener.onResized(this, lastKnownSize);
}
}
| 410
| 75
| 485
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/SimpleTerminalResizeListener.java
|
SimpleTerminalResizeListener
|
isTerminalResized
|
class SimpleTerminalResizeListener implements TerminalResizeListener {
boolean wasResized;
TerminalSize lastKnownSize;
/**
* Creates a new SimpleTerminalResizeListener
* @param initialSize Before any resize event, this listener doesn't know the size of the terminal. By supplying a
* value here, you control what getLastKnownSize() will return if invoked before any resize events has reached us.
*/
public SimpleTerminalResizeListener(TerminalSize initialSize) {
this.wasResized = false;
this.lastKnownSize = initialSize;
}
/**
* Checks if the terminal was resized since the last time this method was called. If this is the first time calling
* this method, the result is going to be based on if the terminal has been resized since this listener was attached
* to the Terminal.
*
* @return true if the terminal was resized, false otherwise
*/
public synchronized boolean isTerminalResized() {<FILL_FUNCTION_BODY>}
/**
* Returns the last known size the Terminal is supposed to have.
*
* @return Size of the terminal, as of the last resize update
*/
public TerminalSize getLastKnownSize() {
return lastKnownSize;
}
@Override
public synchronized void onResized(Terminal terminal, TerminalSize newSize) {
this.wasResized = true;
this.lastKnownSize = newSize;
}
}
|
if(wasResized) {
wasResized = false;
return true;
}
else {
return false;
}
| 381
| 40
| 421
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/TerminalTextGraphics.java
|
TerminalTextGraphics
|
fillTriangle
|
class TerminalTextGraphics extends AbstractTextGraphics {
private final Terminal terminal;
private final TerminalSize terminalSize;
private final Map<TerminalPosition, TextCharacter> writeHistory;
private AtomicInteger manageCallStackSize;
private TextCharacter lastCharacter;
private TerminalPosition lastPosition;
TerminalTextGraphics(Terminal terminal) throws IOException {
this.terminal = terminal;
this.terminalSize = terminal.getTerminalSize();
this.manageCallStackSize = new AtomicInteger(0);
this.writeHistory = new HashMap<>();
this.lastCharacter = null;
this.lastPosition = null;
}
@Override
public TextGraphics setCharacter(int columnIndex, int rowIndex, TextCharacter textCharacter) {
return setCharacter(new TerminalPosition(columnIndex, rowIndex), textCharacter);
}
@Override
public synchronized TextGraphics setCharacter(TerminalPosition position, TextCharacter textCharacter) {
try {
if(manageCallStackSize.get() > 0) {
if(lastCharacter == null || !lastCharacter.equals(textCharacter)) {
applyGraphicState(textCharacter);
lastCharacter = textCharacter;
}
if(lastPosition == null || !lastPosition.equals(position)) {
terminal.setCursorPosition(position.getColumn(), position.getRow());
lastPosition = position;
}
}
else {
terminal.setCursorPosition(position.getColumn(), position.getRow());
applyGraphicState(textCharacter);
}
terminal.putString(textCharacter.getCharacterString());
if(manageCallStackSize.get() > 0) {
lastPosition = position.withRelativeColumn(1);
}
writeHistory.put(position, textCharacter);
}
catch(IOException e) {
throw new RuntimeException(e);
}
return this;
}
@Override
public TextCharacter getCharacter(int column, int row) {
return getCharacter(new TerminalPosition(column, row));
}
@Override
public synchronized TextCharacter getCharacter(TerminalPosition position) {
return writeHistory.get(position);
}
private void applyGraphicState(TextCharacter textCharacter) throws IOException {
terminal.resetColorAndSGR();
terminal.setForegroundColor(textCharacter.getForegroundColor());
terminal.setBackgroundColor(textCharacter.getBackgroundColor());
for(SGR sgr: textCharacter.getModifiers()) {
terminal.enableSGR(sgr);
}
}
@Override
public TerminalSize getSize() {
return terminalSize;
}
@Override
public synchronized TextGraphics drawLine(TerminalPosition fromPoint, TerminalPosition toPoint, char character) {
try {
enterAtomic();
super.drawLine(fromPoint, toPoint, character);
return this;
}
finally {
leaveAtomic();
}
}
@Override
public synchronized TextGraphics drawTriangle(TerminalPosition p1, TerminalPosition p2, TerminalPosition p3, char character) {
try {
enterAtomic();
super.drawTriangle(p1, p2, p3, character);
return this;
}
finally {
leaveAtomic();
}
}
@Override
public synchronized TextGraphics fillTriangle(TerminalPosition p1, TerminalPosition p2, TerminalPosition p3, char character) {<FILL_FUNCTION_BODY>}
@Override
public synchronized TextGraphics fillRectangle(TerminalPosition topLeft, TerminalSize size, char character) {
try {
enterAtomic();
super.fillRectangle(topLeft, size, character);
return this;
}
finally {
leaveAtomic();
}
}
@Override
public synchronized TextGraphics drawRectangle(TerminalPosition topLeft, TerminalSize size, char character) {
try {
enterAtomic();
super.drawRectangle(topLeft, size, character);
return this;
}
finally {
leaveAtomic();
}
}
@Override
public synchronized TextGraphics putString(int column, int row, String string) {
try {
enterAtomic();
return super.putString(column, row, string);
}
finally {
leaveAtomic();
}
}
/**
* It's tricky with this implementation because we can't rely on any state in between two calls to setCharacter
* since the caller might modify the terminal's state outside of this writer. However, many calls inside
* TextGraphics will indeed make multiple calls in setCharacter where we know that the state won't change (actually,
* we can't be 100% sure since the caller might create a separate thread and maliciously write directly to the
* terminal while call one of the draw/fill/put methods in here). We could just set the state before writing every
* single character but that would be inefficient. Rather, we keep a counter of if we are inside an 'atomic'
* (meaning we know multiple calls to setCharacter will have the same state). Some drawing methods call other
* drawing methods internally for their implementation so that's why this is implemented with an integer value
* instead of a boolean; when the counter reaches zero we remove the memory of what state the terminal is in.
*/
private void enterAtomic() {
manageCallStackSize.incrementAndGet();
}
private void leaveAtomic() {
if(manageCallStackSize.decrementAndGet() == 0) {
lastPosition = null;
lastCharacter = null;
}
}
}
|
try {
enterAtomic();
super.fillTriangle(p1, p2, p3, character);
return this;
}
finally {
leaveAtomic();
}
| 1,412
| 53
| 1,465
|
<methods>public com.googlecode.lanterna.graphics.TextGraphics clearModifiers() ,public transient com.googlecode.lanterna.graphics.TextGraphics disableModifiers(com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics drawImage(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.graphics.TextImage) ,public com.googlecode.lanterna.graphics.TextGraphics drawImage(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.graphics.TextImage, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(int, int, int, int, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(int, int, int, int, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public transient com.googlecode.lanterna.graphics.TextGraphics enableModifiers(com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics fill(char) ,public com.googlecode.lanterna.graphics.TextGraphics fillRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, char) ,public com.googlecode.lanterna.graphics.TextGraphics fillRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics fillTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics fillTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public EnumSet<com.googlecode.lanterna.SGR> getActiveModifiers() ,public com.googlecode.lanterna.TextColor getBackgroundColor() ,public com.googlecode.lanterna.TextCharacter getCharacter(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TextColor getForegroundColor() ,public com.googlecode.lanterna.screen.TabBehaviour getTabBehaviour() ,public com.googlecode.lanterna.graphics.TextGraphics newTextGraphics(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize) throws java.lang.IllegalArgumentException,public synchronized com.googlecode.lanterna.graphics.TextGraphics putCSIStyledString(int, int, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putCSIStyledString(com.googlecode.lanterna.TerminalPosition, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putString(com.googlecode.lanterna.TerminalPosition, java.lang.String) ,public transient com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String, com.googlecode.lanterna.SGR, com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String, Collection<com.googlecode.lanterna.SGR>) ,public transient com.googlecode.lanterna.graphics.TextGraphics putString(com.googlecode.lanterna.TerminalPosition, java.lang.String, com.googlecode.lanterna.SGR, com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics setBackgroundColor(com.googlecode.lanterna.TextColor) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(int, int, char) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics setForegroundColor(com.googlecode.lanterna.TextColor) ,public synchronized com.googlecode.lanterna.graphics.TextGraphics setModifiers(EnumSet<com.googlecode.lanterna.SGR>) ,public com.googlecode.lanterna.graphics.TextGraphics setStyleFrom(StyleSet<?>) ,public com.googlecode.lanterna.graphics.TextGraphics setTabBehaviour(com.googlecode.lanterna.screen.TabBehaviour) <variables>protected final non-sealed EnumSet<com.googlecode.lanterna.SGR> activeModifiers,protected com.googlecode.lanterna.TextColor backgroundColor,protected com.googlecode.lanterna.TextColor foregroundColor,private final non-sealed com.googlecode.lanterna.graphics.ShapeRenderer shapeRenderer,protected com.googlecode.lanterna.screen.TabBehaviour tabBehaviour
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/ansi/CygwinTerminal.java
|
CygwinTerminal
|
getPseudoTerminalDevice
|
class CygwinTerminal extends UnixLikeTTYTerminal {
private static final String STTY_LOCATION = findProgram("stty.exe");
private static final Pattern STTY_SIZE_PATTERN = Pattern.compile(".*rows ([0-9]+);.*columns ([0-9]+);.*");
private static final String JAVA_LIBRARY_PATH_PROPERTY = "java.library.path";
private static final String CYGWIN_HOME_ENV = "CYGWIN_HOME";
/**
* Creates a new CygwinTerminal based off input and output streams and a character set to use
* @param terminalInput Input stream to read input from
* @param terminalOutput Output stream to write output to
* @param terminalCharset Character set to use when writing to the output stream
* @throws IOException If there was an I/O error when trying to initialize the class and setup the terminal
*/
public CygwinTerminal(
InputStream terminalInput,
OutputStream terminalOutput,
Charset terminalCharset) throws IOException {
super(null,
terminalInput,
terminalOutput,
terminalCharset,
CtrlCBehaviour.TRAP);
}
@Override
protected TerminalSize findTerminalSize() {
try {
String stty = runSTTYCommand("-a");
Matcher matcher = STTY_SIZE_PATTERN.matcher(stty);
if(matcher.matches()) {
return new TerminalSize(Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(1)));
}
else {
return new TerminalSize(80, 24);
}
}
catch(Throwable e) {
return new TerminalSize(80, 24);
}
}
@Override
protected String runSTTYCommand(String... parameters) throws IOException {
List<String> commandLine = new ArrayList<>(Arrays.asList(
findSTTY(),
"-F",
getPseudoTerminalDevice()));
commandLine.addAll(Arrays.asList(parameters));
return exec(commandLine.toArray(new String[0]));
}
@Override
protected void acquire() throws IOException {
super.acquire();
// Placeholder in case we want to add extra stty invocations for Cygwin
}
private String findSTTY() {
return STTY_LOCATION;
}
private String getPseudoTerminalDevice() {<FILL_FUNCTION_BODY>}
private static String findProgram(String programName) {
if (System.getenv(CYGWIN_HOME_ENV) != null) {
File cygwinHomeBinFile = new File(System.getenv(CYGWIN_HOME_ENV) + "/bin", programName);
if (cygwinHomeBinFile.exists()) {
return cygwinHomeBinFile.getAbsolutePath();
}
}
String[] paths = System.getProperty(JAVA_LIBRARY_PATH_PROPERTY).split(";");
for(String path : paths) {
File shBin = new File(path, programName);
if(shBin.exists()) {
return shBin.getAbsolutePath();
}
}
return programName;
}
}
|
//This will only work if you only have one terminal window open, otherwise we'll need to figure out somehow
//which pty to use, which could be very tricky...
return "/dev/pty0";
| 843
| 52
| 895
|
<methods><variables>private java.lang.String sttyStatusToRestore,private final non-sealed java.io.File ttyDev
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/ansi/TelnetProtocol.java
|
TelnetProtocol
|
createName2CodeMap
|
class TelnetProtocol {
public static final byte COMMAND_SUBNEGOTIATION_END = (byte)0xf0; //SE
public static final byte COMMAND_NO_OPERATION = (byte)0xf1; //NOP
public static final byte COMMAND_DATA_MARK = (byte)0xf2; //DM
public static final byte COMMAND_BREAK = (byte)0xf3; //BRK
public static final byte COMMAND_INTERRUPT_PROCESS = (byte)0xf4; //IP
public static final byte COMMAND_ABORT_OUTPUT = (byte)0xf5; //AO
public static final byte COMMAND_ARE_YOU_THERE = (byte)0xf6; //AYT
public static final byte COMMAND_ERASE_CHARACTER = (byte)0xf7; //EC
public static final byte COMMAND_ERASE_LINE = (byte)0xf8; //WL
public static final byte COMMAND_GO_AHEAD = (byte)0xf9; //GA
public static final byte COMMAND_SUBNEGOTIATION = (byte)0xfa; //SB
public static final byte COMMAND_WILL = (byte)0xfb;
public static final byte COMMAND_WONT = (byte)0xfc;
public static final byte COMMAND_DO = (byte)0xfd;
public static final byte COMMAND_DONT = (byte)0xfe;
public static final byte COMMAND_IAC = (byte)0xff;
public static final byte OPTION_TRANSMIT_BINARY = (byte)0x00;
public static final byte OPTION_ECHO = (byte)0x01;
public static final byte OPTION_SUPPRESS_GO_AHEAD = (byte)0x03;
public static final byte OPTION_STATUS = (byte)0x05;
public static final byte OPTION_TIMING_MARK = (byte)0x06;
public static final byte OPTION_NAOCRD = (byte)0x0a;
public static final byte OPTION_NAOHTS = (byte)0x0b;
public static final byte OPTION_NAOHTD = (byte)0x0c;
public static final byte OPTION_NAOFFD = (byte)0x0d;
public static final byte OPTION_NAOVTS = (byte)0x0e;
public static final byte OPTION_NAOVTD = (byte)0x0f;
public static final byte OPTION_NAOLFD = (byte)0x10;
public static final byte OPTION_EXTEND_ASCII = (byte)0x01;
public static final byte OPTION_TERMINAL_TYPE = (byte)0x18;
public static final byte OPTION_NAWS = (byte)0x1f;
public static final byte OPTION_TERMINAL_SPEED = (byte)0x20;
public static final byte OPTION_TOGGLE_FLOW_CONTROL = (byte)0x21;
public static final byte OPTION_LINEMODE = (byte)0x22;
public static final byte OPTION_AUTHENTICATION = (byte)0x25;
public static final Map<String, Byte> NAME_TO_CODE = createName2CodeMap();
public static final Map<Byte, String> CODE_TO_NAME = reverseMap(NAME_TO_CODE);
private static Map<String, Byte> createName2CodeMap() {<FILL_FUNCTION_BODY>}
private static <V,K> Map<V,K> reverseMap(Map<K,V> n2c) {
Map<V, K> result = new HashMap<>();
for (Map.Entry<K, V> e : n2c.entrySet()) {
result.put(e.getValue(), e.getKey());
}
return Collections.unmodifiableMap(result);
}
/** Cannot instantiate. */
private TelnetProtocol() {}
}
|
Map<String, Byte> result = new HashMap<>();
for(Field field: TelnetProtocol.class.getDeclaredFields()) {
if(field.getType() != byte.class || (!field.getName().startsWith("COMMAND_") && !field.getName().startsWith("OPTION_"))) {
continue;
}
try {
String namePart = field.getName().substring(field.getName().indexOf("_") + 1);
result.put(namePart, (Byte)field.get(null));
}
catch(IllegalAccessException | IllegalArgumentException ignored) {
}
}
return Collections.unmodifiableMap(result);
| 1,049
| 170
| 1,219
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/ansi/TelnetTerminal.java
|
TelnetClientIACFilterer
|
parseCommand
|
class TelnetClientIACFilterer extends InputStream {
private final NegotiationState negotiationState;
private final InputStream inputStream;
private final byte[] buffer;
private final byte[] workingBuffer;
private int bytesInBuffer;
private TelnetClientEventListener eventListener;
private Socket socket;
TelnetClientIACFilterer(Socket socket) throws IOException {
this.negotiationState = new NegotiationState();
this.inputStream = socket.getInputStream();
this.buffer = new byte[64 * 1024];
this.workingBuffer = new byte[1024];
this.bytesInBuffer = 0;
this.eventListener = null;
this.socket = socket;
}
private void setEventListener(TelnetClientEventListener eventListener) {
this.eventListener = eventListener;
}
@Override
public int read() {
throw new UnsupportedOperationException("TelnetClientIACFilterer doesn't support .read()");
}
@Override
public void close() throws IOException {
inputStream.close();
}
@Override
public int available() throws IOException {
if(bytesInBuffer > 0) {
return bytesInBuffer;
}
fillBuffer(false);
return Math.abs(bytesInBuffer);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (bytesInBuffer == -1) {
return -1;
}
if(available() == 0) {
// There was nothing in the buffer and the underlying
// stream has nothing available, so do a blocking read
// from the stream.
fillBuffer(true);
}
if(bytesInBuffer <= 0) {
return -1;
}
int bytesToCopy = Math.min(len, bytesInBuffer);
System.arraycopy(buffer, 0, b, off, bytesToCopy);
System.arraycopy(buffer, bytesToCopy, buffer, 0, buffer.length - bytesToCopy);
bytesInBuffer -= bytesToCopy;
return bytesToCopy;
}
private void fillBuffer(boolean block) throws IOException {
int maxFill = Math.min(workingBuffer.length, buffer.length - bytesInBuffer);
int oldTimeout = socket.getSoTimeout();
if (!block) { socket.setSoTimeout(1); }
int readBytes;
try {
readBytes = inputStream.read(workingBuffer, 0, maxFill);
} catch (java.net.SocketTimeoutException ste) {
readBytes = 0;
}
if (!block) { socket.setSoTimeout(oldTimeout); }
if (readBytes == -1) {
bytesInBuffer = -1; return;
}
for(int i = 0; i < readBytes; i++) {
if(workingBuffer[i] == COMMAND_IAC) {
i++;
if(Arrays.asList(COMMAND_DO, COMMAND_DONT, COMMAND_WILL, COMMAND_WONT).contains(workingBuffer[i])) {
parseCommand(workingBuffer, i, readBytes);
++i;
continue;
}
else if(workingBuffer[i] == COMMAND_SUBNEGOTIATION) { //0xFA = SB = Subnegotiation
i += parseSubNegotiation(workingBuffer, ++i, readBytes);
continue;
}
else if(workingBuffer[i] != COMMAND_IAC) { //Double IAC = 255
System.err.println("Unknown Telnet command: " + workingBuffer[i]);
}
}
buffer[bytesInBuffer++] = workingBuffer[i];
}
}
private void parseCommand(byte[] buffer, int position, int max) throws IOException {<FILL_FUNCTION_BODY>}
private int parseSubNegotiation(byte[] buffer, int position, int max) {
int originalPosition = position;
//Read operation
byte operation = buffer[position++];
//Read until [IAC SE]
ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
while(position < max) {
byte read = buffer[position];
if(read != COMMAND_IAC) {
outputBuffer.write(read);
}
else {
if(position + 1 == max) {
throw new IllegalStateException("State error, unexpected end of buffer when reading subnegotiation");
}
position++;
if(buffer[position] == COMMAND_IAC) {
outputBuffer.write(COMMAND_IAC); //Escaped IAC
}
else if(buffer[position] == COMMAND_SUBNEGOTIATION_END) {
parseSubNegotiation(operation, outputBuffer.toByteArray());
return ++position - originalPosition;
}
}
position++;
}
throw new IllegalStateException("State error, unexpected end of buffer when reading subnegotiation, no IAC SE");
}
private void parseSubNegotiation(byte option, byte[] additionalData) {
switch(option) {
case OPTION_NAWS:
eventListener.onResize(
convertTwoBytesToInt2(additionalData[1], additionalData[0]),
convertTwoBytesToInt2(additionalData[3], additionalData[2]));
break;
case OPTION_LINEMODE:
//We don't parse this, as this is a very complicated command :(
//Let's leave it for now, fingers crossed
break;
default:
negotiationState.onUnsupportedSubnegotiation(option, additionalData);
break;
}
}
}
|
if(position + 1 >= max) {
throw new IllegalStateException("State error, we got a command signal from the remote telnet client but "
+ "not enough characters available in the stream");
}
byte command = buffer[position];
byte value = buffer[position + 1];
switch(command) {
case COMMAND_DO:
case COMMAND_DONT:
if(value == OPTION_SUPPRESS_GO_AHEAD) {
negotiationState.suppressGoAhead = (command == COMMAND_DO);
eventListener.requestReply(command == COMMAND_DO, value);
}
else if(value == OPTION_EXTEND_ASCII) {
negotiationState.extendedAscii = (command == COMMAND_DO);
eventListener.requestReply(command == COMMAND_DO, value);
}
else {
negotiationState.onUnsupportedRequestCommand(command == COMMAND_DO, value);
}
break;
case COMMAND_WILL:
case COMMAND_WONT:
if(value == OPTION_ECHO) {
negotiationState.clientEcho = (command == COMMAND_WILL);
}
else if(value == OPTION_LINEMODE) {
negotiationState.clientLineMode0 = (command == COMMAND_WILL);
}
else if(value == OPTION_NAWS) {
negotiationState.clientResizeNotification = (command == COMMAND_WILL);
}
else {
negotiationState.onUnsupportedStateCommand(command == COMMAND_WILL, value);
}
break;
default:
throw new UnsupportedOperationException("No command handler implemented for " + TelnetProtocol.CODE_TO_NAME.get(command));
}
| 1,453
| 465
| 1,918
|
<methods>public void clearScreen() throws java.io.IOException,public void close() throws java.io.IOException,public void deiconify() throws java.io.IOException,public void disableSGR(com.googlecode.lanterna.SGR) throws java.io.IOException,public void enableSGR(com.googlecode.lanterna.SGR) throws java.io.IOException,public void enterPrivateMode() throws java.io.IOException,public void exitPrivateMode() throws java.io.IOException,public synchronized com.googlecode.lanterna.TerminalPosition getCursorPosition() throws java.io.IOException,public final synchronized com.googlecode.lanterna.TerminalSize getTerminalSize() throws java.io.IOException,public void iconify() throws java.io.IOException,public void maximize() throws java.io.IOException,public com.googlecode.lanterna.input.KeyStroke pollInput() throws java.io.IOException,public void popTitle() ,public void pushTitle() ,public com.googlecode.lanterna.input.KeyStroke readInput() throws java.io.IOException,public void resetColorAndSGR() throws java.io.IOException,public void scrollLines(int, int, int) throws java.io.IOException,public void setBackgroundColor(com.googlecode.lanterna.TextColor) throws java.io.IOException,public void setCursorPosition(int, int) throws java.io.IOException,public void setCursorPosition(com.googlecode.lanterna.TerminalPosition) throws java.io.IOException,public void setCursorVisible(boolean) throws java.io.IOException,public void setForegroundColor(com.googlecode.lanterna.TextColor) throws java.io.IOException,public void setMouseCaptureMode(com.googlecode.lanterna.terminal.MouseCaptureMode) throws java.io.IOException,public void setTerminalSize(int, int) throws java.io.IOException,public void setTitle(java.lang.String) throws java.io.IOException,public void unmaximize() throws java.io.IOException<variables>private boolean inPrivateMode,private com.googlecode.lanterna.terminal.MouseCaptureMode mouseCaptureMode,private com.googlecode.lanterna.terminal.MouseCaptureMode requestedMouseCaptureMode
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/ansi/TelnetTerminalServer.java
|
TelnetTerminalServer
|
acceptConnection
|
class TelnetTerminalServer {
private final Charset charset;
private final ServerSocket serverSocket;
/**
* Creates a new TelnetTerminalServer on a specific port
* @param port Port to listen for incoming telnet connections
* @throws IOException If there was an underlying I/O exception
*/
public TelnetTerminalServer(int port) throws IOException {
this(ServerSocketFactory.getDefault(), port);
}
/**
* Creates a new TelnetTerminalServer on a specific port, using a certain character set
* @param port Port to listen for incoming telnet connections
* @param charset Character set to use
* @throws IOException If there was an underlying I/O exception
*/
public TelnetTerminalServer(int port, Charset charset) throws IOException {
this(ServerSocketFactory.getDefault(), port, charset);
}
/**
* Creates a new TelnetTerminalServer on a specific port through a ServerSocketFactory
* @param port Port to listen for incoming telnet connections
* @param serverSocketFactory ServerSocketFactory to use when creating the ServerSocket
* @throws IOException If there was an underlying I/O exception
*/
public TelnetTerminalServer(ServerSocketFactory serverSocketFactory, int port) throws IOException {
this(serverSocketFactory, port, Charset.defaultCharset());
}
/**
* Creates a new TelnetTerminalServer on a specific port through a ServerSocketFactory with a certain Charset
* @param serverSocketFactory ServerSocketFactory to use when creating the ServerSocket
* @param port Port to listen for incoming telnet connections
* @param charset Character set to use
* @throws IOException If there was an underlying I/O exception
*/
public TelnetTerminalServer(ServerSocketFactory serverSocketFactory, int port, Charset charset) throws IOException {
this.serverSocket = serverSocketFactory.createServerSocket(port);
this.charset = charset;
}
/**
* Returns the actual server socket used by this object. Can be used to tweak settings but be careful!
* @return Underlying ServerSocket
*/
public ServerSocket getServerSocket() {
return serverSocket;
}
/**
* Waits for the next client to connect in to our server and returns a Terminal implementation, TelnetTerminal, that
* represents the remote terminal this client is running. The terminal can be used just like any other Terminal, but
* keep in mind that all operations are sent over the network.
* @return TelnetTerminal for the remote client's terminal
* @throws IOException If there was an underlying I/O exception
*/
public TelnetTerminal acceptConnection() throws IOException {<FILL_FUNCTION_BODY>}
/**
* Closes the server socket, accepting no new connection. Any call to acceptConnection() after this will fail.
* @throws IOException If there was an underlying I/O exception
*/
public void close() throws IOException {
serverSocket.close();
}
}
|
Socket clientSocket = serverSocket.accept();
clientSocket.setTcpNoDelay(true);
return new TelnetTerminal(clientSocket, charset);
| 731
| 42
| 773
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/ansi/UnixLikeTTYTerminal.java
|
UnixLikeTTYTerminal
|
keyStrokeSignalsEnabled
|
class UnixLikeTTYTerminal extends UnixLikeTerminal {
private final File ttyDev;
private String sttyStatusToRestore;
/**
* Creates a UnixTerminal using a specified input stream, output stream and character set, with a custom size
* querier instead of using the default one. This way you can override size detection (if you want to force the
* terminal to a fixed size, for example). You also choose how you want ctrl+c key strokes to be handled.
*
* @param ttyDev TTY device file that is representing this terminal session, will be used when calling stty to make
* it operate on this session
* @param terminalInput Input stream to read terminal input from
* @param terminalOutput Output stream to write terminal output to
* @param terminalCharset Character set to use when converting characters to bytes
* @param terminalCtrlCBehaviour Special settings on how the terminal will behave, see {@code UnixTerminalMode} for
* more details
* @throws IOException If there was an I/O error while setting up the terminal
*/
protected UnixLikeTTYTerminal(
File ttyDev,
InputStream terminalInput,
OutputStream terminalOutput,
Charset terminalCharset,
CtrlCBehaviour terminalCtrlCBehaviour) throws IOException {
super(terminalInput,
terminalOutput,
terminalCharset,
terminalCtrlCBehaviour);
this.ttyDev = ttyDev;
// Take ownership of the terminal
realAcquire();
}
@Override
protected void acquire() throws IOException {
// Hack!
}
private void realAcquire() throws IOException {
super.acquire();
}
@Override
protected void registerTerminalResizeListener(final Runnable onResize) throws IOException {
try {
Class<?> signalClass = Class.forName("sun.misc.Signal");
for(Method m : signalClass.getDeclaredMethods()) {
if("handle".equals(m.getName())) {
Object windowResizeHandler = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Class.forName("sun.misc.SignalHandler")}, (proxy, method, args) -> {
if("handle".equals(method.getName())) {
onResize.run();
}
return null;
});
m.invoke(null, signalClass.getConstructor(String.class).newInstance("WINCH"), windowResizeHandler);
}
}
}
catch(Throwable ignore) {
// We're probably running on a non-Sun JVM and there's no way to catch signals without resorting to native
// code integration
}
}
@Override
protected void saveTerminalSettings() throws IOException {
sttyStatusToRestore = runSTTYCommand("-g").trim();
}
@Override
protected void restoreTerminalSettings() throws IOException {
if(sttyStatusToRestore != null) {
runSTTYCommand(sttyStatusToRestore);
}
}
@Override
protected void keyEchoEnabled(boolean enabled) throws IOException {
runSTTYCommand(enabled ? "echo" : "-echo");
}
@Override
protected void canonicalMode(boolean enabled) throws IOException {
runSTTYCommand(enabled ? "icanon" : "-icanon");
if(!enabled) {
runSTTYCommand("min", "1");
}
}
@Override
protected void keyStrokeSignalsEnabled(boolean enabled) throws IOException {<FILL_FUNCTION_BODY>}
protected String runSTTYCommand(String... parameters) throws IOException {
List<String> commandLine = new ArrayList<>(Arrays.asList(
getSTTYCommand()));
commandLine.addAll(Arrays.asList(parameters));
return exec(commandLine.toArray(new String[0]));
}
protected String exec(String... cmd) throws IOException {
ProcessBuilder pb = new ProcessBuilder(cmd);
if (ttyDev != null) {
pb.redirectInput(ProcessBuilder.Redirect.from(ttyDev));
}
Process process = pb.start();
ByteArrayOutputStream stdoutBuffer = new ByteArrayOutputStream();
InputStream stdout = process.getInputStream();
int readByte = stdout.read();
while(readByte >= 0) {
stdoutBuffer.write(readByte);
readByte = stdout.read();
}
ByteArrayInputStream stdoutBufferInputStream = new ByteArrayInputStream(stdoutBuffer.toByteArray());
BufferedReader reader = new BufferedReader(new InputStreamReader(stdoutBufferInputStream));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
return builder.toString();
}
protected String[] getSTTYCommand() {
String sttyOverride = System.getProperty("com.googlecode.lanterna.terminal.UnixTerminal.sttyCommand");
if (sttyOverride != null) {
return new String[] { sttyOverride };
}
else {
// Issue #519: this will hopefully be more portable across linux distributions
// Previously we hard-coded "/bin/stty" here
return new String[] {
"/usr/bin/env",
"stty"
};
}
}
}
|
if(enabled) {
runSTTYCommand("intr", "^C");
}
else {
runSTTYCommand("intr", "undef");
}
| 1,372
| 48
| 1,420
|
<methods>public void close() throws java.io.IOException,public com.googlecode.lanterna.input.KeyStroke pollInput() throws java.io.IOException,public com.googlecode.lanterna.input.KeyStroke readInput() throws java.io.IOException<variables>private boolean acquired,private final non-sealed boolean catchSpecialCharacters,private final non-sealed java.lang.Thread shutdownHook,private final non-sealed com.googlecode.lanterna.terminal.ansi.UnixLikeTerminal.CtrlCBehaviour terminalCtrlCBehaviour
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/ansi/UnixLikeTerminal.java
|
UnixLikeTerminal
|
exitPrivateModeAndRestoreState
|
class UnixLikeTerminal extends ANSITerminal {
/**
* This enum lets you control how Lanterna will handle a ctrl+c keystroke from the user.
*/
public enum CtrlCBehaviour {
/**
* Pressing ctrl+c doesn't kill the application, it will be added to the input queue as any other key stroke
*/
TRAP,
/**
* Pressing ctrl+c will restore the terminal and kill the application as it normally does with terminal
* applications. Lanterna will restore the terminal and then call {@code System.exit(1)} for this.
*/
CTRL_C_KILLS_APPLICATION,
}
private final CtrlCBehaviour terminalCtrlCBehaviour;
private final boolean catchSpecialCharacters;
private final Thread shutdownHook;
private boolean acquired;
protected UnixLikeTerminal(InputStream terminalInput,
OutputStream terminalOutput,
Charset terminalCharset,
CtrlCBehaviour terminalCtrlCBehaviour) throws IOException {
super(terminalInput, terminalOutput, terminalCharset);
this.acquired = false;
String catchSpecialCharactersPropValue = System.getProperty(
"com.googlecode.lanterna.terminal.UnixTerminal.catchSpecialCharacters",
"");
this.catchSpecialCharacters = !"false".equals(catchSpecialCharactersPropValue.trim().toLowerCase());
this.terminalCtrlCBehaviour = terminalCtrlCBehaviour;
shutdownHook = new Thread("Lanterna STTY restore") {
@Override
public void run() {
exitPrivateModeAndRestoreState();
}
};
acquire();
}
/**
* Effectively taking over the terminal and enabling it for Lanterna to use, by turning off echo and canonical mode,
* adding resize listeners and optionally trap unix signals. This should be called automatically by the constructor
* of any end-user class extending from {@link UnixLikeTerminal}
* @throws IOException If there was an I/O error
*/
protected void acquire() throws IOException {
//Make sure to set an initial size
onResized(80, 24);
saveTerminalSettings();
canonicalMode(false);
keyEchoEnabled(false);
if(catchSpecialCharacters) {
keyStrokeSignalsEnabled(false);
}
registerTerminalResizeListener(() -> {
// This will trigger a resize notification as the size will be different than before
try {
getTerminalSize();
}
catch(IOException ignore) {
// Not much to do here, we can't re-throw it
}
});
Runtime.getRuntime().addShutdownHook(shutdownHook);
acquired = true;
}
@Override
public void close() throws IOException {
exitPrivateModeAndRestoreState();
Runtime.getRuntime().removeShutdownHook(shutdownHook);
acquired = false;
super.close();
}
@Override
public KeyStroke pollInput() throws IOException {
//Check if we have ctrl+c coming
KeyStroke key = super.pollInput();
isCtrlC(key);
return key;
}
@Override
public KeyStroke readInput() throws IOException {
//Check if we have ctrl+c coming
KeyStroke key = super.readInput();
isCtrlC(key);
return key;
}
protected CtrlCBehaviour getTerminalCtrlCBehaviour() {
return terminalCtrlCBehaviour;
}
protected abstract void registerTerminalResizeListener(Runnable onResize) throws IOException;
/**
* Stores the current terminal device settings (the ones that are modified through this interface) so that they can
* be restored later using {@link #restoreTerminalSettings()}
* @throws IOException If there was an I/O error when altering the terminal environment
*/
protected abstract void saveTerminalSettings() throws IOException;
/**
* Restores the terminal settings from last time {@link #saveTerminalSettings()} was called
* @throws IOException If there was an I/O error when altering the terminal environment
*/
protected abstract void restoreTerminalSettings() throws IOException;
private void restoreTerminalSettingsAndKeyStrokeSignals() throws IOException {
restoreTerminalSettings();
if(catchSpecialCharacters) {
keyStrokeSignalsEnabled(true);
}
}
/**
* Enables or disable key echo mode, which means when the user press a key, the terminal will immediately print that
* key to the terminal. Normally for Lanterna, this should be turned off so the software can take the key as an
* input event, put it on the input queue and then depending on the code decide what to do with it.
* @param enabled {@code true} if key echo should be enabled, {@code false} otherwise
* @throws IOException If there was an I/O error when altering the terminal environment
*/
protected abstract void keyEchoEnabled(boolean enabled) throws IOException;
/**
* In canonical mode, data are accumulated in a line editing buffer, and do not become "available for reading" until
* line editing has been terminated by the user sending a line delimiter character. This is usually the default mode
* for a terminal. Lanterna wants to read each character as they are typed, without waiting for the final newline,
* so it will attempt to turn canonical mode off on initialization.
* @param enabled {@code true} if canonical input mode should be enabled, {@code false} otherwise
* @throws IOException If there was an I/O error when altering the terminal environment
*/
protected abstract void canonicalMode(boolean enabled) throws IOException;
/**
* This method causes certain keystrokes (at the moment only ctrl+c) to be passed in to the program as a regular
* {@link com.googlecode.lanterna.input.KeyStroke} instead of as a signal to the JVM process. For example,
* <i>ctrl+c</i> will normally send an interrupt that causes the JVM to shut down, but this method will make it pass
* in <i>ctrl+c</i> as a regular {@link com.googlecode.lanterna.input.KeyStroke} instead. You can of course still
* make <i>ctrl+c</i> kill the application through your own input handling if you like.
* <p>
* Please note that this method is called automatically by lanterna to disable signals unless you define a system
* property "com.googlecode.lanterna.terminal.UnixTerminal.catchSpecialCharacters" and set it to the string "false".
* @param enabled Pass in {@code true} if you want keystrokes to generate system signals (like process interrupt),
* {@code false} if you want lanterna to catch and interpret these keystrokes are regular keystrokes
* @throws IOException If there was an I/O error when attempting to disable special characters
* @see UnixLikeTTYTerminal.CtrlCBehaviour
*/
protected abstract void keyStrokeSignalsEnabled(boolean enabled) throws IOException;
private void isCtrlC(KeyStroke key) throws IOException {
if(key != null
&& terminalCtrlCBehaviour == CtrlCBehaviour.CTRL_C_KILLS_APPLICATION
&& key.getCharacter() != null
&& key.getCharacter() == 'c'
&& !key.isAltDown()
&& key.isCtrlDown()) {
if (isInPrivateMode()) {
exitPrivateMode();
}
System.exit(1);
}
}
private void exitPrivateModeAndRestoreState() {<FILL_FUNCTION_BODY>}
}
|
if(!acquired) {
return;
}
try {
if (isInPrivateMode()) {
exitPrivateMode();
}
}
catch(IOException | IllegalStateException ignored) {}
try {
restoreTerminalSettingsAndKeyStrokeSignals();
}
catch(IOException ignored) {}
| 1,924
| 85
| 2,009
|
<methods>public void clearScreen() throws java.io.IOException,public void close() throws java.io.IOException,public void deiconify() throws java.io.IOException,public void disableSGR(com.googlecode.lanterna.SGR) throws java.io.IOException,public void enableSGR(com.googlecode.lanterna.SGR) throws java.io.IOException,public void enterPrivateMode() throws java.io.IOException,public void exitPrivateMode() throws java.io.IOException,public synchronized com.googlecode.lanterna.TerminalPosition getCursorPosition() throws java.io.IOException,public final synchronized com.googlecode.lanterna.TerminalSize getTerminalSize() throws java.io.IOException,public void iconify() throws java.io.IOException,public void maximize() throws java.io.IOException,public com.googlecode.lanterna.input.KeyStroke pollInput() throws java.io.IOException,public void popTitle() ,public void pushTitle() ,public com.googlecode.lanterna.input.KeyStroke readInput() throws java.io.IOException,public void resetColorAndSGR() throws java.io.IOException,public void scrollLines(int, int, int) throws java.io.IOException,public void setBackgroundColor(com.googlecode.lanterna.TextColor) throws java.io.IOException,public void setCursorPosition(int, int) throws java.io.IOException,public void setCursorPosition(com.googlecode.lanterna.TerminalPosition) throws java.io.IOException,public void setCursorVisible(boolean) throws java.io.IOException,public void setForegroundColor(com.googlecode.lanterna.TextColor) throws java.io.IOException,public void setMouseCaptureMode(com.googlecode.lanterna.terminal.MouseCaptureMode) throws java.io.IOException,public void setTerminalSize(int, int) throws java.io.IOException,public void setTitle(java.lang.String) throws java.io.IOException,public void unmaximize() throws java.io.IOException<variables>private boolean inPrivateMode,private com.googlecode.lanterna.terminal.MouseCaptureMode mouseCaptureMode,private com.googlecode.lanterna.terminal.MouseCaptureMode requestedMouseCaptureMode
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/swing/AWTTerminalImplementation.java
|
AWTTerminalImplementation
|
readInput
|
class AWTTerminalImplementation extends GraphicalTerminalImplementation {
private final Component component;
private final AWTTerminalFontConfiguration fontConfiguration;
/**
* Creates a new {@code AWTTerminalImplementation}
* @param component Component that is the AWT terminal surface
* @param fontConfiguration Font configuration to use
* @param initialTerminalSize Initial size of the terminal
* @param deviceConfiguration Device configuration
* @param colorConfiguration Color configuration
* @param scrollController Controller to be used when inspecting scroll status
*/
AWTTerminalImplementation(
Component component,
AWTTerminalFontConfiguration fontConfiguration,
TerminalSize initialTerminalSize,
TerminalEmulatorDeviceConfiguration deviceConfiguration,
TerminalEmulatorColorConfiguration colorConfiguration,
TerminalScrollController scrollController) {
super(initialTerminalSize, deviceConfiguration, colorConfiguration, scrollController);
this.component = component;
this.fontConfiguration = fontConfiguration;
//Prevent us from shrinking beyond one character
component.setMinimumSize(new Dimension(fontConfiguration.getFontWidth(), fontConfiguration.getFontHeight()));
component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.<AWTKeyStroke>emptySet());
component.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, Collections.<AWTKeyStroke>emptySet());
component.addKeyListener(new TerminalInputListener());
component.addMouseListener(new TerminalMouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
AWTTerminalImplementation.this.component.requestFocusInWindow();
}
});
component.addHierarchyListener(e -> {
if(e.getChangeFlags() == HierarchyEvent.DISPLAYABILITY_CHANGED) {
if(e.getChanged().isDisplayable()) {
onCreated();
}
else {
onDestroyed();
}
}
});
}
public AWTTerminalFontConfiguration getFontConfiguration() {
return fontConfiguration;
}
@Override
protected int getFontHeight() {
return fontConfiguration.getFontHeight();
}
@Override
protected int getFontWidth() {
return fontConfiguration.getFontWidth();
}
@Override
protected int getHeight() {
return component.getHeight();
}
@Override
protected int getWidth() {
return component.getWidth();
}
@Override
protected Font getFontForCharacter(TextCharacter character) {
return fontConfiguration.getFontForCharacter(character);
}
@Override
protected boolean isTextAntiAliased() {
return fontConfiguration.isAntiAliased();
}
@Override
protected void repaint() {
if(EventQueue.isDispatchThread()) {
component.repaint();
}
else {
EventQueue.invokeLater(component::repaint);
}
}
@Override
public KeyStroke readInput() {<FILL_FUNCTION_BODY>}
}
|
if(EventQueue.isDispatchThread()) {
throw new UnsupportedOperationException("Cannot call SwingTerminal.readInput() on the AWT thread");
}
return super.readInput();
| 813
| 53
| 866
|
<methods>public void addResizeListener(com.googlecode.lanterna.terminal.TerminalResizeListener) ,public void bell() ,public synchronized void clearScreen() ,public void close() ,public void disableSGR(com.googlecode.lanterna.SGR) ,public void enableSGR(com.googlecode.lanterna.SGR) ,public byte[] enquireTerminal(int, java.util.concurrent.TimeUnit) ,public synchronized void enterPrivateMode() ,public synchronized void exitPrivateMode() ,public synchronized void flush() ,public com.googlecode.lanterna.TerminalPosition getCursorPosition() ,public synchronized com.googlecode.lanterna.TerminalSize getTerminalSize() ,public com.googlecode.lanterna.graphics.TextGraphics newTextGraphics() ,public com.googlecode.lanterna.input.KeyStroke pollInput() ,public synchronized void putCharacter(char) ,public void putString(java.lang.String) ,public com.googlecode.lanterna.input.KeyStroke readInput() ,public void removeResizeListener(com.googlecode.lanterna.terminal.TerminalResizeListener) ,public void resetColorAndSGR() ,public void setBackgroundColor(com.googlecode.lanterna.TextColor) ,public synchronized void setCursorPosition(int, int) ,public synchronized void setCursorPosition(com.googlecode.lanterna.TerminalPosition) ,public void setCursorVisible(boolean) ,public void setForegroundColor(com.googlecode.lanterna.TextColor) <variables>private static final Set<java.lang.Character> TYPED_KEYS_TO_IGNORE,private java.awt.image.BufferedImage backbuffer,private boolean bellOn,private boolean blinkOn,private java.util.Timer blinkTimer,private final non-sealed com.googlecode.lanterna.terminal.swing.TerminalEmulatorColorConfiguration colorConfiguration,private java.awt.image.BufferedImage copybuffer,private boolean cursorIsVisible,private final non-sealed com.googlecode.lanterna.terminal.swing.TerminalEmulatorDeviceConfiguration deviceConfiguration,private final non-sealed com.googlecode.lanterna.terminal.swing.GraphicalTerminalImplementation.DirtyCellsLookupTable dirtyCellsLookupTable,private boolean enableInput,private final non-sealed java.lang.String enquiryString,private boolean hasBlinkingText,private final non-sealed BlockingQueue<com.googlecode.lanterna.input.KeyStroke> keyQueue,private int lastBufferUpdateScrollPosition,private int lastComponentHeight,private int lastComponentWidth,private com.googlecode.lanterna.TerminalPosition lastDrawnCursorPosition,private boolean needFullRedraw,private final non-sealed com.googlecode.lanterna.terminal.swing.TerminalScrollController scrollController,private final non-sealed com.googlecode.lanterna.terminal.virtual.DefaultVirtualTerminal virtualTerminal
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/swing/ScrollingAWTTerminal.java
|
ScrollController
|
updateModel
|
class ScrollController implements TerminalScrollController {
private int scrollValue;
@Override
public void updateModel(final int totalSize, final int screenHeight) {<FILL_FUNCTION_BODY>}
@Override
public int getScrollingOffset() {
return scrollValue;
}
}
|
if(!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(() -> updateModel(totalSize, screenHeight));
return;
}
try {
scrollModelUpdateBySystem = true;
int value = scrollBar.getValue();
int maximum = scrollBar.getMaximum();
int visibleAmount = scrollBar.getVisibleAmount();
if(maximum != totalSize) {
int lastMaximum = maximum;
maximum = totalSize > screenHeight ? totalSize : screenHeight;
if(lastMaximum < maximum &&
lastMaximum - visibleAmount - value == 0) {
value = scrollBar.getValue() + (maximum - lastMaximum);
}
}
if(value + screenHeight > maximum) {
value = maximum - screenHeight;
}
if(visibleAmount != screenHeight) {
if(visibleAmount > screenHeight) {
value += visibleAmount - screenHeight;
}
visibleAmount = screenHeight;
}
if(value > maximum - visibleAmount) {
value = maximum - visibleAmount;
}
if(value < 0) {
value = 0;
}
this.scrollValue = value;
if(scrollBar.getMaximum() != maximum) {
scrollBar.setMaximum(maximum);
}
if(scrollBar.getVisibleAmount() != visibleAmount) {
scrollBar.setVisibleAmount(visibleAmount);
}
if(scrollBar.getValue() != value) {
scrollBar.setValue(value);
}
}
finally {
scrollModelUpdateBySystem = false;
}
| 79
| 412
| 491
|
<methods>public void <init>() ,public java.awt.Component add(java.awt.Component) ,public java.awt.Component add(java.lang.String, java.awt.Component) ,public java.awt.Component add(java.awt.Component, int) ,public void add(java.awt.Component, java.lang.Object) ,public void add(java.awt.Component, java.lang.Object, int) ,public synchronized void addContainerListener(java.awt.event.ContainerListener) ,public void addNotify() ,public void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public void addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) ,public void applyComponentOrientation(java.awt.ComponentOrientation) ,public boolean areFocusTraversalKeysSet(int) ,public int countComponents() ,public void deliverEvent(java.awt.Event) ,public void doLayout() ,public java.awt.Component findComponentAt(java.awt.Point) ,public java.awt.Component findComponentAt(int, int) ,public float getAlignmentX() ,public float getAlignmentY() ,public java.awt.Component getComponent(int) ,public java.awt.Component getComponentAt(java.awt.Point) ,public java.awt.Component getComponentAt(int, int) ,public int getComponentCount() ,public int getComponentZOrder(java.awt.Component) ,public java.awt.Component[] getComponents() ,public synchronized java.awt.event.ContainerListener[] getContainerListeners() ,public Set<java.awt.AWTKeyStroke> getFocusTraversalKeys(int) ,public java.awt.FocusTraversalPolicy getFocusTraversalPolicy() ,public java.awt.Insets getInsets() ,public java.awt.LayoutManager getLayout() ,public T[] getListeners(Class<T>) ,public java.awt.Dimension getMaximumSize() ,public java.awt.Dimension getMinimumSize() ,public java.awt.Point getMousePosition(boolean) throws java.awt.HeadlessException,public java.awt.Dimension getPreferredSize() ,public java.awt.Insets insets() ,public void invalidate() ,public boolean isAncestorOf(java.awt.Component) ,public boolean isFocusCycleRoot() ,public boolean isFocusCycleRoot(java.awt.Container) ,public final boolean isFocusTraversalPolicyProvider() ,public boolean isFocusTraversalPolicySet() ,public boolean isValidateRoot() ,public void layout() ,public void list(java.io.PrintStream, int) ,public void list(java.io.PrintWriter, int) ,public java.awt.Component locate(int, int) ,public java.awt.Dimension minimumSize() ,public void paint(java.awt.Graphics) ,public void paintComponents(java.awt.Graphics) ,public java.awt.Dimension preferredSize() ,public void print(java.awt.Graphics) ,public void printComponents(java.awt.Graphics) ,public void remove(int) ,public void remove(java.awt.Component) ,public void removeAll() ,public synchronized void removeContainerListener(java.awt.event.ContainerListener) ,public void removeNotify() ,public void setComponentZOrder(java.awt.Component, int) ,public void setFocusCycleRoot(boolean) ,public void setFocusTraversalKeys(int, Set<? extends java.awt.AWTKeyStroke>) ,public void setFocusTraversalPolicy(java.awt.FocusTraversalPolicy) ,public final void setFocusTraversalPolicyProvider(boolean) ,public void setFont(java.awt.Font) ,public void setLayout(java.awt.LayoutManager) ,public void transferFocusDownCycle() ,public void update(java.awt.Graphics) ,public void validate() <variables>private static final java.awt.Component[] EMPTY_ARRAY,static final boolean INCLUDE_SELF,static final boolean SEARCH_HEAVYWEIGHTS,private List<java.awt.Component> component,transient java.awt.event.ContainerListener containerListener,private int containerSerializedDataVersion,private static boolean descendUnconditionallyWhenValidating,transient int descendantsCount,private java.awt.LightweightDispatcher dispatcher,private static final sun.util.logging.PlatformLogger eventLog,private boolean focusCycleRoot,private transient java.awt.FocusTraversalPolicy focusTraversalPolicy,private boolean focusTraversalPolicyProvider,private static final boolean isJavaAwtSmartInvalidate,java.awt.LayoutManager layoutMgr,transient int listeningBoundsChildren,transient int listeningChildren,private static final sun.util.logging.PlatformLogger log,private static final sun.util.logging.PlatformLogger mixingLog,transient sun.awt.AppContext modalAppContext,transient java.awt.Component modalComp,private transient int numOfHWComponents,private transient int numOfLWComponents,transient java.awt.Color preserveBackgroundColor,private transient boolean printing,private transient Set<java.lang.Thread> printingThreads,private static final java.io.ObjectStreamField[] serialPersistentFields,private static final long serialVersionUID
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/swing/ScrollingSwingTerminal.java
|
ScrollController
|
updateModel
|
class ScrollController implements TerminalScrollController {
private int scrollValue;
@Override
public void updateModel(final int totalSize, final int screenHeight) {<FILL_FUNCTION_BODY>}
@Override
public int getScrollingOffset() {
return scrollValue;
}
}
|
if(!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(() -> updateModel(totalSize, screenHeight));
return;
}
try {
scrollModelUpdateBySystem = true;
int value = scrollBar.getValue();
int maximum = scrollBar.getMaximum();
int visibleAmount = scrollBar.getVisibleAmount();
if(maximum != totalSize) {
int lastMaximum = maximum;
maximum = totalSize > screenHeight ? totalSize : screenHeight;
if(lastMaximum < maximum &&
lastMaximum - visibleAmount - value == 0) {
value = scrollBar.getValue() + (maximum - lastMaximum);
}
}
if(value + screenHeight > maximum) {
value = maximum - screenHeight;
}
if(visibleAmount != screenHeight) {
if(visibleAmount > screenHeight) {
value += visibleAmount - screenHeight;
}
visibleAmount = screenHeight;
}
if(value > maximum - visibleAmount) {
value = maximum - visibleAmount;
}
if(value < 0) {
value = 0;
}
this.scrollValue = value;
if(scrollBar.getMaximum() != maximum) {
scrollBar.setMaximum(maximum);
}
if(scrollBar.getVisibleAmount() != visibleAmount) {
scrollBar.setVisibleAmount(visibleAmount);
}
if(scrollBar.getValue() != value) {
scrollBar.setValue(value);
}
}
finally {
scrollModelUpdateBySystem = false;
}
| 79
| 417
| 496
|
<methods>public void <init>() ,public void addAncestorListener(javax.swing.event.AncestorListener) ,public void addNotify() ,public synchronized void addVetoableChangeListener(java.beans.VetoableChangeListener) ,public void computeVisibleRect(java.awt.Rectangle) ,public boolean contains(int, int) ,public javax.swing.JToolTip createToolTip() ,public void disable() ,public void enable() ,public void firePropertyChange(java.lang.String, boolean, boolean) ,public void firePropertyChange(java.lang.String, int, int) ,public void firePropertyChange(java.lang.String, char, char) ,public java.awt.event.ActionListener getActionForKeyStroke(javax.swing.KeyStroke) ,public final javax.swing.ActionMap getActionMap() ,public float getAlignmentX() ,public float getAlignmentY() ,public javax.swing.event.AncestorListener[] getAncestorListeners() ,public boolean getAutoscrolls() ,public int getBaseline(int, int) ,public java.awt.Component.BaselineResizeBehavior getBaselineResizeBehavior() ,public javax.swing.border.Border getBorder() ,public java.awt.Rectangle getBounds(java.awt.Rectangle) ,public final java.lang.Object getClientProperty(java.lang.Object) ,public javax.swing.JPopupMenu getComponentPopupMenu() ,public int getConditionForKeyStroke(javax.swing.KeyStroke) ,public int getDebugGraphicsOptions() ,public static java.util.Locale getDefaultLocale() ,public java.awt.FontMetrics getFontMetrics(java.awt.Font) ,public java.awt.Graphics getGraphics() ,public int getHeight() ,public boolean getInheritsPopupMenu() ,public final javax.swing.InputMap getInputMap() ,public final javax.swing.InputMap getInputMap(int) ,public javax.swing.InputVerifier getInputVerifier() ,public java.awt.Insets getInsets() ,public java.awt.Insets getInsets(java.awt.Insets) ,public T[] getListeners(Class<T>) ,public java.awt.Point getLocation(java.awt.Point) ,public java.awt.Dimension getMaximumSize() ,public java.awt.Dimension getMinimumSize() ,public java.awt.Component getNextFocusableComponent() ,public java.awt.Point getPopupLocation(java.awt.event.MouseEvent) ,public java.awt.Dimension getPreferredSize() ,public javax.swing.KeyStroke[] getRegisteredKeyStrokes() ,public javax.swing.JRootPane getRootPane() ,public java.awt.Dimension getSize(java.awt.Dimension) ,public java.awt.Point getToolTipLocation(java.awt.event.MouseEvent) ,public java.lang.String getToolTipText() ,public java.lang.String getToolTipText(java.awt.event.MouseEvent) ,public java.awt.Container getTopLevelAncestor() ,public javax.swing.TransferHandler getTransferHandler() ,public javax.swing.plaf.ComponentUI getUI() ,public java.lang.String getUIClassID() ,public boolean getVerifyInputWhenFocusTarget() ,public synchronized java.beans.VetoableChangeListener[] getVetoableChangeListeners() ,public java.awt.Rectangle getVisibleRect() ,public int getWidth() ,public int getX() ,public int getY() ,public void grabFocus() ,public void hide() ,public boolean isDoubleBuffered() ,public static boolean isLightweightComponent(java.awt.Component) ,public boolean isManagingFocus() ,public boolean isOpaque() ,public boolean isOptimizedDrawingEnabled() ,public final boolean isPaintingForPrint() ,public boolean isPaintingTile() ,public boolean isRequestFocusEnabled() ,public boolean isValidateRoot() ,public void paint(java.awt.Graphics) ,public void paintImmediately(java.awt.Rectangle) ,public void paintImmediately(int, int, int, int) ,public void print(java.awt.Graphics) ,public void printAll(java.awt.Graphics) ,public final void putClientProperty(java.lang.Object, java.lang.Object) ,public void registerKeyboardAction(java.awt.event.ActionListener, javax.swing.KeyStroke, int) ,public void registerKeyboardAction(java.awt.event.ActionListener, java.lang.String, javax.swing.KeyStroke, int) ,public void removeAncestorListener(javax.swing.event.AncestorListener) ,public void removeNotify() ,public synchronized void removeVetoableChangeListener(java.beans.VetoableChangeListener) ,public void repaint(java.awt.Rectangle) ,public void repaint(long, int, int, int, int) ,public boolean requestDefaultFocus() ,public void requestFocus() ,public boolean requestFocus(boolean) ,public boolean requestFocusInWindow() ,public void resetKeyboardActions() ,public void reshape(int, int, int, int) ,public void revalidate() ,public void scrollRectToVisible(java.awt.Rectangle) ,public final void setActionMap(javax.swing.ActionMap) ,public void setAlignmentX(float) ,public void setAlignmentY(float) ,public void setAutoscrolls(boolean) ,public void setBackground(java.awt.Color) ,public void setBorder(javax.swing.border.Border) ,public void setComponentPopupMenu(javax.swing.JPopupMenu) ,public void setDebugGraphicsOptions(int) ,public static void setDefaultLocale(java.util.Locale) ,public void setDoubleBuffered(boolean) ,public void setEnabled(boolean) ,public void setFocusTraversalKeys(int, Set<? extends java.awt.AWTKeyStroke>) ,public void setFont(java.awt.Font) ,public void setForeground(java.awt.Color) ,public void setInheritsPopupMenu(boolean) ,public final void setInputMap(int, javax.swing.InputMap) ,public void setInputVerifier(javax.swing.InputVerifier) ,public void setMaximumSize(java.awt.Dimension) ,public void setMinimumSize(java.awt.Dimension) ,public void setNextFocusableComponent(java.awt.Component) ,public void setOpaque(boolean) ,public void setPreferredSize(java.awt.Dimension) ,public void setRequestFocusEnabled(boolean) ,public void setToolTipText(java.lang.String) ,public void setTransferHandler(javax.swing.TransferHandler) ,public void setVerifyInputWhenFocusTarget(boolean) ,public void setVisible(boolean) ,public void unregisterKeyboardAction(javax.swing.KeyStroke) ,public void update(java.awt.Graphics) ,public void updateUI() <variables>private static final int ACTIONMAP_CREATED,private static final int ANCESTOR_INPUTMAP_CREATED,private static final int ANCESTOR_USING_BUFFER,private static final int AUTOSCROLLS_SET,private static final int COMPLETELY_OBSCURED,private static final int CREATED_DOUBLE_BUFFER,static boolean DEBUG_GRAPHICS_LOADED,private static final int FOCUS_INPUTMAP_CREATED,private static final int FOCUS_TRAVERSAL_KEYS_BACKWARD_SET,private static final int FOCUS_TRAVERSAL_KEYS_FORWARD_SET,private static final int INHERITS_POPUP_MENU,private static final java.lang.Object INPUT_VERIFIER_SOURCE_KEY,private static final int IS_DOUBLE_BUFFERED,private static final int IS_OPAQUE,private static final int IS_PAINTING_TILE,private static final int IS_PRINTING,private static final int IS_PRINTING_ALL,private static final int IS_REPAINTING,private static final java.lang.String KEYBOARD_BINDINGS_KEY,private static final int KEY_EVENTS_ENABLED,private static final java.lang.String NEXT_FOCUS,private static final int NOT_OBSCURED,private static final int OPAQUE_SET,private static final int PARTIALLY_OBSCURED,private static final int REQUEST_FOCUS_DISABLED,private static final int RESERVED_1,private static final int RESERVED_2,private static final int RESERVED_3,private static final int RESERVED_4,private static final int RESERVED_5,private static final int RESERVED_6,public static final java.lang.String TOOL_TIP_TEXT_KEY,public static final int UNDEFINED_CONDITION,public static final int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,public static final int WHEN_FOCUSED,public static final int WHEN_IN_FOCUSED_WINDOW,private static final java.lang.String WHEN_IN_FOCUSED_WINDOW_BINDINGS,private static final int WIF_INPUTMAP_CREATED,private static final int WRITE_OBJ_COUNTER_FIRST,private static final int WRITE_OBJ_COUNTER_LAST,private transient java.lang.Object aaHint,private javax.swing.ActionMap actionMap,private float alignmentX,private float alignmentY,private javax.swing.InputMap ancestorInputMap,private boolean autoscrolls,private javax.swing.border.Border border,private transient javax.swing.ArrayTable clientProperties,private static java.awt.Component componentObtainingGraphicsFrom,private static java.lang.Object componentObtainingGraphicsFromLock,private static final java.lang.String defaultLocale,private int flags,static final sun.awt.RequestFocusController focusController,private javax.swing.InputMap focusInputMap,private javax.swing.InputVerifier inputVerifier,private boolean isAlignmentXSet,private boolean isAlignmentYSet,private transient java.lang.Object lcdRenderingHint,protected javax.swing.event.EventListenerList listenerList,private static Set<javax.swing.KeyStroke> managingFocusBackwardTraversalKeys,private static Set<javax.swing.KeyStroke> managingFocusForwardTraversalKeys,transient java.awt.Component paintingChild,private javax.swing.JPopupMenu popupMenu,private static final Hashtable<java.io.ObjectInputStream,javax.swing.JComponent.ReadObjectCallback> readObjectCallbacks,private transient java.util.concurrent.atomic.AtomicBoolean revalidateRunnableScheduled,private static List<java.awt.Rectangle> tempRectangles,protected transient javax.swing.plaf.ComponentUI ui,private static final java.lang.String uiClassID,private boolean verifyInputWhenFocusTarget,private java.beans.VetoableChangeSupport vetoableChangeSupport,private javax.swing.ComponentInputMap windowInputMap
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/swing/SwingTerminalImplementation.java
|
SwingTerminalImplementation
|
readInput
|
class SwingTerminalImplementation extends GraphicalTerminalImplementation {
private final JComponent component;
private final SwingTerminalFontConfiguration fontConfiguration;
/**
* Creates a new {@code SwingTerminalImplementation}
* @param component JComponent that is the Swing terminal surface
* @param fontConfiguration Font configuration to use
* @param initialTerminalSize Initial size of the terminal
* @param deviceConfiguration Device configuration
* @param colorConfiguration Color configuration
* @param scrollController Controller to be used when inspecting scroll status
*/
SwingTerminalImplementation(
JComponent component,
SwingTerminalFontConfiguration fontConfiguration,
TerminalSize initialTerminalSize,
TerminalEmulatorDeviceConfiguration deviceConfiguration,
TerminalEmulatorColorConfiguration colorConfiguration,
TerminalScrollController scrollController) {
super(initialTerminalSize, deviceConfiguration, colorConfiguration, scrollController);
this.component = component;
this.fontConfiguration = fontConfiguration;
//Prevent us from shrinking beyond one character
component.setMinimumSize(new Dimension(fontConfiguration.getFontWidth(), fontConfiguration.getFontHeight()));
component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.<AWTKeyStroke>emptySet());
component.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, Collections.<AWTKeyStroke>emptySet());
//Make sure the component is double-buffered to prevent flickering
component.setDoubleBuffered(true);
component.addKeyListener(new TerminalInputListener());
component.addMouseListener(new TerminalMouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
SwingTerminalImplementation.this.component.requestFocusInWindow();
}
});
component.addHierarchyListener(e -> {
if(e.getChangeFlags() == HierarchyEvent.DISPLAYABILITY_CHANGED) {
if(e.getChanged().isDisplayable()) {
onCreated();
}
else {
onDestroyed();
}
}
});
}
/**
* Returns the current font configuration. Note that it is immutable and cannot be changed.
* @return This SwingTerminal's current font configuration
*/
public SwingTerminalFontConfiguration getFontConfiguration() {
return fontConfiguration;
}
@Override
protected int getFontHeight() {
return fontConfiguration.getFontHeight();
}
@Override
protected int getFontWidth() {
return fontConfiguration.getFontWidth();
}
@Override
protected int getHeight() {
return component.getHeight();
}
@Override
protected int getWidth() {
return component.getWidth();
}
@Override
protected Font getFontForCharacter(TextCharacter character) {
return fontConfiguration.getFontForCharacter(character);
}
@Override
protected boolean isTextAntiAliased() {
return fontConfiguration.isAntiAliased();
}
@Override
protected void repaint() {
if(SwingUtilities.isEventDispatchThread()) {
component.repaint();
}
else {
SwingUtilities.invokeLater(component::repaint);
}
}
@Override
public com.googlecode.lanterna.input.KeyStroke readInput() {<FILL_FUNCTION_BODY>}
}
|
if(SwingUtilities.isEventDispatchThread()) {
throw new UnsupportedOperationException("Cannot call SwingTerminal.readInput() on the AWT thread");
}
return super.readInput();
| 895
| 56
| 951
|
<methods>public void addResizeListener(com.googlecode.lanterna.terminal.TerminalResizeListener) ,public void bell() ,public synchronized void clearScreen() ,public void close() ,public void disableSGR(com.googlecode.lanterna.SGR) ,public void enableSGR(com.googlecode.lanterna.SGR) ,public byte[] enquireTerminal(int, java.util.concurrent.TimeUnit) ,public synchronized void enterPrivateMode() ,public synchronized void exitPrivateMode() ,public synchronized void flush() ,public com.googlecode.lanterna.TerminalPosition getCursorPosition() ,public synchronized com.googlecode.lanterna.TerminalSize getTerminalSize() ,public com.googlecode.lanterna.graphics.TextGraphics newTextGraphics() ,public com.googlecode.lanterna.input.KeyStroke pollInput() ,public synchronized void putCharacter(char) ,public void putString(java.lang.String) ,public com.googlecode.lanterna.input.KeyStroke readInput() ,public void removeResizeListener(com.googlecode.lanterna.terminal.TerminalResizeListener) ,public void resetColorAndSGR() ,public void setBackgroundColor(com.googlecode.lanterna.TextColor) ,public synchronized void setCursorPosition(int, int) ,public synchronized void setCursorPosition(com.googlecode.lanterna.TerminalPosition) ,public void setCursorVisible(boolean) ,public void setForegroundColor(com.googlecode.lanterna.TextColor) <variables>private static final Set<java.lang.Character> TYPED_KEYS_TO_IGNORE,private java.awt.image.BufferedImage backbuffer,private boolean bellOn,private boolean blinkOn,private java.util.Timer blinkTimer,private final non-sealed com.googlecode.lanterna.terminal.swing.TerminalEmulatorColorConfiguration colorConfiguration,private java.awt.image.BufferedImage copybuffer,private boolean cursorIsVisible,private final non-sealed com.googlecode.lanterna.terminal.swing.TerminalEmulatorDeviceConfiguration deviceConfiguration,private final non-sealed com.googlecode.lanterna.terminal.swing.GraphicalTerminalImplementation.DirtyCellsLookupTable dirtyCellsLookupTable,private boolean enableInput,private final non-sealed java.lang.String enquiryString,private boolean hasBlinkingText,private final non-sealed BlockingQueue<com.googlecode.lanterna.input.KeyStroke> keyQueue,private int lastBufferUpdateScrollPosition,private int lastComponentHeight,private int lastComponentWidth,private com.googlecode.lanterna.TerminalPosition lastDrawnCursorPosition,private boolean needFullRedraw,private final non-sealed com.googlecode.lanterna.terminal.swing.TerminalScrollController scrollController,private final non-sealed com.googlecode.lanterna.terminal.virtual.DefaultVirtualTerminal virtualTerminal
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/swing/TerminalEmulatorColorConfiguration.java
|
TerminalEmulatorColorConfiguration
|
toAWTColor
|
class TerminalEmulatorColorConfiguration {
/**
* This is the default settings that is used when you create a new SwingTerminal without specifying any color
* configuration. It will use classic VGA colors for the ANSI palette and bright colors on bold text.
* @return A terminal emulator color configuration object with values set to classic VGA palette
*/
public static TerminalEmulatorColorConfiguration getDefault() {
return newInstance(TerminalEmulatorPalette.STANDARD_VGA);
}
/**
* Creates a new color configuration based on a particular palette and with using brighter colors on bold text.
* @param colorPalette Palette to use for this color configuration
* @return The resulting color configuration
*/
@SuppressWarnings("SameParameterValue")
public static TerminalEmulatorColorConfiguration newInstance(TerminalEmulatorPalette colorPalette) {
return new TerminalEmulatorColorConfiguration(colorPalette, true);
}
private final TerminalEmulatorPalette colorPalette;
private final boolean useBrightColorsOnBold;
private TerminalEmulatorColorConfiguration(TerminalEmulatorPalette colorPalette, boolean useBrightColorsOnBold) {
this.colorPalette = colorPalette;
this.useBrightColorsOnBold = useBrightColorsOnBold;
}
/**
* Given a TextColor and a hint as to if the color is to be used as foreground or not and if we currently have
* bold text enabled or not, it returns the closest AWT color that matches this.
* @param color What text color to convert
* @param isForeground Is the color intended to be used as foreground color
* @param inBoldContext Is the color intended to be used for on a character this is bold
* @return The AWT color that represents this text color
* @deprecated This adds a runtime dependency to the java.desktop module which isn't declared in the module
* descriptor of lanterna. If you want to call this method, make sure to add it to your module.
*/
@Deprecated
public Color toAWTColor(TextColor color, boolean isForeground, boolean inBoldContext) {<FILL_FUNCTION_BODY>}
}
|
if(color instanceof TextColor.ANSI) {
return colorPalette.get((TextColor.ANSI)color, isForeground, inBoldContext && useBrightColorsOnBold);
}
return color.toColor();
| 550
| 62
| 612
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/swing/TerminalInputMethodRequests.java
|
TerminalInputMethodRequests
|
getTextLocation
|
class TerminalInputMethodRequests implements InputMethodRequests {
private Component owner;
private GraphicalTerminalImplementation terminalImplementation;
public TerminalInputMethodRequests(Component owner, GraphicalTerminalImplementation terminalImplementation) {
this.owner = owner;
this.terminalImplementation = terminalImplementation;
}
@Override
public Rectangle getTextLocation(TextHitInfo offset) {<FILL_FUNCTION_BODY>}
@Override
public TextHitInfo getLocationOffset(int x, int y) {
return null;
}
@Override
public int getInsertPositionOffset() {
return 0;
}
@Override
public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Override
public int getCommittedTextLength() {
return 0;
}
@Override
public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
@Override
public AttributedCharacterIterator getSelectedText(AttributedCharacterIterator.Attribute[] attributes) {
return null;
}
}
|
Point location = owner.getLocationOnScreen();
TerminalPosition cursorPosition = terminalImplementation.getCursorPosition();
int offsetX = cursorPosition.getColumn() * terminalImplementation.getFontWidth();
int offsetY = cursorPosition.getRow() * terminalImplementation.getFontHeight() + terminalImplementation.getFontHeight();
return new Rectangle(location.x + offsetX, location.y + offsetY, 0, 0);
| 310
| 111
| 421
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/virtual/TextBuffer.java
|
TextBuffer
|
setCharacter
|
class TextBuffer {
private static final TextCharacter DOUBLE_WIDTH_CHAR_PADDING = new TextCharacter(' ');
private final LinkedList<List<TextCharacter>> lines;
TextBuffer() {
this.lines = new LinkedList<>();
newLine();
}
synchronized void newLine() {
lines.add(new ArrayList<>(200));
}
synchronized void removeTopLines(int numberOfLinesToRemove) {
for(int i = 0; i < numberOfLinesToRemove; i++) {
lines.removeFirst();
}
}
synchronized void clear() {
lines.clear();
newLine();
}
ListIterator<List<TextCharacter>> getLinesFrom(int rowNumber) {
return lines.listIterator(rowNumber);
}
synchronized int getLineCount() {
return lines.size();
}
synchronized int setCharacter(int lineNumber, int columnIndex, TextCharacter textCharacter) {<FILL_FUNCTION_BODY>}
synchronized TextCharacter getCharacter(int lineNumber, int columnIndex) {
if(lineNumber < 0 || columnIndex < 0) {
throw new IllegalArgumentException("Illegal argument to TextBuffer.getCharacter(..), lineNumber = " +
lineNumber + ", columnIndex = " + columnIndex);
}
if(lineNumber >= lines.size()) {
return TextCharacter.DEFAULT_CHARACTER;
}
List<TextCharacter> line = lines.get(lineNumber);
if(line.size() <= columnIndex) {
return TextCharacter.DEFAULT_CHARACTER;
}
TextCharacter textCharacter = line.get(columnIndex);
if(textCharacter == DOUBLE_WIDTH_CHAR_PADDING) {
return line.get(columnIndex - 1);
}
return textCharacter;
}
@Override
public String toString() {
StringBuilder bo = new StringBuilder();
for (List<TextCharacter> line : lines) {
StringBuilder b = new StringBuilder();
for (TextCharacter c : line) {
b.append(c.getCharacterString());
}
bo.append(b.toString().replaceFirst("\\s+$", ""));
bo.append('\n');
}
return bo.toString();
}
}
|
if(lineNumber < 0 || columnIndex < 0) {
throw new IllegalArgumentException("Illegal argument to TextBuffer.setCharacter(..), lineNumber = " +
lineNumber + ", columnIndex = " + columnIndex);
}
if(textCharacter == null) {
textCharacter = TextCharacter.DEFAULT_CHARACTER;
}
while(lineNumber >= lines.size()) {
newLine();
}
List<TextCharacter> line = lines.get(lineNumber);
while(line.size() <= columnIndex) {
line.add(TextCharacter.DEFAULT_CHARACTER);
}
// Default
int returnStyle = 0;
// Check if we are overwriting a double-width character, in that case we need to reset the other half
if(line.get(columnIndex).isDoubleWidth()) {
line.set(columnIndex + 1, line.get(columnIndex).withCharacter(' '));
returnStyle = 1; // this character and the one to the right
}
else if(line.get(columnIndex) == DOUBLE_WIDTH_CHAR_PADDING) {
line.set(columnIndex - 1, TextCharacter.DEFAULT_CHARACTER);
returnStyle = 2; // this character and the one to the left
}
line.set(columnIndex, textCharacter);
if(textCharacter.isDoubleWidth()) {
// We don't report this column as dirty (yet), it's implied since a double-width character is reported
setCharacter(lineNumber, columnIndex + 1, DOUBLE_WIDTH_CHAR_PADDING);
}
return returnStyle;
| 590
| 404
| 994
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/virtual/VirtualTerminalTextGraphics.java
|
VirtualTerminalTextGraphics
|
setCharacter
|
class VirtualTerminalTextGraphics extends AbstractTextGraphics {
private final DefaultVirtualTerminal virtualTerminal;
VirtualTerminalTextGraphics(DefaultVirtualTerminal virtualTerminal) {
this.virtualTerminal = virtualTerminal;
}
@Override
public TextGraphics setCharacter(int columnIndex, int rowIndex, TextCharacter textCharacter) {<FILL_FUNCTION_BODY>}
@Override
public TextCharacter getCharacter(TerminalPosition position) {
return virtualTerminal.getCharacter(position);
}
@Override
public TextCharacter getCharacter(int column, int row) {
return getCharacter(new TerminalPosition(column, row));
}
@Override
public TerminalSize getSize() {
return virtualTerminal.getTerminalSize();
}
}
|
TerminalSize size = getSize();
if(columnIndex < 0 || columnIndex >= size.getColumns() ||
rowIndex < 0 || rowIndex >= size.getRows()) {
return this;
}
synchronized(virtualTerminal) {
virtualTerminal.setCursorPosition(new TerminalPosition(columnIndex, rowIndex));
virtualTerminal.putCharacter(textCharacter);
}
return this;
| 198
| 104
| 302
|
<methods>public com.googlecode.lanterna.graphics.TextGraphics clearModifiers() ,public transient com.googlecode.lanterna.graphics.TextGraphics disableModifiers(com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics drawImage(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.graphics.TextImage) ,public com.googlecode.lanterna.graphics.TextGraphics drawImage(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.graphics.TextImage, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(int, int, int, int, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(int, int, int, int, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public transient com.googlecode.lanterna.graphics.TextGraphics enableModifiers(com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics fill(char) ,public com.googlecode.lanterna.graphics.TextGraphics fillRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, char) ,public com.googlecode.lanterna.graphics.TextGraphics fillRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics fillTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics fillTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public EnumSet<com.googlecode.lanterna.SGR> getActiveModifiers() ,public com.googlecode.lanterna.TextColor getBackgroundColor() ,public com.googlecode.lanterna.TextCharacter getCharacter(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TextColor getForegroundColor() ,public com.googlecode.lanterna.screen.TabBehaviour getTabBehaviour() ,public com.googlecode.lanterna.graphics.TextGraphics newTextGraphics(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize) throws java.lang.IllegalArgumentException,public synchronized com.googlecode.lanterna.graphics.TextGraphics putCSIStyledString(int, int, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putCSIStyledString(com.googlecode.lanterna.TerminalPosition, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putString(com.googlecode.lanterna.TerminalPosition, java.lang.String) ,public transient com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String, com.googlecode.lanterna.SGR, com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String, Collection<com.googlecode.lanterna.SGR>) ,public transient com.googlecode.lanterna.graphics.TextGraphics putString(com.googlecode.lanterna.TerminalPosition, java.lang.String, com.googlecode.lanterna.SGR, com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics setBackgroundColor(com.googlecode.lanterna.TextColor) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(int, int, char) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics setForegroundColor(com.googlecode.lanterna.TextColor) ,public synchronized com.googlecode.lanterna.graphics.TextGraphics setModifiers(EnumSet<com.googlecode.lanterna.SGR>) ,public com.googlecode.lanterna.graphics.TextGraphics setStyleFrom(StyleSet<?>) ,public com.googlecode.lanterna.graphics.TextGraphics setTabBehaviour(com.googlecode.lanterna.screen.TabBehaviour) <variables>protected final non-sealed EnumSet<com.googlecode.lanterna.SGR> activeModifiers,protected com.googlecode.lanterna.TextColor backgroundColor,protected com.googlecode.lanterna.TextColor foregroundColor,private final non-sealed com.googlecode.lanterna.graphics.ShapeRenderer shapeRenderer,protected com.googlecode.lanterna.screen.TabBehaviour tabBehaviour
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/win32/WindowsConsoleInputStream.java
|
WindowsConsoleInputStream
|
available
|
class WindowsConsoleInputStream extends InputStream {
private final HANDLE hConsoleInput;
private final Charset encoderCharset;
private ByteBuffer buffer = ByteBuffer.allocate(0);
public WindowsConsoleInputStream(Charset encoderCharset) {
this(Wincon.INSTANCE.GetStdHandle(Wincon.STD_INPUT_HANDLE), encoderCharset);
}
public WindowsConsoleInputStream(HANDLE hConsoleInput, Charset encoderCharset) {
this.hConsoleInput = hConsoleInput;
this.encoderCharset = encoderCharset;
}
public HANDLE getHandle() {
return hConsoleInput;
}
public Charset getEncoderCharset() {
return encoderCharset;
}
private INPUT_RECORD[] readConsoleInput() throws IOException {
INPUT_RECORD[] lpBuffer = new INPUT_RECORD[64];
IntByReference lpNumberOfEventsRead = new IntByReference();
if (Wincon.INSTANCE.ReadConsoleInput(hConsoleInput, lpBuffer, lpBuffer.length, lpNumberOfEventsRead)) {
int n = lpNumberOfEventsRead.getValue();
return Arrays.copyOfRange(lpBuffer, 0, n);
}
throw new EOFException();
}
private int availableConsoleInput() {
IntByReference lpcNumberOfEvents = new IntByReference();
if (Wincon.INSTANCE.GetNumberOfConsoleInputEvents(hConsoleInput, lpcNumberOfEvents)) {
return lpcNumberOfEvents.getValue();
}
return 0;
}
@Override
public synchronized int read() throws IOException {
while (!buffer.hasRemaining()) {
buffer = readKeyEvents(true);
}
return buffer.get();
}
@Override
public synchronized int read(byte[] b, int offset, int length) throws IOException {
while (length > 0 && !buffer.hasRemaining()) {
buffer = readKeyEvents(true);
}
int n = Math.min(buffer.remaining(), length);
buffer.get(b, offset, n);
return n;
}
@Override
public synchronized int available() throws IOException {<FILL_FUNCTION_BODY>}
private ByteBuffer readKeyEvents(boolean blocking) throws IOException {
StringBuilder keyEvents = new StringBuilder();
if (blocking || availableConsoleInput() > 0) {
for (INPUT_RECORD i : readConsoleInput()) {
filter(i, keyEvents);
}
}
return encoderCharset.encode(CharBuffer.wrap(keyEvents));
}
private void filter(INPUT_RECORD input, Appendable keyEvents) throws IOException {
switch (input.EventType) {
case INPUT_RECORD.KEY_EVENT:
if (input.Event.KeyEvent.uChar != 0 && input.Event.KeyEvent.bKeyDown) {
keyEvents.append(input.Event.KeyEvent.uChar);
}
if (keyEventHandler != null) {
keyEventHandler.accept(input.Event.KeyEvent);
}
break;
case INPUT_RECORD.MOUSE_EVENT:
if (mouseEventHandler != null) {
mouseEventHandler.accept(input.Event.MouseEvent);
}
break;
case INPUT_RECORD.WINDOW_BUFFER_SIZE_EVENT:
if (windowBufferSizeEventHandler != null) {
windowBufferSizeEventHandler.accept(input.Event.WindowBufferSizeEvent);
}
break;
}
}
private Consumer<KEY_EVENT_RECORD> keyEventHandler = null;
private Consumer<MOUSE_EVENT_RECORD> mouseEventHandler = null;
private Consumer<WINDOW_BUFFER_SIZE_RECORD> windowBufferSizeEventHandler = null;
public void onKeyEvent(Consumer<KEY_EVENT_RECORD> handler) {
if (keyEventHandler == null) {
keyEventHandler = handler;
} else {
keyEventHandler = keyEventHandler.andThen(handler);
}
}
public void onMouseEvent(Consumer<MOUSE_EVENT_RECORD> handler) {
if (mouseEventHandler == null) {
mouseEventHandler = handler;
} else {
mouseEventHandler = mouseEventHandler.andThen(handler);
}
}
public void onWindowBufferSizeEvent(Consumer<WINDOW_BUFFER_SIZE_RECORD> handler) {
if (windowBufferSizeEventHandler == null) {
windowBufferSizeEventHandler = handler;
} else {
windowBufferSizeEventHandler = windowBufferSizeEventHandler.andThen(handler);
}
}
}
|
if (buffer.hasRemaining()) {
return buffer.remaining();
}
buffer = readKeyEvents(false);
return buffer.remaining();
| 1,196
| 45
| 1,241
|
<methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public byte[] readAllBytes() throws java.io.IOException,public byte[] readNBytes(int) throws java.io.IOException,public int readNBytes(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public void skipNBytes(long) throws java.io.IOException,public long transferTo(java.io.OutputStream) throws java.io.IOException<variables>private static final int DEFAULT_BUFFER_SIZE,private static final int MAX_BUFFER_SIZE,private static final int MAX_SKIP_BUFFER_SIZE
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/win32/WindowsConsoleOutputStream.java
|
WindowsConsoleOutputStream
|
flush
|
class WindowsConsoleOutputStream extends OutputStream {
private final HANDLE hConsoleOutput;
private final Charset decoderCharset;
private final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
public WindowsConsoleOutputStream(Charset decoder) {
this(Wincon.INSTANCE.GetStdHandle(Wincon.STD_OUTPUT_HANDLE), decoder);
}
public WindowsConsoleOutputStream(HANDLE hConsoleOutput, Charset decoderCharset) {
this.hConsoleOutput = hConsoleOutput;
this.decoderCharset = decoderCharset;
}
public HANDLE getHandle() {
return hConsoleOutput;
}
public Charset getDecoderCharset() {
return decoderCharset;
}
@Override
public synchronized void write(int b) {
buffer.write(b);
}
@Override
public synchronized void write(byte[] b, int off, int len) {
buffer.write(b, off, len);
}
@Override
public synchronized void flush() throws IOException {<FILL_FUNCTION_BODY>}
}
|
String characters = buffer.toString(decoderCharset.name());
buffer.reset();
IntByReference lpNumberOfCharsWritten = new IntByReference();
while (!characters.isEmpty()) {
if (!Wincon.INSTANCE.WriteConsole(hConsoleOutput, characters, characters.length(), lpNumberOfCharsWritten, null)) {
throw new EOFException();
}
characters = characters.substring(lpNumberOfCharsWritten.getValue());
}
| 273
| 129
| 402
|
<methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/terminal/win32/WindowsTerminal.java
|
WindowsTerminal
|
canonicalMode
|
class WindowsTerminal extends UnixLikeTerminal {
private static final Charset CONSOLE_CHARSET = StandardCharsets.UTF_8;
private static final WindowsConsoleInputStream CONSOLE_INPUT = new WindowsConsoleInputStream(CONSOLE_CHARSET);
private static final WindowsConsoleOutputStream CONSOLE_OUTPUT = new WindowsConsoleOutputStream(CONSOLE_CHARSET);
private int[] settings;
public WindowsTerminal() throws IOException {
this(CONSOLE_INPUT, CONSOLE_OUTPUT, CONSOLE_CHARSET, CtrlCBehaviour.CTRL_C_KILLS_APPLICATION);
}
public WindowsTerminal(InputStream terminalInput, OutputStream terminalOutput, Charset terminalCharset, CtrlCBehaviour terminalCtrlCBehaviour) throws IOException {
super(CONSOLE_INPUT, CONSOLE_OUTPUT, CONSOLE_CHARSET, terminalCtrlCBehaviour);
// handle resize events
CONSOLE_INPUT.onWindowBufferSizeEvent(evt -> {
onResized(evt.dwSize.X, evt.dwSize.Y);
});
}
@Override
protected KeyDecodingProfile getDefaultKeyDecodingProfile() {
ArrayList<CharacterPattern> keyDecodingProfile = new ArrayList<CharacterPattern>();
// handle Key Code 13 as ENTER
keyDecodingProfile.add(new BasicCharacterPattern(new KeyStroke(KeyType.ENTER), '\r'));
// handle everything else as per default
keyDecodingProfile.addAll(super.getDefaultKeyDecodingProfile().getPatterns());
return () -> keyDecodingProfile;
}
@Override
protected void acquire() throws IOException {
super.acquire();
int terminalOutputMode = getConsoleOutputMode();
terminalOutputMode |= Wincon.ENABLE_VIRTUAL_TERMINAL_PROCESSING;
terminalOutputMode |= Wincon.DISABLE_NEWLINE_AUTO_RETURN;
Wincon.INSTANCE.SetConsoleMode(CONSOLE_OUTPUT.getHandle(), terminalOutputMode);
int terminalInputMode = getConsoleInputMode();
terminalInputMode |= Wincon.ENABLE_MOUSE_INPUT;
terminalInputMode |= Wincon.ENABLE_WINDOW_INPUT;
terminalInputMode |= Wincon.ENABLE_VIRTUAL_TERMINAL_INPUT;
Wincon.INSTANCE.SetConsoleMode(CONSOLE_INPUT.getHandle(), terminalInputMode);
}
@Override
public void saveTerminalSettings() {
settings = new int[] { getConsoleInputMode(), getConsoleOutputMode() };
}
@Override
public void restoreTerminalSettings() {
if (settings != null) {
Wincon.INSTANCE.SetConsoleMode(CONSOLE_INPUT.getHandle(), settings[0]);
Wincon.INSTANCE.SetConsoleMode(CONSOLE_OUTPUT.getHandle(), settings[1]);
}
}
@Override
public void keyEchoEnabled(boolean enabled) {
int mode = getConsoleInputMode();
if (enabled) {
mode |= Wincon.ENABLE_ECHO_INPUT;
} else {
mode &= ~Wincon.ENABLE_ECHO_INPUT;
}
Wincon.INSTANCE.SetConsoleMode(CONSOLE_INPUT.getHandle(), mode);
}
@Override
public void canonicalMode(boolean enabled) {<FILL_FUNCTION_BODY>}
@Override
public void keyStrokeSignalsEnabled(boolean enabled) {
int mode = getConsoleInputMode();
if (enabled) {
mode |= Wincon.ENABLE_PROCESSED_INPUT;
} else {
mode &= ~Wincon.ENABLE_PROCESSED_INPUT;
}
Wincon.INSTANCE.SetConsoleMode(CONSOLE_INPUT.getHandle(), mode);
}
@Override
protected TerminalSize findTerminalSize() {
CONSOLE_SCREEN_BUFFER_INFO screenBufferInfo = new CONSOLE_SCREEN_BUFFER_INFO();
Wincon.INSTANCE.GetConsoleScreenBufferInfo(CONSOLE_OUTPUT.getHandle(), screenBufferInfo);
int columns = screenBufferInfo.srWindow.Right - screenBufferInfo.srWindow.Left + 1;
int rows = screenBufferInfo.srWindow.Bottom - screenBufferInfo.srWindow.Top + 1;
return new TerminalSize(columns, rows);
}
@Override
public void registerTerminalResizeListener(Runnable runnable) {
// ignore
}
public TerminalPosition getCursorPosition() {
CONSOLE_SCREEN_BUFFER_INFO screenBufferInfo = new CONSOLE_SCREEN_BUFFER_INFO();
Wincon.INSTANCE.GetConsoleScreenBufferInfo(CONSOLE_OUTPUT.getHandle(), screenBufferInfo);
int column = screenBufferInfo.dwCursorPosition.X - screenBufferInfo.srWindow.Left;
int row = screenBufferInfo.dwCursorPosition.Y - screenBufferInfo.srWindow.Top;
return new TerminalPosition(column, row);
}
private int getConsoleInputMode() {
IntByReference lpMode = new IntByReference();
Wincon.INSTANCE.GetConsoleMode(CONSOLE_INPUT.getHandle(), lpMode);
return lpMode.getValue();
}
private int getConsoleOutputMode() {
IntByReference lpMode = new IntByReference();
Wincon.INSTANCE.GetConsoleMode(CONSOLE_OUTPUT.getHandle(), lpMode);
return lpMode.getValue();
}
}
|
int mode = getConsoleInputMode();
if (enabled) {
mode |= Wincon.ENABLE_LINE_INPUT;
} else {
mode &= ~Wincon.ENABLE_LINE_INPUT;
}
Wincon.INSTANCE.SetConsoleMode(CONSOLE_INPUT.getHandle(), mode);
| 1,402
| 85
| 1,487
|
<methods>public void close() throws java.io.IOException,public com.googlecode.lanterna.input.KeyStroke pollInput() throws java.io.IOException,public com.googlecode.lanterna.input.KeyStroke readInput() throws java.io.IOException<variables>private boolean acquired,private final non-sealed boolean catchSpecialCharacters,private final non-sealed java.lang.Thread shutdownHook,private final non-sealed com.googlecode.lanterna.terminal.ansi.UnixLikeTerminal.CtrlCBehaviour terminalCtrlCBehaviour
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/AclSetuserArgs.java
|
AddCommand
|
build
|
class AddCommand implements Argument {
private final CommandSubcommandPair command;
AddCommand(CommandSubcommandPair command) {
this.command = command;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>}
}
|
if (command.getSubCommand() == null) {
args.add("+" + command.getCommand().name());
} else {
args.add("+" + command.getCommand().name() + "|" + command.getSubCommand().name());
}
| 85
| 70
| 155
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ChannelGroupListener.java
|
ChannelGroupListener
|
getRedisUri
|
class ChannelGroupListener extends ChannelInboundHandlerAdapter {
private final ChannelGroup channels;
private final EventBus eventBus;
public ChannelGroupListener(ChannelGroup channels, EventBus eventBus) {
this.channels = channels;
this.eventBus = eventBus;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
CommandHandler commandHandler = getCommandHandler(ctx);
String epid = commandHandler.getEndpoint().getId();
eventBus.publish(
new ConnectedEvent(getRedisUri(ctx.channel()), epid, commandHandler.getChannelId(), local(ctx), remote(ctx)));
channels.add(ctx.channel());
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
CommandHandler commandHandler = getCommandHandler(ctx);
String epid = commandHandler.getEndpoint().getId();
eventBus.publish(new DisconnectedEvent(getRedisUri(ctx.channel()), epid, commandHandler.getChannelId(), local(ctx),
remote(ctx)));
channels.remove(ctx.channel());
super.channelInactive(ctx);
}
private static String getRedisUri(Channel channel) {<FILL_FUNCTION_BODY>}
private static CommandHandler getCommandHandler(ChannelHandlerContext ctx) {
return ctx.pipeline().get(CommandHandler.class);
}
}
|
String redisUri = null;
if (channel.hasAttr(ConnectionBuilder.REDIS_URI)) {
redisUri = channel.attr(ConnectionBuilder.REDIS_URI).get();
}
return redisUri;
| 359
| 62
| 421
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ClientListArgs.java
|
Builder
|
type
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link ClientListArgs} setting {@literal client-id}.
*
* @param id client ids.
* @return new {@link ClientListArgs} with {@literal client-id} set.
* @see ClientListArgs#ids(long...)
*/
public static ClientListArgs ids(long... id) {
return new ClientListArgs().ids(id);
}
/**
* Creates new {@link ClientListArgs} setting {@literal TYPE PUBSUB}.
*
* @return new {@link ClientListArgs} with {@literal TYPE PUBSUB} set.
* @see ClientListArgs#type(Type)
*/
public static ClientListArgs typePubsub() {
return new ClientListArgs().type(Type.PUBSUB);
}
/**
* Creates new {@link ClientListArgs} setting {@literal TYPE NORMAL}.
*
* @return new {@link ClientListArgs} with {@literal TYPE NORMAL} set.
* @see ClientListArgs#type(Type)
*/
public static ClientListArgs typeNormal() {
return new ClientListArgs().type(Type.NORMAL);
}
/**
* Creates new {@link ClientListArgs} setting {@literal TYPE MASTER}.
*
* @return new {@link ClientListArgs} with {@literal TYPE MASTER} set.
* @see ClientListArgs#type(Type)
*/
public static ClientListArgs typeMaster() {
return new ClientListArgs().type(Type.MASTER);
}
/**
* Creates new {@link ClientListArgs} setting {@literal TYPE REPLICA}.
*
* @return new {@link ClientListArgs} with {@literal TYPE REPLICA} set.
* @see ClientListArgs#type(Type)
*/
public static ClientListArgs typeReplica() {
return new ClientListArgs().type(Type.REPLICA);
}
}
/**
* Filter the clients with its client {@code ids}.
*
* @param ids client ids
* @return {@code this} {@link ClientListArgs}.
*/
public ClientListArgs ids(long... ids) {
LettuceAssert.notNull(ids, "Ids must not be null");
this.ids = new ArrayList<>(ids.length);
for (long id : ids) {
this.ids.add(id);
}
return this;
}
/**
* This filters the connections of all the clients in the specified {@link ClientListArgs.Type}. Note that clients blocked
* into the {@literal MONITOR} command are considered to belong to the normal class.
*
* @param type must not be {@code null}.
* @return {@code this} {@link ClientListArgs}.
*/
public ClientListArgs type(Type type) {<FILL_FUNCTION_BODY>
|
LettuceAssert.notNull(type, "Type must not be null");
this.type = type;
return this;
| 764
| 37
| 801
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/CommandListenerWriter.java
|
CommandListenerWriter
|
write
|
class CommandListenerWriter implements RedisChannelWriter {
private final RedisChannelWriter delegate;
private final CommandListener listener;
private final Clock clock = Clock.systemDefaultZone();
public CommandListenerWriter(RedisChannelWriter delegate, List<CommandListener> listeners) {
this.delegate = delegate;
this.listener = new CommandListenerMulticaster(new ArrayList<>(listeners));
}
/**
* Check whether the list of {@link CommandListener} is not empty.
*
* @param commandListeners must not be {@code null}.
* @return {@code true} if the list of {@link CommandListener} is not empty.
*/
public static boolean isSupported(List<CommandListener> commandListeners) {
LettuceAssert.notNull(commandListeners, "CommandListeners must not be null");
return !commandListeners.isEmpty();
}
@Override
public <K, V, T> RedisCommand<K, V, T> write(RedisCommand<K, V, T> command) {
long now = clock.millis();
CommandStartedEvent startedEvent = new CommandStartedEvent((RedisCommand<Object, Object, Object>) command, now);
listener.commandStarted(startedEvent);
return delegate.write(new RedisCommandListenerCommand<>(command, clock, startedEvent.getContext(), now, listener));
}
@Override
public <K, V> Collection<RedisCommand<K, V, ?>> write(Collection<? extends RedisCommand<K, V, ?>> redisCommands) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
delegate.close();
}
@Override
public CompletableFuture<Void> closeAsync() {
return delegate.closeAsync();
}
@Override
@SuppressWarnings("deprecation")
public void reset() {
delegate.reset();
}
@Override
public void setConnectionFacade(ConnectionFacade connection) {
delegate.setConnectionFacade(connection);
}
@Override
public void setAutoFlushCommands(boolean autoFlush) {
delegate.setAutoFlushCommands(autoFlush);
}
@Override
public void flushCommands() {
delegate.flushCommands();
}
@Override
public ClientResources getClientResources() {
return delegate.getClientResources();
}
public RedisChannelWriter getDelegate() {
return this.delegate;
}
private static class RedisCommandListenerCommand<K, V, T> extends CommandWrapper<K, V, T> {
private final Clock clock;
private final Map<String, Object> context;
private final long startedAt;
private final CommandListener listener;
public RedisCommandListenerCommand(RedisCommand<K, V, T> command, Clock clock, Map<String, Object> context,
long startedAt, CommandListener listener) {
super(command);
this.clock = clock;
this.context = context;
this.startedAt = startedAt;
this.listener = listener;
}
@Override
protected void doOnComplete() {
if (getOutput().hasError()) {
CommandFailedEvent failedEvent = new CommandFailedEvent((RedisCommand<Object, Object, Object>) command, context,
ExceptionFactory.createExecutionException(getOutput().getError()));
listener.commandFailed(failedEvent);
} else {
long now = clock.millis();
CommandSucceededEvent succeededEvent = new CommandSucceededEvent((RedisCommand<Object, Object, Object>) command,
context, startedAt, now);
listener.commandSucceeded(succeededEvent);
}
}
@Override
protected void doOnError(Throwable throwable) {
CommandFailedEvent failedEvent = new CommandFailedEvent((RedisCommand<Object, Object, Object>) command, context,
throwable);
listener.commandFailed(failedEvent);
}
@Override
public void cancel() {
super.cancel();
}
}
/**
* Wraps multiple command listeners into one multicaster.
*
* @author Mikhael Sokolov
* @since 6.1
*/
public static class CommandListenerMulticaster implements CommandListener {
private final List<CommandListener> listeners;
public CommandListenerMulticaster(List<CommandListener> listeners) {
this.listeners = listeners;
}
@Override
public void commandStarted(CommandStartedEvent event) {
for (CommandListener listener : listeners) {
listener.commandStarted(event);
}
}
@Override
public void commandSucceeded(CommandSucceededEvent event) {
for (CommandListener listener : listeners) {
listener.commandSucceeded(event);
}
}
@Override
public void commandFailed(CommandFailedEvent event) {
for (CommandListener listener : listeners) {
listener.commandFailed(event);
}
}
}
}
|
List<RedisCommandListenerCommand<K, V, ?>> listenedCommands = new ArrayList<>();
long now = clock.millis();
for (RedisCommand<K, V, ?> redisCommand : redisCommands) {
CommandStartedEvent startedEvent = new CommandStartedEvent((RedisCommand<Object, Object, Object>) redisCommand,
now);
listener.commandStarted(startedEvent);
RedisCommandListenerCommand<K, V, ?> command = new RedisCommandListenerCommand<>(redisCommand, clock,
startedEvent.getContext(), now, listener);
listenedCommands.add(command);
}
return delegate.write(listenedCommands);
| 1,303
| 178
| 1,481
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ConcurrentLruCache.java
|
ConcurrentLruCache
|
get
|
class ConcurrentLruCache<K, V> {
private final int sizeLimit;
private final Function<K, V> generator;
private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<>();
private final ConcurrentLinkedDeque<K> queue = new ConcurrentLinkedDeque<>();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private volatile int size;
/**
* Create a new cache instance with the given limit and generator function.
*
* @param sizeLimit the maximum number of entries in the cache (0 indicates no caching, always generating a new value)
* @param generator a function to generate a new value for a given key
*/
public ConcurrentLruCache(int sizeLimit, Function<K, V> generator) {
LettuceAssert.isTrue(sizeLimit >= 0, "Cache size limit must not be negative");
LettuceAssert.notNull(generator, "Generator function must not be null");
this.sizeLimit = sizeLimit;
this.generator = generator;
}
/**
* Retrieve an entry from the cache, potentially triggering generation of the value.
*
* @param key the key to retrieve the entry for
* @return the cached or newly generated value
*/
public V get(K key) {<FILL_FUNCTION_BODY>}
/**
* Determine whether the given key is present in this cache.
*
* @param key the key to check for
* @return {@code true} if the key is present, {@code false} if there was no matching key
*/
public boolean contains(K key) {
return this.cache.containsKey(key);
}
/**
* Immediately remove the given key and any associated value.
*
* @param key the key to evict the entry for
* @return {@code true} if the key was present before, {@code false} if there was no matching key
*/
public boolean remove(K key) {
this.lock.writeLock().lock();
try {
boolean wasPresent = (this.cache.remove(key) != null);
this.queue.remove(key);
this.size = this.cache.size();
return wasPresent;
} finally {
this.lock.writeLock().unlock();
}
}
/**
* Immediately remove all entries from this cache.
*/
public void clear() {
this.lock.writeLock().lock();
try {
this.cache.clear();
this.queue.clear();
this.size = 0;
} finally {
this.lock.writeLock().unlock();
}
}
/**
* Return the current size of the cache.
*
* @see #sizeLimit()
*/
public int size() {
return this.size;
}
/**
* Return the maximum number of entries in the cache (0 indicates no caching, always generating a new value).
*
* @see #size()
*/
public int sizeLimit() {
return this.sizeLimit;
}
}
|
if (this.sizeLimit == 0) {
return this.generator.apply(key);
}
V cached = this.cache.get(key);
if (cached != null) {
if (this.size < this.sizeLimit) {
return cached;
}
this.lock.readLock().lock();
try {
if (this.queue.removeLastOccurrence(key)) {
this.queue.offer(key);
}
return cached;
} finally {
this.lock.readLock().unlock();
}
}
this.lock.writeLock().lock();
try {
// Retrying in case of concurrent reads on the same key
cached = this.cache.get(key);
if (cached != null) {
if (this.queue.removeLastOccurrence(key)) {
this.queue.offer(key);
}
return cached;
}
// Generate value first, to prevent size inconsistency
V value = this.generator.apply(key);
if (this.size == this.sizeLimit) {
K leastUsed = this.queue.poll();
if (leastUsed != null) {
this.cache.remove(leastUsed);
}
}
this.queue.offer(key);
this.cache.put(key, value);
this.size = this.cache.size();
return value;
} finally {
this.lock.writeLock().unlock();
}
| 789
| 384
| 1,173
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ConnectionEventTrigger.java
|
ConnectionEventTrigger
|
local
|
class ConnectionEventTrigger extends ChannelInboundHandlerAdapter {
private final ConnectionEvents connectionEvents;
private final RedisChannelHandler<?, ?> connection;
private final EventBus eventBus;
ConnectionEventTrigger(ConnectionEvents connectionEvents, RedisChannelHandler<?, ?> connection, EventBus eventBus) {
this.connectionEvents = connectionEvents;
this.connection = connection;
this.eventBus = eventBus;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
connectionEvents.fireEventRedisConnected(connection, channel.remoteAddress());
CommandHandler commandHandler = getCommandHandler(ctx);
String epid = commandHandler.getEndpoint().getId();
eventBus.publish(new ConnectionActivatedEvent(getRedisUri(channel), epid, commandHandler.getChannelId(), local(ctx),
remote(ctx)));
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
connectionEvents.fireEventRedisDisconnected(connection);
CommandHandler commandHandler = getCommandHandler(ctx);
String epid = commandHandler.getEndpoint().getId();
eventBus.publish(new ConnectionDeactivatedEvent(getRedisUri(ctx.channel()), epid, commandHandler.getChannelId(),
local(ctx), remote(ctx)));
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
connectionEvents.fireEventRedisExceptionCaught(connection, cause);
super.exceptionCaught(ctx, cause);
}
static SocketAddress remote(ChannelHandlerContext ctx) {
if (ctx.channel() != null && ctx.channel().remoteAddress() != null) {
return ctx.channel().remoteAddress();
}
return new LocalAddress("unknown");
}
static SocketAddress local(ChannelHandlerContext ctx) {<FILL_FUNCTION_BODY>}
private static String getRedisUri(Channel channel) {
String redisUri = null;
if (channel.hasAttr(ConnectionBuilder.REDIS_URI)) {
redisUri = channel.attr(ConnectionBuilder.REDIS_URI).get();
}
return redisUri;
}
private static CommandHandler getCommandHandler(ChannelHandlerContext ctx) {
return ctx.pipeline().get(CommandHandler.class);
}
}
|
Channel channel = ctx.channel();
if (channel != null && channel.localAddress() != null) {
return channel.localAddress();
}
return LocalAddress.ANY;
| 617
| 51
| 668
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ConnectionEvents.java
|
ConnectionEvents
|
fireEventRedisConnected
|
class ConnectionEvents {
private final Set<RedisConnectionStateListener> listeners = ConcurrentHashMap.newKeySet();
void fireEventRedisConnected(RedisChannelHandler<?, ?> connection, SocketAddress socketAddress) {<FILL_FUNCTION_BODY>}
void fireEventRedisDisconnected(RedisChannelHandler<?, ?> connection) {
for (RedisConnectionStateListener listener : listeners) {
listener.onRedisDisconnected(connection);
}
}
void fireEventRedisExceptionCaught(RedisChannelHandler<?, ?> connection, Throwable cause) {
for (RedisConnectionStateListener listener : listeners) {
listener.onRedisExceptionCaught(connection, cause);
}
}
public void addListener(RedisConnectionStateListener listener) {
listeners.add(listener);
}
public void removeListener(RedisConnectionStateListener listener) {
listeners.remove(listener);
}
/**
* Internal event when a channel is closed.
*/
public static class Reset {
}
/**
* Internal event when a reconnect is initiated.
*/
public static class Reconnect {
private final int attempt;
public Reconnect(int attempt) {
this.attempt = attempt;
}
public int getAttempt() {
return attempt;
}
}
static ConnectionEvents of(ConnectionEvents... delegates) {
return delegates.length == 1 ? delegates[0] : new MergedConnectionEvents(delegates);
}
static class MergedConnectionEvents extends ConnectionEvents {
private final ConnectionEvents[] delegates;
MergedConnectionEvents(ConnectionEvents[] delegates) {
this.delegates = delegates;
}
@Override
void fireEventRedisConnected(RedisChannelHandler<?, ?> connection, SocketAddress socketAddress) {
for (ConnectionEvents delegate : delegates) {
delegate.fireEventRedisConnected(connection, socketAddress);
}
}
@Override
void fireEventRedisDisconnected(RedisChannelHandler<?, ?> connection) {
for (ConnectionEvents delegate : delegates) {
delegate.fireEventRedisDisconnected(connection);
}
}
@Override
void fireEventRedisExceptionCaught(RedisChannelHandler<?, ?> connection, Throwable cause) {
for (ConnectionEvents delegate : delegates) {
delegate.fireEventRedisExceptionCaught(connection, cause);
}
}
@Override
public void addListener(RedisConnectionStateListener listener) {
throw new UnsupportedOperationException();
}
@Override
public void removeListener(RedisConnectionStateListener listener) {
throw new UnsupportedOperationException();
}
}
}
|
for (RedisConnectionStateListener listener : listeners) {
listener.onRedisConnected(connection, socketAddress);
}
| 715
| 35
| 750
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ConnectionState.java
|
ConnectionState
|
setUserNamePassword
|
class ConnectionState {
private volatile HandshakeResponse handshakeResponse;
private volatile RedisCredentialsProvider credentialsProvider;
private volatile int db;
private volatile boolean readOnly;
private volatile ConnectionMetadata connectionMetadata = new ConnectionMetadata();
/**
* Applies settings from {@link RedisURI}.
*
* @param redisURI the URI to apply the client name and authentication.
*/
public void apply(RedisURI redisURI) {
connectionMetadata.apply(redisURI);
setCredentialsProvider(redisURI.getCredentialsProvider());
}
void apply(ConnectionMetadata metadata) {
this.connectionMetadata.apply(metadata);
}
ConnectionMetadata getConnectionMetadata() {
return connectionMetadata;
}
/**
* Returns the negotiated {@link ProtocolVersion}.
*
* @return the negotiated {@link ProtocolVersion} once the connection is established.
*/
public ProtocolVersion getNegotiatedProtocolVersion() {
return handshakeResponse != null ? handshakeResponse.getNegotiatedProtocolVersion() : null;
}
/**
* Returns the client connection id. Only available when using {@link ProtocolVersion#RESP3}.
*
* @return the client connection id. Can be {@code null} if Redis uses RESP2.
*/
public Long getConnectionId() {
return handshakeResponse != null ? handshakeResponse.getConnectionId() : null;
}
/**
* Returns the Redis server version. Only available when using {@link ProtocolVersion#RESP3}.
*
* @return the Redis server version.
*/
public String getRedisVersion() {
return handshakeResponse != null ? handshakeResponse.getRedisVersion() : null;
}
/**
* Returns the Redis server mode. Only available when using {@link ProtocolVersion#RESP3}.
*
* @return the Redis server mode.
*/
public String getMode() {
return handshakeResponse != null ? handshakeResponse.getMode() : null;
}
/**
* Returns the Redis server role. Only available when using {@link ProtocolVersion#RESP3}.
*
* @return the Redis server role.
*/
public String getRole() {
return handshakeResponse != null ? handshakeResponse.getRole() : null;
}
void setHandshakeResponse(HandshakeResponse handshakeResponse) {
this.handshakeResponse = handshakeResponse;
}
/**
* Sets username/password state based on the argument count from an {@code AUTH} command.
*
* @param args
*/
protected void setUserNamePassword(List<char[]> args) {<FILL_FUNCTION_BODY>}
protected void setCredentialsProvider(RedisCredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
}
public RedisCredentialsProvider getCredentialsProvider() {
return credentialsProvider;
}
protected void setDb(int db) {
this.db = db;
}
int getDb() {
return db;
}
protected void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
boolean isReadOnly() {
return readOnly;
}
protected void setClientName(String clientName) {
this.connectionMetadata.setClientName(clientName);
}
String getClientName() {
return connectionMetadata.getClientName();
}
/**
* HELLO Handshake response.
*/
static class HandshakeResponse {
private final ProtocolVersion negotiatedProtocolVersion;
private final Long connectionId;
private final String redisVersion;
private final String mode;
private final String role;
public HandshakeResponse(ProtocolVersion negotiatedProtocolVersion, Long connectionId, String redisVersion, String mode,
String role) {
this.negotiatedProtocolVersion = negotiatedProtocolVersion;
this.connectionId = connectionId;
this.redisVersion = redisVersion;
this.role = role;
this.mode = mode;
}
public ProtocolVersion getNegotiatedProtocolVersion() {
return negotiatedProtocolVersion;
}
public Long getConnectionId() {
return connectionId;
}
public String getRedisVersion() {
return redisVersion;
}
public String getMode() {
return mode;
}
public String getRole() {
return role;
}
}
}
|
if (args.isEmpty()) {
return;
}
if (args.size() > 1) {
this.credentialsProvider = new StaticCredentialsProvider(new String(args.get(0)), args.get(1));
} else {
this.credentialsProvider = new StaticCredentialsProvider(null, args.get(0));
}
| 1,179
| 94
| 1,273
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/Consumer.java
|
Consumer
|
from
|
class Consumer<K> {
final K group;
final K name;
private Consumer(K group, K name) {
this.group = group;
this.name = name;
}
/**
* Create a new consumer.
*
* @param group name of the consumer group, must not be {@code null} or empty.
* @param name name of the consumer, must not be {@code null} or empty.
* @return the consumer {@link Consumer} object.
*/
public static <K> Consumer<K> from(K group, K name) {<FILL_FUNCTION_BODY>}
/**
* @return name of the group.
*/
public K getGroup() {
return group;
}
/**
* @return name of the consumer.
*/
public K getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Consumer))
return false;
Consumer<?> consumer = (Consumer<?>) o;
return Objects.equals(group, consumer.group) && Objects.equals(name, consumer.name);
}
@Override
public int hashCode() {
return Objects.hash(group, name);
}
@Override
public String toString() {
return String.format("%s:%s", group, name);
}
}
|
LettuceAssert.notNull(group, "Group must not be null");
LettuceAssert.notNull(name, "Name must not be null");
return new Consumer<>(group, name);
| 382
| 55
| 437
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/CopyArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link CopyArgs} and sets {@literal DB}.
*
* @return new {@link CopyArgs} with {@literal DB} set.
*/
public static CopyArgs destinationDb(long destinationDb) {
return new CopyArgs().destinationDb(destinationDb);
}
/**
* Creates new {@link CopyArgs} and sets {@literal REPLACE}.
*
* @return new {@link CopyArgs} with {@literal REPLACE} set.
*/
public static CopyArgs replace(boolean replace) {
return new CopyArgs().replace(replace);
}
}
/**
* Specify an alternative logical database index for the destination key.
*
* @param destinationDb logical database index to apply for {@literal DB}.
* @return {@code this}.
*/
public CopyArgs destinationDb(long destinationDb) {
this.destinationDb = destinationDb;
return this;
}
/**
* Hint redis to remove the destination key before copying the value to it.
*
* @param replace remove destination key before copying the value {@literal REPLACE}.
* @return {@code this}.
*/
public CopyArgs replace(boolean replace) {
this.replace = replace;
return this;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (destinationDb != null) {
args.add(CommandKeyword.DB).add(destinationDb);
}
if (replace) {
args.add(CommandKeyword.REPLACE);
}
| 386
| 64
| 450
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ExpireArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link ExpireArgs} and sets {@literal NX}.
*
* @return new {@link ExpireArgs} with {@literal NX} set.
*/
public static ExpireArgs nx() {
return new ExpireArgs().nx();
}
/**
* Creates new {@link ExpireArgs} and sets {@literal XX}.
*
* @return new {@link ExpireArgs} with {@literal XX} set.
*/
public static ExpireArgs xx() {
return new ExpireArgs().xx();
}
/**
* Creates new {@link ExpireArgs} and sets {@literal GT}.
*
* @return new {@link ExpireArgs} with {@literal GT} set.
*/
public static ExpireArgs gt() {
return new ExpireArgs().gt();
}
/**
* Creates new {@link ExpireArgs} and sets {@literal LT}.
*
* @return new {@link ExpireArgs} with {@literal LT} set.
*/
public static ExpireArgs lt() {
return new ExpireArgs().lt();
}
}
/**
* Set expiry only when the key has no expiry.
*
* @return {@code this}.
*/
public ExpireArgs nx() {
this.nx = true;
return this;
}
/**
* Set expiry only when the key has an existing expiry.
*
* @return {@code this}.
*/
public ExpireArgs xx() {
this.xx = true;
return this;
}
/**
* Set expiry only when the new expiry is greater than current one.
*
* @return {@code this}.
*/
public ExpireArgs gt() {
this.gt = true;
return this;
}
/**
* Set expiry only when the new expiry is less than current one.
*
* @return {@code this}.
*/
public ExpireArgs lt() {
this.lt = true;
return this;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (xx) {
args.add(CommandKeyword.XX);
} else if (nx) {
args.add(CommandKeyword.NX);
}
if (lt) {
args.add("LT");
} else if (gt) {
args.add("GT");
}
| 614
| 85
| 699
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/FutureSyncInvocationHandler.java
|
FutureSyncInvocationHandler
|
handleInvocation
|
class FutureSyncInvocationHandler extends AbstractInvocationHandler {
private final StatefulConnection<?, ?> connection;
private final TimeoutProvider timeoutProvider;
private final Object asyncApi;
private final MethodTranslator translator;
FutureSyncInvocationHandler(StatefulConnection<?, ?> connection, Object asyncApi, Class<?>[] interfaces) {
this.connection = connection;
this.timeoutProvider = new TimeoutProvider(() -> connection.getOptions().getTimeoutOptions(),
() -> connection.getTimeout().toNanos());
this.asyncApi = asyncApi;
this.translator = MethodTranslator.of(asyncApi.getClass(), interfaces);
}
@Override
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {<FILL_FUNCTION_BODY>}
private long getTimeoutNs(RedisFuture<?> command) {
if (command instanceof RedisCommand) {
return timeoutProvider.getTimeoutNs((RedisCommand) command);
}
return connection.getTimeout().toNanos();
}
private static boolean isTransactionActive(StatefulConnection<?, ?> connection) {
return connection instanceof StatefulRedisConnection && ((StatefulRedisConnection) connection).isMulti();
}
private static boolean isTxControlMethod(String methodName, Object[] args) {
if (methodName.equals("exec") || methodName.equals("multi") || methodName.equals("discard")) {
return true;
}
if (methodName.equals("dispatch") && args.length > 0 && args[0] instanceof ProtocolKeyword) {
ProtocolKeyword keyword = (ProtocolKeyword) args[0];
if (keyword.name().equals(CommandType.MULTI.name()) || keyword.name().equals(CommandType.EXEC.name())
|| keyword.name().equals(CommandType.DISCARD.name())) {
return true;
}
}
return false;
}
}
|
try {
Method targetMethod = this.translator.get(method);
Object result = targetMethod.invoke(asyncApi, args);
if (result instanceof RedisFuture<?>) {
RedisFuture<?> command = (RedisFuture<?>) result;
if (!isTxControlMethod(method.getName(), args) && isTransactionActive(connection)) {
return null;
}
long timeout = getTimeoutNs(command);
return Futures.awaitOrCancel(command, timeout, TimeUnit.NANOSECONDS);
}
return result;
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
| 507
| 180
| 687
|
<methods>public non-sealed void <init>() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public final java.lang.Object invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) throws java.lang.Throwable,public java.lang.String toString() <variables>private static final java.lang.Object[] NO_ARGS
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/GeoAddArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link GeoAddArgs} and enabling {@literal NX}.
*
* @return new {@link GeoAddArgs} with {@literal NX} enabled.
* @see GeoAddArgs#nx()
*/
public static GeoAddArgs nx() {
return new GeoAddArgs().nx();
}
/**
* Creates new {@link GeoAddArgs} and enabling {@literal XX}.
*
* @return new {@link GeoAddArgs} with {@literal XX} enabled.
* @see GeoAddArgs#xx()
*/
public static GeoAddArgs xx() {
return new GeoAddArgs().xx();
}
/**
* Creates new {@link GeoAddArgs} and enabling {@literal CH}.
*
* @return new {@link GeoAddArgs} with {@literal CH} enabled.
* @see GeoAddArgs#ch()
*/
public static GeoAddArgs ch() {
return new GeoAddArgs().ch();
}
}
/**
* Don't update already existing elements. Always add new elements.
*
* @return {@code this} {@link GeoAddArgs}.
*/
public GeoAddArgs nx() {
this.nx = true;
return this;
}
/**
* Only update elements that already exist. Never add elements.
*
* @return {@code this} {@link GeoAddArgs}.
*/
public GeoAddArgs xx() {
this.xx = true;
return this;
}
/**
* Modify the return value from the number of new elements added, to the total number of elements changed.
*
* @return {@code this} {@link GeoAddArgs}.
*/
public GeoAddArgs ch() {
this.ch = true;
return this;
}
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (nx) {
args.add(NX);
}
if (xx) {
args.add(XX);
}
if (ch) {
args.add(CH);
}
| 526
| 62
| 588
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/GeoArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link GeoArgs} with {@literal WITHDIST} enabled.
*
* @return new {@link GeoArgs} with {@literal WITHDIST} enabled.
* @see GeoArgs#withDistance()
*/
public static GeoArgs distance() {
return new GeoArgs().withDistance();
}
/**
* Creates new {@link GeoArgs} with {@literal WITHCOORD} enabled.
*
* @return new {@link GeoArgs} with {@literal WITHCOORD} enabled.
* @see GeoArgs#withCoordinates()
*/
public static GeoArgs coordinates() {
return new GeoArgs().withCoordinates();
}
/**
* Creates new {@link GeoArgs} with {@literal WITHHASH} enabled.
*
* @return new {@link GeoArgs} with {@literal WITHHASH} enabled.
* @see GeoArgs#withHash()
*/
public static GeoArgs hash() {
return new GeoArgs().withHash();
}
/**
* Creates new {@link GeoArgs} with distance, coordinates and hash enabled.
*
* @return new {@link GeoArgs} with {@literal WITHDIST}, {@literal WITHCOORD}, {@literal WITHHASH} enabled.
* @see GeoArgs#withDistance()
* @see GeoArgs#withCoordinates()
* @see GeoArgs#withHash()
*/
public static GeoArgs full() {
return new GeoArgs().withDistance().withCoordinates().withHash();
}
/**
* Creates new {@link GeoArgs} with {@literal COUNT} set.
*
* @param count number greater 0.
* @return new {@link GeoArgs} with {@literal COUNT} set.
* @see GeoArgs#withCount(long)
*/
public static GeoArgs count(long count) {
return new GeoArgs().withCount(count);
}
}
/**
* Request distance for results.
*
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withDistance() {
withdistance = true;
return this;
}
/**
* Request coordinates for results.
*
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withCoordinates() {
withcoordinates = true;
return this;
}
/**
* Request geohash for results.
*
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withHash() {
withhash = true;
return this;
}
/**
* Limit results to {@code count} entries.
*
* @param count number greater 0.
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withCount(long count) {
return withCount(count, false);
}
/**
* Limit results to {@code count} entries.
*
* @param count number greater 0.
* @param any whether to complete the command as soon as enough matches are found, so the results may not be the ones
* closest to the specified point.
* @return {@code this} {@link GeoArgs}.
* @since 6.1
*/
public GeoArgs withCount(long count, boolean any) {
LettuceAssert.isTrue(count > 0, "Count must be greater 0");
this.count = count;
this.any = any;
return this;
}
/**
*
* @return {@code true} if distance is requested.
*/
public boolean isWithDistance() {
return withdistance;
}
/**
*
* @return {@code true} if coordinates are requested.
*/
public boolean isWithCoordinates() {
return withcoordinates;
}
/**
*
* @return {@code true} if geohash is requested.
*/
public boolean isWithHash() {
return withhash;
}
/**
* Sort results ascending.
*
* @return {@code this}
*/
public GeoArgs asc() {
return sort(Sort.asc);
}
/**
* Sort results descending.
*
* @return {@code this}
*/
public GeoArgs desc() {
return sort(Sort.desc);
}
/**
* Sort results.
*
* @param sort sort order, must not be {@code null}
* @return {@code this}
*/
public GeoArgs sort(Sort sort) {
LettuceAssert.notNull(sort, "Sort must not be null");
this.sort = sort;
return this;
}
/**
* Sort order.
*/
public enum Sort {
/**
* ascending.
*/
asc,
/**
* descending.
*/
desc,
/**
* no sort order.
*/
none;
}
/**
* Supported geo unit.
*/
public enum Unit implements ProtocolKeyword {
/**
* meter.
*/
m,
/**
* kilometer.
*/
km,
/**
* feet.
*/
ft,
/**
* mile.
*/
mi;
private final byte[] asBytes;
Unit() {
asBytes = name().getBytes();
}
@Override
public byte[] getBytes() {
return asBytes;
}
}
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (withdistance) {
args.add("WITHDIST");
}
if (withhash) {
args.add("WITHHASH");
}
if (withcoordinates) {
args.add("WITHCOORD");
}
if (sort != null && sort != Sort.none) {
args.add(sort.name());
}
if (count != null) {
args.add(CommandKeyword.COUNT).add(count);
if (any) {
args.add("ANY");
}
}
| 1,484
| 151
| 1,635
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/GeoCoordinates.java
|
GeoCoordinates
|
equals
|
class GeoCoordinates {
private final Number x;
private final Number y;
/**
* Creates new {@link GeoCoordinates}.
*
* @param x the longitude, must not be {@code null}.
* @param y the latitude, must not be {@code null}.
*/
public GeoCoordinates(Number x, Number y) {
LettuceAssert.notNull(x, "X must not be null");
LettuceAssert.notNull(y, "Y must not be null");
this.x = x;
this.y = y;
}
/**
* Creates new {@link GeoCoordinates}.
*
* @param x the longitude, must not be {@code null}.
* @param y the latitude, must not be {@code null}.
* @return {@link GeoCoordinates}.
*/
public static GeoCoordinates create(Number x, Number y) {
return new GeoCoordinates(x, y);
}
/**
*
* @return the longitude.
*/
public Number getX() {
return x;
}
/**
*
* @return the latitude.
*/
public Number getY() {
return y;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = x != null ? x.hashCode() : 0;
result = 31 * result + (y != null ? y.hashCode() : 0);
return result;
}
@Override
public String toString() {
return String.format("(%s, %s)", getX(), getY());
}
}
|
if (this == o)
return true;
if (!(o instanceof GeoCoordinates))
return false;
GeoCoordinates geoCoords = (GeoCoordinates) o;
if (x != null ? !x.equals(geoCoords.x) : geoCoords.x != null)
return false;
return !(y != null ? !y.equals(geoCoords.y) : geoCoords.y != null);
| 449
| 120
| 569
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/GeoRadiusStoreArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link GeoRadiusStoreArgs} with {@literal STORE} enabled.
*
* @param key must not be {@code null}.
* @return new {@link GeoRadiusStoreArgs} with {@literal STORE} enabled.
* @see GeoRadiusStoreArgs#withStore(Object)
*/
public static <K> GeoRadiusStoreArgs store(K key) {
return new GeoRadiusStoreArgs<>().withStore(key);
}
/**
* Creates new {@link GeoRadiusStoreArgs} with {@literal STOREDIST} enabled.
*
* @param key must not be {@code null}.
* @return new {@link GeoRadiusStoreArgs} with {@literal STOREDIST} enabled.
* @see GeoRadiusStoreArgs#withStoreDist(Object)
*/
public static <K> GeoRadiusStoreArgs withStoreDist(K key) {
return new GeoRadiusStoreArgs<>().withStoreDist(key);
}
/**
* Creates new {@link GeoRadiusStoreArgs} with {@literal COUNT} set.
*
* @param count number greater 0.
* @return new {@link GeoRadiusStoreArgs} with {@literal COUNT} set.
* @see GeoRadiusStoreArgs#withStoreDist(Object)
*/
public static <K> GeoRadiusStoreArgs count(long count) {
return new GeoRadiusStoreArgs<>().withCount(count);
}
}
/**
* Store the resulting members with their location in the new Geo set {@code storeKey}. Cannot be used together with
* {@link #withStoreDist(Object)}.
*
* @param storeKey the destination key.
* @return {@code this} {@link GeoRadiusStoreArgs}.
*/
public GeoRadiusStoreArgs withStore(K storeKey) {
LettuceAssert.notNull(storeKey, "StoreKey must not be null");
this.storeKey = storeKey;
return this;
}
/**
* Store the resulting members with their distance in the sorted set {@code storeKey}. Cannot be used together with
* {@link #withStore(Object)}.
*
* @param storeKey the destination key.
* @return {@code this} {@link GeoRadiusStoreArgs}.
*/
public GeoRadiusStoreArgs withStoreDist(K storeKey) {
LettuceAssert.notNull(storeKey, "StoreKey must not be null");
this.storeDistKey = storeKey;
return this;
}
/**
* Limit results to {@code count} entries.
*
* @param count number greater 0.
* @return {@code this} {@link GeoRadiusStoreArgs}.
*/
public GeoRadiusStoreArgs withCount(long count) {
LettuceAssert.isTrue(count > 0, "Count must be greater 0");
this.count = count;
return this;
}
/**
* Sort results ascending.
*
* @return {@code this} {@link GeoRadiusStoreArgs}.
*/
public GeoRadiusStoreArgs asc() {
return sort(Sort.asc);
}
/**
* Sort results descending.
*
* @return {@code this} {@link GeoRadiusStoreArgs}.
*/
public GeoRadiusStoreArgs desc() {
return sort(Sort.desc);
}
/**
* @return the key for storing results
*/
public K getStoreKey() {
return storeKey;
}
/**
* @return the key for storing distance results
*/
public K getStoreDistKey() {
return storeDistKey;
}
/**
* Sort results.
*
* @param sort sort order, must not be {@code null}
* @return {@code this} {@link GeoRadiusStoreArgs}.
*/
public GeoRadiusStoreArgs sort(Sort sort) {
LettuceAssert.notNull(sort, "Sort must not be null");
this.sort = sort;
return this;
}
@SuppressWarnings("unchecked")
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (sort != null && sort != Sort.none) {
args.add(sort.name());
}
if (count != null) {
args.add(CommandKeyword.COUNT).add(count);
}
if (storeKey != null) {
args.add("STORE").addKey((K) storeKey);
}
if (storeDistKey != null) {
args.add("STOREDIST").addKey((K) storeDistKey);
}
| 1,106
| 133
| 1,239
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/GeoSearch.java
|
GeoSearch
|
fromMember
|
class GeoSearch {
// TODO: Should be V
/**
* Create a {@link GeoRef} from a Geo set {@code member}.
*
* @param member the Geo set member to use as search reference starting point.
* @return the {@link GeoRef}.
*/
public static <K> GeoRef<K> fromMember(K member) {<FILL_FUNCTION_BODY>}
/**
* Create a {@link GeoRef} from WGS84 coordinates {@code longitude} and {@code latitude}.
*
* @param longitude the longitude coordinate according to WGS84.
* @param latitude the latitude coordinate according to WGS84.
* @return the {@link GeoRef}.
*/
public static <K> GeoRef<K> fromCoordinates(double longitude, double latitude) {
return (GeoRef<K>) new FromCoordinates(longitude, latitude);
}
/**
* Create a {@link GeoPredicate} by specifying a radius {@code distance} and {@link GeoArgs.Unit}.
*
* @param distance the radius.
* @param unit size unit.
* @return the {@link GeoPredicate} for the specified radius.
*/
public static GeoPredicate byRadius(double distance, GeoArgs.Unit unit) {
return new Radius(distance, unit);
}
/**
* Create a {@link GeoPredicate} by specifying a box of the size {@code width}, {@code height} and {@link GeoArgs.Unit}.
*
* @param width box width.
* @param height box height.
* @param unit size unit.
* @return the {@link GeoPredicate} for the specified box.
*/
public static GeoPredicate byBox(double width, double height, GeoArgs.Unit unit) {
return new Box(width, height, unit);
}
/**
* Geo reference specifying a search starting point.
*
* @param <K>
*/
public interface GeoRef<K> extends CompositeArgument {
}
static class FromMember<K> implements GeoRef<K> {
final K member;
public FromMember(K member) {
this.member = member;
}
@Override
@SuppressWarnings("unchecked")
public <K, V> void build(CommandArgs<K, V> args) {
args.add("FROMMEMBER").addKey((K) member);
}
}
static class FromCoordinates implements GeoRef<Object> {
final double longitude, latitude;
public FromCoordinates(double longitude, double latitude) {
this.longitude = longitude;
this.latitude = latitude;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {
args.add("FROMLONLAT").add(longitude).add(latitude);
}
}
/**
* Geo predicate specifying a search scope.
*/
public interface GeoPredicate extends CompositeArgument {
}
static class Radius implements GeoPredicate {
final double distance;
final GeoArgs.Unit unit;
public Radius(double distance, GeoArgs.Unit unit) {
this.distance = distance;
this.unit = unit;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {
args.add("BYRADIUS").add(distance).add(unit);
}
}
static class Box implements GeoPredicate {
final double width, height;
final GeoArgs.Unit unit;
public Box(double width, double height, GeoArgs.Unit unit) {
this.width = width;
this.height = height;
this.unit = unit;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {
args.add("BYBOX").add(width).add(height).add(unit);
}
}
}
|
LettuceAssert.notNull(member, "Reference member must not be null");
return new FromMember<>(member);
| 1,034
| 33
| 1,067
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/GeoValue.java
|
GeoValue
|
getLatitude
|
class GeoValue<V> extends Value<V> {
private final GeoCoordinates coordinates;
/**
* Serializable constructor.
*/
protected GeoValue() {
super(null);
this.coordinates = null;
}
private GeoValue(GeoCoordinates coordinates, V value) {
super(value);
this.coordinates = coordinates;
}
/**
* Creates a {@link Value} from a {@code key} and an {@link Optional}. The resulting value contains the value from the
* {@link Optional} if a value is present. Value is empty if the {@link Optional} is empty.
*
* @param coordinates the score.
* @param optional the optional. May be empty but never {@code null}.
* @return the {@link Value}.
*/
public static <T extends V, V> Value<V> from(GeoCoordinates coordinates, Optional<T> optional) {
LettuceAssert.notNull(optional, "Optional must not be null");
if (optional.isPresent()) {
LettuceAssert.notNull(coordinates, "GeoCoordinates must not be null");
return new GeoValue<>(coordinates, optional.get());
}
return Value.empty();
}
/**
* Creates a {@link Value} from a {@code coordinates} and {@code value}. The resulting value contains the value if the
* {@code value} is not null.
*
* @param coordinates the coordinates.
* @param value the value. May be {@code null}.
* @return the {@link Value}.
*/
public static <T extends V, V> Value<V> fromNullable(GeoCoordinates coordinates, T value) {
if (value == null) {
return empty();
}
LettuceAssert.notNull(coordinates, "GeoCoordinates must not be null");
return new GeoValue<>(coordinates, value);
}
/**
* Creates a {@link GeoValue} from a {@code key} and {@code value}. The resulting value contains the value.
*
* @param longitude the longitude coordinate according to WGS84.
* @param latitude the latitude coordinate according to WGS84.
* @param value the value. Must not be {@code null}.
* @return the {@link GeoValue}
*/
public static <T extends V, V> GeoValue<V> just(double longitude, double latitude, T value) {
return new GeoValue<>(new GeoCoordinates(longitude, latitude), value);
}
/**
* Creates a {@link GeoValue} from a {@code key} and {@code value}. The resulting value contains the value.
*
* @param coordinates the coordinates.
* @param value the value. Must not be {@code null}.
* @return the {@link GeoValue}.
*/
public static <T extends V, V> GeoValue<V> just(GeoCoordinates coordinates, T value) {
LettuceAssert.notNull(coordinates, "GeoCoordinates must not be null");
return new GeoValue<>(coordinates, value);
}
public GeoCoordinates getCoordinates() {
return coordinates;
}
/**
* @return the longitude if this instance has a {@link #hasValue()}.
* @throws NoSuchElementException if the value is not present.
*/
public double getLongitude() {
if (coordinates == null) {
throw new NoSuchElementException();
}
return coordinates.getX().doubleValue();
}
/**
* @return the latitude if this instance has a {@link #hasValue()}.
* @throws NoSuchElementException if the value is not present.
*/
public double getLatitude() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof GeoValue)) {
return false;
}
if (!super.equals(o)) {
return false;
}
GeoValue<?> geoValue = (GeoValue<?>) o;
return Objects.equals(coordinates, geoValue.coordinates);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), coordinates);
}
@Override
public String toString() {
return hasValue() ? String.format("GeoValue[%s, %s]", coordinates, getValue())
: String.format("GeoValue[%s].empty", coordinates);
}
/**
* Returns a {@link GeoValue} consisting of the results of applying the given function to the value of this element. Mapping
* is performed only if a {@link #hasValue() value is present}.
*
* @param <R> element type of the new {@link GeoValue}.
* @param mapper a stateless function to apply to each element.
* @return the new {@link GeoValue}.
*/
@SuppressWarnings("unchecked")
public <R> GeoValue<R> map(Function<? super V, ? extends R> mapper) {
LettuceAssert.notNull(mapper, "Mapper function must not be null");
if (hasValue()) {
return new GeoValue<>(coordinates, mapper.apply(getValue()));
}
return (GeoValue<R>) this;
}
/**
* Returns a {@link GeoValue} consisting of the results of applying the given function to the {@link GeoCoordinates} of this
* element. Mapping is performed only if a {@link #hasValue() value is present}.
*
* @param mapper a stateless function to apply to each element.
* @return the new {@link GeoValue}.
*/
public GeoValue<V> mapCoordinates(Function<? super GeoCoordinates, ? extends GeoCoordinates> mapper) {
LettuceAssert.notNull(mapper, "Mapper function must not be null");
if (hasValue()) {
return new GeoValue<>(mapper.apply(coordinates), getValue());
}
return this;
}
}
|
if (coordinates == null) {
throw new NoSuchElementException();
}
return coordinates.getY().doubleValue();
| 1,556
| 38
| 1,594
|
<methods>public static Value<V> empty() ,public boolean equals(java.lang.Object) ,public static Value<V> from(Optional<T>) ,public static Value<V> fromNullable(T) ,public V getValue() ,public V getValueOrElse(V) ,public V getValueOrElseGet(Supplier<V>) ,public V getValueOrElseThrow(Supplier<? extends X>) throws X,public boolean hasValue() ,public int hashCode() ,public void ifEmpty(java.lang.Runnable) ,public void ifHasValue(Consumer<? super V>) ,public void ifHasValueOrElse(Consumer<? super V>, java.lang.Runnable) ,public boolean isEmpty() ,public static Value<V> just(T) ,public Value<R> map(Function<? super V,? extends R>) ,public Optional<V> optional() ,public Stream<V> stream() ,public java.lang.String toString() <variables>private static final Value<java.lang.Object> EMPTY,private final non-sealed V value
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/GeoWithin.java
|
GeoWithin
|
equals
|
class GeoWithin<V> {
private final V member;
private final Double distance;
private final Long geohash;
private final GeoCoordinates coordinates;
/**
* Creates a new {@link GeoWithin}.
*
* @param member the member.
* @param distance the distance, may be {@code null}.
* @param geohash the geohash, may be {@code null}.
* @param coordinates the coordinates, may be {@code null}.
*/
public GeoWithin(V member, Double distance, Long geohash, GeoCoordinates coordinates) {
this.member = member;
this.distance = distance;
this.geohash = geohash;
this.coordinates = coordinates;
}
/**
* @return the member within the Geo set.
*/
public V getMember() {
return member;
}
/**
* @return distance if requested otherwise {@code null}.
*/
public Double getDistance() {
return distance;
}
/**
* @return geohash if requested otherwise {@code null}.
*/
public Long getGeohash() {
return geohash;
}
/**
* @return coordinates if requested otherwise {@code null}.
*/
public GeoCoordinates getCoordinates() {
return coordinates;
}
/**
* @return a {@link GeoValue} if {@code coordinates} are set.
* @since 6.1
*/
public GeoValue<V> toValue() {
return GeoValue.just(coordinates, this.member);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = member != null ? member.hashCode() : 0;
result = 31 * result + (distance != null ? distance.hashCode() : 0);
result = 31 * result + (geohash != null ? geohash.hashCode() : 0);
result = 31 * result + (coordinates != null ? coordinates.hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [member=").append(member);
sb.append(", distance=").append(distance);
sb.append(", geohash=").append(geohash);
sb.append(", coordinates=").append(coordinates);
sb.append(']');
return sb.toString();
}
}
|
if (this == o)
return true;
if (!(o instanceof GeoWithin))
return false;
GeoWithin<?> geoWithin = (GeoWithin<?>) o;
if (member != null ? !member.equals(geoWithin.member) : geoWithin.member != null)
return false;
if (distance != null ? !distance.equals(geoWithin.distance) : geoWithin.distance != null)
return false;
if (geohash != null ? !geohash.equals(geoWithin.geohash) : geoWithin.geohash != null)
return false;
return !(coordinates != null ? !coordinates.equals(geoWithin.coordinates) : geoWithin.coordinates != null);
| 670
| 210
| 880
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/GetExArgs.java
|
Builder
|
exAt
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link GetExArgs} and enable {@literal EX}.
*
* @param timeout expire time in seconds.
* @return new {@link GetExArgs} with {@literal EX} enabled.
* @see GetExArgs#ex(long)
*/
public static GetExArgs ex(long timeout) {
return new GetExArgs().ex(timeout);
}
/**
* Creates new {@link GetExArgs} and enable {@literal EX}.
*
* @param timeout expire time in seconds.
* @return new {@link GetExArgs} with {@literal EX} enabled.
* @see GetExArgs#ex(long)
* @since 6.1
*/
public static GetExArgs ex(Duration timeout) {
return new GetExArgs().ex(timeout);
}
/**
* Creates new {@link GetExArgs} and enable {@literal EXAT}.
*
* @param timestamp the timestamp type: posix time in seconds.
* @return new {@link GetExArgs} with {@literal EXAT} enabled.
* @see GetExArgs#exAt(long)
*/
public static GetExArgs exAt(long timestamp) {
return new GetExArgs().exAt(timestamp);
}
/**
* Creates new {@link GetExArgs} and enable {@literal EXAT}.
*
* @param timestamp the timestamp type: posix time in seconds.
* @return new {@link GetExArgs} with {@literal EXAT} enabled.
* @see GetExArgs#exAt(Date)
* @since 6.1
*/
public static GetExArgs exAt(Date timestamp) {
return new GetExArgs().exAt(timestamp);
}
/**
* Creates new {@link GetExArgs} and enable {@literal EXAT}.
*
* @param timestamp the timestamp type: posix time in seconds.
* @return new {@link GetExArgs} with {@literal EXAT} enabled.
* @see GetExArgs#exAt(Instant)
* @since 6.1
*/
public static GetExArgs exAt(Instant timestamp) {
return new GetExArgs().exAt(timestamp);
}
/**
* Creates new {@link GetExArgs} and enable {@literal PX}.
*
* @param timeout expire time in milliseconds.
* @return new {@link GetExArgs} with {@literal PX} enabled.
* @see GetExArgs#px(long)
*/
public static GetExArgs px(long timeout) {
return new GetExArgs().px(timeout);
}
/**
* Creates new {@link GetExArgs} and enable {@literal PX}.
*
* @param timeout expire time in milliseconds.
* @return new {@link GetExArgs} with {@literal PX} enabled.
* @see GetExArgs#px(long)
* @since 6.1
*/
public static GetExArgs px(Duration timeout) {
return new GetExArgs().px(timeout);
}
/**
* Creates new {@link GetExArgs} and enable {@literal PXAT}.
*
* @param timestamp the timestamp type: posix time.
* @return new {@link GetExArgs} with {@literal PXAT} enabled.
* @see GetExArgs#pxAt(long)
*/
public static GetExArgs pxAt(long timestamp) {
return new GetExArgs().pxAt(timestamp);
}
/**
* Creates new {@link GetExArgs} and enable {@literal PXAT}.
*
* @param timestamp the timestamp type: posix time.
* @return new {@link GetExArgs} with {@literal PXAT} enabled.
* @see GetExArgs#pxAt(Date)
* @since 6.1
*/
public static GetExArgs pxAt(Date timestamp) {
return new GetExArgs().pxAt(timestamp);
}
/**
* Creates new {@link GetExArgs} and enable {@literal PXAT}.
*
* @param timestamp the timestamp type: posix time.
* @return new {@link GetExArgs} with {@literal PXAT} enabled.
* @see GetExArgs#pxAt(Instant)
* @since 6.1
*/
public static GetExArgs pxAt(Instant timestamp) {
return new GetExArgs().pxAt(timestamp);
}
/**
* Creates new {@link GetExArgs} and enable {@literal PERSIST}.
*
* @return new {@link GetExArgs} with {@literal PERSIST} enabled.
* @see GetExArgs#persist()
*/
public static GetExArgs persist() {
return new GetExArgs().persist();
}
}
/**
* Set the specified expire time, in seconds.
*
* @param timeout expire time in seconds.
* @return {@code this} {@link GetExArgs}.
*/
public GetExArgs ex(long timeout) {
this.ex = timeout;
return this;
}
/**
* Set the specified expire time, in seconds.
*
* @param timeout expire time in seconds.
* @return {@code this} {@link GetExArgs}.
* @since 6.1
*/
public GetExArgs ex(Duration timeout) {
LettuceAssert.notNull(timeout, "Timeout must not be null");
this.ex = timeout.toMillis() / 1000;
return this;
}
/**
* Set the specified expire at time using a posix {@code timestamp}.
*
* @param timestamp the timestamp type: posix time in seconds.
* @return {@code this} {@link GetExArgs}.
* @since 6.1
*/
public GetExArgs exAt(long timestamp) {
this.exAt = timestamp;
return this;
}
/**
* Set the specified expire at time using a posix {@code timestamp}.
*
* @param timestamp the timestamp type: posix time in seconds.
* @return {@code this} {@link GetExArgs}.
* @since 6.1
*/
public GetExArgs exAt(Date timestamp) {<FILL_FUNCTION_BODY>
|
LettuceAssert.notNull(timestamp, "Timestamp must not be null");
return exAt(timestamp.getTime() / 1000);
| 1,653
| 42
| 1,695
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/KeyValue.java
|
KeyValue
|
from
|
class KeyValue<K, V> extends Value<V> {
private final K key;
/**
* Serializable constructor.
*/
protected KeyValue() {
super(null);
this.key = null;
}
private KeyValue(K key, V value) {
super(value);
LettuceAssert.notNull(key, "Key must not be null");
this.key = key;
}
/**
* Creates a {@link KeyValue} from a {@code key} and an {@link Optional}. The resulting value contains the value from the
* {@link Optional} if a value is present. Value is empty if the {@link Optional} is empty.
*
* @param key the key, must not be {@code null}.
* @param optional the optional. May be empty but never {@code null}.
* @return the {@link KeyValue}
*/
public static <K, T extends V, V> KeyValue<K, V> from(K key, Optional<T> optional) {<FILL_FUNCTION_BODY>}
/**
* Creates a {@link KeyValue} from a {@code key} and{@code value}. The resulting value contains the value if the
* {@code value} is not null.
*
* @param key the key, must not be {@code null}.
* @param value the value. May be {@code null}.
* @return the {@link KeyValue}
*/
public static <K, T extends V, V> KeyValue<K, V> fromNullable(K key, T value) {
if (value == null) {
return empty(key);
}
return new KeyValue<K, V>(key, value);
}
/**
* Returns an empty {@code KeyValue} instance with the {@code key} set. No value is present for this instance.
*
* @param key the key, must not be {@code null}.
* @return the {@link KeyValue}
*/
public static <K, V> KeyValue<K, V> empty(K key) {
return new KeyValue<K, V>(key, null);
}
/**
* Creates a {@link KeyValue} from a {@code key} and {@code value}. The resulting value contains the value.
*
* @param key the key. Must not be {@code null}.
* @param value the value. Must not be {@code null}.
* @return the {@link KeyValue}
*/
public static <K, T extends V, V> KeyValue<K, V> just(K key, T value) {
LettuceAssert.notNull(value, "Value must not be null");
return new KeyValue<K, V>(key, value);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof KeyValue))
return false;
if (!super.equals(o))
return false;
KeyValue<?, ?> keyValue = (KeyValue<?, ?>) o;
return key.equals(keyValue.key);
}
@Override
public int hashCode() {
int result = key.hashCode();
result = 31 * result + (hasValue() ? getValue().hashCode() : 0);
return result;
}
@Override
public String toString() {
return hasValue() ? String.format("KeyValue[%s, %s]", key, getValue()) : String.format("KeyValue[%s].empty", key);
}
/**
*
* @return the key
*/
public K getKey() {
return key;
}
/**
* Returns a {@link KeyValue} consisting of the results of applying the given function to the value of this element. Mapping
* is performed only if a {@link #hasValue() value is present}.
*
* @param <R> The element type of the new {@link KeyValue}
* @param mapper a stateless function to apply to each element
* @return the new {@link KeyValue}
*/
@SuppressWarnings("unchecked")
@Override
public <R> KeyValue<K, R> map(Function<? super V, ? extends R> mapper) {
LettuceAssert.notNull(mapper, "Mapper function must not be null");
if (hasValue()) {
return new KeyValue<>(getKey(), mapper.apply(getValue()));
}
return (KeyValue<K, R>) this;
}
}
|
LettuceAssert.notNull(optional, "Optional must not be null");
if (optional.isPresent()) {
return new KeyValue<K, V>(key, optional.get());
}
return empty(key);
| 1,153
| 63
| 1,216
|
<methods>public static Value<V> empty() ,public boolean equals(java.lang.Object) ,public static Value<V> from(Optional<T>) ,public static Value<V> fromNullable(T) ,public V getValue() ,public V getValueOrElse(V) ,public V getValueOrElseGet(Supplier<V>) ,public V getValueOrElseThrow(Supplier<? extends X>) throws X,public boolean hasValue() ,public int hashCode() ,public void ifEmpty(java.lang.Runnable) ,public void ifHasValue(Consumer<? super V>) ,public void ifHasValueOrElse(Consumer<? super V>, java.lang.Runnable) ,public boolean isEmpty() ,public static Value<V> just(T) ,public Value<R> map(Function<? super V,? extends R>) ,public Optional<V> optional() ,public Stream<V> stream() ,public java.lang.String toString() <variables>private static final Value<java.lang.Object> EMPTY,private final non-sealed V value
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/KillArgs.java
|
Builder
|
laddr
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link KillArgs} and enabling {@literal SKIPME YES}.
*
* @return new {@link KillArgs} with {@literal SKIPME YES} enabled.
* @see KillArgs#skipme()
*/
public static KillArgs skipme() {
return new KillArgs().skipme();
}
/**
* Creates new {@link KillArgs} setting {@literal ADDR} (Remote Address).
*
* @param addr must not be {@code null}.
* @return new {@link KillArgs} with {@literal ADDR} set.
* @see KillArgs#addr(String)
*/
public static KillArgs addr(String addr) {
return new KillArgs().addr(addr);
}
/**
* Creates new {@link KillArgs} setting {@literal LADDR} (Local Address).
*
* @param laddr must not be {@code null}.
* @return new {@link KillArgs} with {@literal LADDR} set.
* @see KillArgs#laddr(String)
*/
public static KillArgs laddr(String laddr) {
return new KillArgs().laddr(laddr);
}
/**
* Creates new {@link KillArgs} setting {@literal ID}.
*
* @param id client id.
* @return new {@link KillArgs} with {@literal ID} set.
* @see KillArgs#id(long)
*/
public static KillArgs id(long id) {
return new KillArgs().id(id);
}
/**
* Creates new {@link KillArgs} setting {@literal TYPE PUBSUB}.
*
* @return new {@link KillArgs} with {@literal TYPE PUBSUB} set.
* @see KillArgs#type(Type)
*/
public static KillArgs typePubsub() {
return new KillArgs().type(Type.PUBSUB);
}
/**
* Creates new {@link KillArgs} setting {@literal TYPE NORMAL}.
*
* @return new {@link KillArgs} with {@literal TYPE NORMAL} set.
* @see KillArgs#type(Type)
*/
public static KillArgs typeNormal() {
return new KillArgs().type(Type.NORMAL);
}
/**
* Creates new {@link KillArgs} setting {@literal TYPE MASTER}.
*
* @return new {@link KillArgs} with {@literal TYPE MASTER} set.
* @see KillArgs#type(Type)
* @since 5.0.4
*/
public static KillArgs typeMaster() {
return new KillArgs().type(Type.MASTER);
}
/**
* Creates new {@link KillArgs} setting {@literal TYPE SLAVE}.
*
* @return new {@link KillArgs} with {@literal TYPE SLAVE} set.
* @see KillArgs#type(Type)
*/
public static KillArgs typeSlave() {
return new KillArgs().type(Type.SLAVE);
}
/**
* Creates new {@link KillArgs} setting {@literal USER}.
*
* @return new {@link KillArgs} with {@literal USER} set.
* @see KillArgs#user(String)
* @since 6.1
*/
public static KillArgs user(String username) {
return new KillArgs().user(username);
}
}
/**
* By default this option is enabled, that is, the client calling the command will not get killed, however setting this
* option to no will have the effect of also killing the client calling the command.
*
* @return {@code this} {@link MigrateArgs}.
*/
public KillArgs skipme() {
return this.skipme(true);
}
/**
* By default this option is enabled, that is, the client calling the command will not get killed, however setting this
* option to no will have the effect of also killing the client calling the command.
*
* @param state
* @return {@code this} {@link KillArgs}.
*/
public KillArgs skipme(boolean state) {
this.skipme = state;
return this;
}
/**
* Kill the client at {@code addr} (Remote Address).
*
* @param addr must not be {@code null}.
* @return {@code this} {@link KillArgs}.
*/
public KillArgs addr(String addr) {
LettuceAssert.notNull(addr, "Client address must not be null");
this.addr = addr;
return this;
}
/**
* Kill the client at {@code laddr} (Local Address).
*
* @param laddr must not be {@code null}.
* @return {@code this} {@link KillArgs}.
* @since 6.1
*/
public KillArgs laddr(String laddr) {<FILL_FUNCTION_BODY>
|
LettuceAssert.notNull(laddr, "Local client address must not be null");
this.laddr = laddr;
return this;
| 1,336
| 42
| 1,378
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/LMPopArgs.java
|
Builder
|
count
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link LMPopArgs} setting with {@code LEFT} direction.
*
* @return new {@link LMPopArgs} with args set.
*/
public static LMPopArgs left() {
return new LMPopArgs(CommandKeyword.LEFT, null);
}
/**
* Creates new {@link LMPopArgs} setting with {@code RIGHT} direction.
*
* @return new {@link LMPopArgs} with args set.
*/
public static LMPopArgs right() {
return new LMPopArgs(CommandKeyword.RIGHT, null);
}
}
/**
* Set the {@code count} of entries to return.
*
* @param count number greater 0.
* @return {@code this}
*/
public LMPopArgs count(long count) {<FILL_FUNCTION_BODY>
|
LettuceAssert.isTrue(count > 0, "Count must be greater 0");
this.count = count;
return this;
| 260
| 40
| 300
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/LPosArgs.java
|
Builder
|
maxlen
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new empty {@link LPosArgs}.
*
* @return new {@link LPosArgs}.
* @see LPosArgs#maxlen(long)
*/
public static LPosArgs empty() {
return new LPosArgs();
}
/**
* Creates new {@link LPosArgs} and setting {@literal MAXLEN}.
*
* @return new {@link LPosArgs} with {@literal MAXLEN} set.
* @see LPosArgs#maxlen(long)
*/
public static LPosArgs maxlen(long count) {
return new LPosArgs().maxlen(count);
}
/**
* Creates new {@link LPosArgs} and setting {@literal RANK}.
*
* @return new {@link LPosArgs} with {@literal RANK} set.
* @see LPosArgs#rank(long)
*/
public static LPosArgs rank(long rank) {
return new LPosArgs().rank(rank);
}
}
/**
* Limit list scanning to {@code maxlen} entries.
*
* @param maxlen number greater 0.
* @return {@code this}
*/
public LPosArgs maxlen(long maxlen) {<FILL_FUNCTION_BODY>
|
LettuceAssert.isTrue(maxlen > 0, "Maxlen must be greater 0");
this.maxlen = maxlen;
return this;
| 362
| 44
| 406
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/Limit.java
|
Limit
|
toString
|
class Limit {
private static final Limit UNLIMITED = new Limit(null, null);
private final Long offset;
private final Long count;
protected Limit(Long offset, Long count) {
this.offset = offset;
this.count = count;
}
/**
*
* @return an unlimited limit.
*/
public static Limit unlimited() {
return UNLIMITED;
}
/**
* Creates a {@link Limit} given {@code offset} and {@code count}.
*
* @param offset the offset.
* @param count the limit count.
* @return the {@link Limit}
*/
public static Limit create(long offset, long count) {
return new Limit(offset, count);
}
/**
* Creates a {@link Limit} given {@code count}.
*
* @param count the limit count.
* @return the {@link Limit}.
* @since 4.5
*/
public static Limit from(long count) {
return new Limit(0L, count);
}
/**
* @return the offset or {@literal -1} if unlimited.
*/
public long getOffset() {
if (offset != null) {
return offset;
}
return -1;
}
/**
* @return the count or {@literal -1} if unlimited.
*/
public long getCount() {
if (count != null) {
return count;
}
return -1;
}
/**
*
* @return {@code true} if the {@link Limit} contains a limitation.
*/
public boolean isLimited() {
return offset != null && count != null;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
if (isLimited()) {
return sb.append(" [offset=").append(getOffset()).append(", count=").append(getCount()).append("]").toString();
}
return sb.append(" [unlimited]").toString();
| 493
| 88
| 581
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/Operators.java
|
Operators
|
onOperatorError
|
class Operators {
private static final InternalLogger LOG = InternalLoggerFactory.getInstance(Operators.class);
/**
* A key that can be used to store a sequence-specific {@link Hooks#onOperatorError(BiFunction)} hook in a {@link Context},
* as a {@link BiFunction BiFunction<Throwable, Object, Throwable>}.
*/
private static final String KEY_ON_OPERATOR_ERROR = "reactor.onOperatorError.local";
private static final Field onOperatorErrorHook = findOnOperatorErrorHookField();
private static final Supplier<Queue<Object>> queueSupplier = getQueueSupplier();
private static Field findOnOperatorErrorHookField() {
try {
return AccessController.doPrivileged((PrivilegedExceptionAction<Field>) () -> {
Field field = Hooks.class.getDeclaredField("onOperatorErrorHook");
if (!field.isAccessible()) {
field.setAccessible(true);
}
return field;
});
} catch (PrivilegedActionException e) {
return null;
}
}
@SuppressWarnings("unchecked")
private static Supplier<Queue<Object>> getQueueSupplier() {
try {
return AccessController.doPrivileged((PrivilegedExceptionAction<Supplier<Queue<Object>>>) () -> {
Method unbounded = Queues.class.getMethod("unbounded");
return (Supplier) unbounded.invoke(Queues.class);
});
} catch (PrivilegedActionException e) {
return LettuceFactories::newSpScQueue;
}
}
/**
* Cap an addition to Long.MAX_VALUE
*
* @param a left operand
* @param b right operand
*
* @return Addition result or Long.MAX_VALUE if overflow
*/
static long addCap(long a, long b) {
long res = a + b;
if (res < 0L) {
return Long.MAX_VALUE;
}
return res;
}
/**
* Concurrent addition bound to Long.MAX_VALUE. Any concurrent write will "happen before" this operation.
*
* @param <T> the parent instance type
* @param updater current field updater
* @param instance current instance to update
* @param toAdd delta to add
* @return {@code true} if the operation succeeded.
* @since 5.0.1
*/
public static <T> boolean request(AtomicLongFieldUpdater<T> updater, T instance, long toAdd) {
if (validate(toAdd)) {
addCap(updater, instance, toAdd);
return true;
}
return false;
}
/**
* Concurrent addition bound to Long.MAX_VALUE. Any concurrent write will "happen before" this operation.
*
* @param <T> the parent instance type
* @param updater current field updater
* @param instance current instance to update
* @param toAdd delta to add
* @return value before addition or Long.MAX_VALUE
*/
static <T> long addCap(AtomicLongFieldUpdater<T> updater, T instance, long toAdd) {
long r, u;
for (;;) {
r = updater.get(instance);
if (r == Long.MAX_VALUE) {
return Long.MAX_VALUE;
}
u = addCap(r, toAdd);
if (updater.compareAndSet(instance, r, u)) {
return r;
}
}
}
/**
* Evaluate if a request is strictly positive otherwise {@link #reportBadRequest(long)}
*
* @param n the request value
* @return true if valid
*/
static boolean validate(long n) {
if (n <= 0) {
reportBadRequest(n);
return false;
}
return true;
}
/**
* Log an {@link IllegalArgumentException} if the request is null or negative.
*
* @param n the failing demand
*
* @see Exceptions#nullOrNegativeRequestException(long)
*/
static void reportBadRequest(long n) {
if (LOG.isDebugEnabled()) {
LOG.debug("Negative request", Exceptions.nullOrNegativeRequestException(n));
}
}
/**
* @param elements the invalid requested demand
*
* @return a new {@link IllegalArgumentException} with a cause message abiding to reactive stream specification rule 3.9.
*/
static IllegalArgumentException nullOrNegativeRequestException(long elements) {
return new IllegalArgumentException("Spec. Rule 3.9 - Cannot request a non strictly positive number: " + elements);
}
/**
* Map an "operator" error given an operator parent {@link Subscription}. The result error will be passed via onError to the
* operator downstream. {@link Subscription} will be cancelled after checking for fatal error via
* {@link Exceptions#throwIfFatal(Throwable)}. Takes an additional signal, which can be added as a suppressed exception if
* it is a {@link Throwable} and the default {@link Hooks#onOperatorError(BiFunction) hook} is in place.
*
* @param subscription the linked operator parent {@link Subscription}
* @param error the callback or operator error
* @param dataSignal the value (onNext or onError) signal processed during failure
* @param context a context that might hold a local error consumer
* @return mapped {@link Throwable}
*/
static Throwable onOperatorError(@Nullable Subscription subscription, Throwable error, @Nullable Object dataSignal,
Context context) {<FILL_FUNCTION_BODY>}
/**
* Create a new {@link Queue}.
*
* @return the new queue.
*/
@SuppressWarnings("unchecked")
static <T> Queue<T> newQueue() {
return (Queue<T>) queueSupplier.get();
}
@SuppressWarnings("unchecked")
private static BiFunction<? super Throwable, Object, ? extends Throwable> getOnOperatorErrorHook() {
try {
return (BiFunction<? super Throwable, Object, ? extends Throwable>) onOperatorErrorHook.get(Hooks.class);
} catch (ReflectiveOperationException e) {
return null;
}
}
}
|
Exceptions.throwIfFatal(error);
if (subscription != null) {
subscription.cancel();
}
Throwable t = Exceptions.unwrap(error);
BiFunction<? super Throwable, Object, ? extends Throwable> hook = context.getOrDefault(KEY_ON_OPERATOR_ERROR, null);
if (hook == null && onOperatorErrorHook != null) {
hook = getOnOperatorErrorHook();
}
if (hook == null) {
if (dataSignal != null) {
if (dataSignal != t && dataSignal instanceof Throwable) {
t = Exceptions.addSuppressed(t, (Throwable) dataSignal);
}
// do not wrap original value to avoid strong references
/*
* else { }
*/
}
return t;
}
return hook.apply(error, dataSignal);
| 1,662
| 235
| 1,897
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/Range.java
|
Boundary
|
equals
|
class Boundary<T> {
private static final Boundary<?> UNBOUNDED = new Boundary<>(null, true);
private final T value;
private final boolean including;
private Boundary(T value, boolean including) {
this.value = value;
this.including = including;
}
/**
* Creates an unbounded (infinite) boundary that marks the beginning/end of the range.
*
* @return the unbounded boundary.
* @param <T> inferred type.
*/
@SuppressWarnings("unchecked")
public static <T> Boundary<T> unbounded() {
return (Boundary<T>) UNBOUNDED;
}
/**
* Create a {@link Boundary} based on the {@code value} that includes the value when comparing ranges. Greater or
* equals, less or equals. but not Greater or equal, less or equal to {@code value}.
*
* @param value must not be {@code null}.
* @param <T> value type.
* @return the {@link Boundary}.
*/
public static <T> Boundary<T> including(T value) {
LettuceAssert.notNull(value, "Value must not be null");
return new Boundary<>(value, true);
}
/**
* Create a {@link Boundary} based on the {@code value} that excludes the value when comparing ranges. Greater or less
* to {@code value} but not greater or equal, less or equal.
*
* @param value must not be {@code null}.
* @param <T> value type.
* @return the {@link Boundary}.
*/
public static <T> Boundary<T> excluding(T value) {
LettuceAssert.notNull(value, "Value must not be null");
return new Boundary<>(value, false);
}
/**
* @return the value
*/
public T getValue() {
return value;
}
/**
* @return {@code true} if the boundary includes the value.
*/
public boolean isIncluding() {
return including;
}
/**
* @return {@code true} if the bound is unbounded.
* @since 6.0
*/
public boolean isUnbounded() {
return this == UNBOUNDED;
}
/**
* @return {@code true} if the bound is unbounded.
* @since 6.0
*/
public boolean isBounded() {
return this != UNBOUNDED;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(value, including);
}
@Override
public String toString() {
if (value == null) {
return "[unbounded]";
}
StringBuilder sb = new StringBuilder();
if (including) {
sb.append('[');
} else {
sb.append('(');
}
sb.append(value);
return sb.toString();
}
}
|
if (this == o)
return true;
if (!(o instanceof Boundary))
return false;
Boundary<?> boundary = (Boundary<?>) o;
return including == boundary.including && Objects.equals(value, boundary.value);
| 829
| 71
| 900
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ReadFromImpl.java
|
OrderedPredicateReadFromAdapter
|
select
|
class OrderedPredicateReadFromAdapter extends ReadFrom {
private final Predicate<RedisNodeDescription> predicates[];
@SafeVarargs
OrderedPredicateReadFromAdapter(Predicate<RedisNodeDescription>... predicates) {
this.predicates = predicates;
}
@Override
public List<RedisNodeDescription> select(Nodes nodes) {<FILL_FUNCTION_BODY>}
@Override
protected boolean isOrderSensitive() {
return true;
}
}
|
List<RedisNodeDescription> result = new ArrayList<>(nodes.getNodes().size());
for (Predicate<RedisNodeDescription> predicate : predicates) {
for (RedisNodeDescription node : nodes) {
if (predicate.test(node)) {
result.add(node);
}
}
}
return result;
| 137
| 95
| 232
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/RedisConnectionException.java
|
RedisConnectionException
|
create
|
class RedisConnectionException extends RedisException {
/**
* Create a {@code RedisConnectionException} with the specified detail message.
*
* @param msg the detail message.
*/
public RedisConnectionException(String msg) {
super(msg);
}
/**
* Create a {@code RedisConnectionException} with the specified detail message and nested exception.
*
* @param msg the detail message.
* @param cause the nested exception.
*/
public RedisConnectionException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Create a new {@link RedisConnectionException} given {@link SocketAddress} and the {@link Throwable cause}.
*
* @param remoteAddress remote socket address.
* @param cause the nested exception.
* @return the {@link RedisConnectionException}.
* @since 4.4
*/
public static RedisConnectionException create(SocketAddress remoteAddress, Throwable cause) {
return create(remoteAddress == null ? null : remoteAddress.toString(), cause);
}
/**
* Create a new {@link RedisConnectionException} given {@code remoteAddress} and the {@link Throwable cause}.
*
* @param remoteAddress remote address.
* @param cause the nested exception.
* @return the {@link RedisConnectionException}.
* @since 5.1
*/
public static RedisConnectionException create(String remoteAddress, Throwable cause) {<FILL_FUNCTION_BODY>}
/**
* Create a new {@link RedisConnectionException} given {@link Throwable cause}.
*
* @param cause the exception.
* @return the {@link RedisConnectionException}.
* @since 5.1
*/
public static RedisConnectionException create(Throwable cause) {
if (cause instanceof RedisConnectionException) {
return new RedisConnectionException(cause.getMessage(), cause.getCause());
}
return new RedisConnectionException("Unable to connect", cause);
}
/**
* @param error the error message.
* @return {@code true} if the {@code error} message indicates Redis protected mode.
* @since 5.0.1
*/
public static boolean isProtectedMode(String error) {
return error != null && error.startsWith("DENIED");
}
}
|
if (remoteAddress == null) {
if (cause instanceof RedisConnectionException) {
return new RedisConnectionException(cause.getMessage(), cause.getCause());
}
return new RedisConnectionException(null, cause);
}
return new RedisConnectionException(String.format("Unable to connect to %s", remoteAddress), cause);
| 608
| 93
| 701
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, java.lang.Throwable) ,public void <init>(java.lang.Throwable) <variables>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/RedisHandshake.java
|
RedisVersion
|
equals
|
class RedisVersion {
private static final Pattern DECIMALS = Pattern.compile("(\\d+)");
private final static RedisVersion UNKNOWN = new RedisVersion("0.0.0");
private final static RedisVersion UNSTABLE = new RedisVersion("255.255.255");
private final int major;
private final int minor;
private final int bugfix;
private RedisVersion(String version) {
int major = 0;
int minor = 0;
int bugfix = 0;
LettuceAssert.notNull(version, "Version must not be null");
Matcher matcher = DECIMALS.matcher(version);
if (matcher.find()) {
major = Integer.parseInt(matcher.group(1));
if (matcher.find()) {
minor = Integer.parseInt(matcher.group(1));
}
if (matcher.find()) {
bugfix = Integer.parseInt(matcher.group(1));
}
}
this.major = major;
this.minor = minor;
this.bugfix = bugfix;
}
/**
* Construct a new {@link RedisVersion} from a version string containing major, minor and bugfix version such as
* {@code 7.2.0}.
*
* @param version
* @return
*/
public static RedisVersion of(String version) {
return new RedisVersion(version);
}
public boolean isGreaterThan(RedisVersion version) {
return this.compareTo(version) > 0;
}
public boolean isGreaterThanOrEqualTo(RedisVersion version) {
return this.compareTo(version) >= 0;
}
public boolean is(RedisVersion version) {
return this.equals(version);
}
public boolean isLessThan(RedisVersion version) {
return this.compareTo(version) < 0;
}
public boolean isLessThanOrEqualTo(RedisVersion version) {
return this.compareTo(version) <= 0;
}
public int compareTo(RedisVersion that) {
if (this.major != that.major) {
return this.major - that.major;
} else if (this.minor != that.minor) {
return this.minor - that.minor;
} else {
return this.bugfix - that.bugfix;
}
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(major, minor, bugfix);
}
@Override
public String toString() {
return major + "." + minor + "." + bugfix;
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RedisVersion that = (RedisVersion) o;
return major == that.major && minor == that.minor && bugfix == that.bugfix;
| 743
| 85
| 828
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/RedisPublisher.java
|
SubscriptionCommand
|
doOnComplete
|
class SubscriptionCommand<K, V, T> extends CommandWrapper<K, V, T> implements DemandAware.Sink {
private final boolean dissolve;
private final RedisSubscription<T> subscription;
private volatile DemandAware.Source source;
public SubscriptionCommand(RedisCommand<K, V, T> command, RedisSubscription<T> subscription, boolean dissolve) {
super(command);
this.subscription = subscription;
this.dissolve = dissolve;
}
@Override
public boolean hasDemand() {
return isDone() || subscription.state() == State.COMPLETED || subscription.data.isEmpty();
}
@Override
@SuppressWarnings({ "unchecked", "CastCanBeRemovedNarrowingVariableType" })
protected void doOnComplete() {<FILL_FUNCTION_BODY>}
@Override
public void setSource(DemandAware.Source source) {
this.source = source;
}
@Override
public void removeSource() {
this.source = null;
}
@Override
protected void doOnError(Throwable throwable) {
onError(throwable);
}
private void onError(Throwable throwable) {
subscription.onError(throwable);
}
}
|
if (getOutput() != null) {
Object result = getOutput().get();
if (getOutput().hasError()) {
onError(ExceptionFactory.createExecutionException(getOutput().getError()));
return;
}
if (!(getOutput() instanceof StreamingOutput<?>) && result != null) {
if (dissolve && result instanceof Collection) {
Collection<T> collection = (Collection<T>) result;
for (T t : collection) {
if (t != null) {
subscription.onNext(t);
}
}
} else {
subscription.onNext((T) result);
}
}
}
subscription.onAllDataRead();
| 343
| 191
| 534
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/RestoreArgs.java
|
Builder
|
ttl
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link RestoreArgs} and set the TTL.
*
* @return new {@link RestoreArgs} with min idle time set.
* @see RestoreArgs#ttl(long)
*/
public static RestoreArgs ttl(long milliseconds) {
return new RestoreArgs().ttl(milliseconds);
}
/**
* Creates new {@link RestoreArgs} and set the minimum idle time.
*
* @return new {@link RestoreArgs} with min idle time set.
* @see RestoreArgs#ttl(Duration)
*/
public static RestoreArgs ttl(Duration ttl) {
LettuceAssert.notNull(ttl, "Time to live must not be null");
return ttl(ttl.toMillis());
}
}
/**
* Set TTL in {@code milliseconds} after restoring the key.
*
* @param milliseconds time to live.
* @return {@code this}.
*/
public RestoreArgs ttl(long milliseconds) {
this.ttl = milliseconds;
return this;
}
/**
* Set TTL in {@code milliseconds} after restoring the key.
*
* @param ttl time to live.
* @return {@code this}.
*/
public RestoreArgs ttl(Duration ttl) {<FILL_FUNCTION_BODY>
|
LettuceAssert.notNull(ttl, "Time to live must not be null");
return ttl(ttl.toMillis());
| 399
| 40
| 439
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ScanArgs.java
|
Builder
|
match
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link ScanArgs} with {@literal LIMIT} set.
*
* @param count number of elements to scan
* @return new {@link ScanArgs} with {@literal LIMIT} set.
* @see ScanArgs#limit(long)
*/
public static ScanArgs limit(long count) {
return new ScanArgs().limit(count);
}
/**
* Creates new {@link ScanArgs} with {@literal MATCH} set.
*
* @param matches the filter.
* @return new {@link ScanArgs} with {@literal MATCH} set.
* @see ScanArgs#match(String)
*/
public static ScanArgs matches(String matches) {
return new ScanArgs().match(matches);
}
/**
* Creates new {@link ScanArgs} with {@literal MATCH} set.
*
* @param matches the filter.
* @return new {@link ScanArgs} with {@literal MATCH} set.
* @since 6.0.4
* @see ScanArgs#match(byte[])
*/
public static ScanArgs matches(byte[] matches) {
return new ScanArgs().match(matches);
}
}
/**
* Set the match filter. Uses {@link StandardCharsets#UTF_8 UTF-8} to encode {@code match}.
*
* @param match the filter, must not be {@code null}.
* @return {@literal this} {@link ScanArgs}.
*/
public ScanArgs match(String match) {
return match(match, StandardCharsets.UTF_8);
}
/**
* Set the match filter along the given {@link Charset}.
*
* @param match the filter, must not be {@code null}.
* @param charset the charset for match, must not be {@code null}.
* @return {@literal this} {@link ScanArgs}.
* @since 6.0
*/
public ScanArgs match(String match, Charset charset) {<FILL_FUNCTION_BODY>
|
LettuceAssert.notNull(match, "Match must not be null");
LettuceAssert.notNull(charset, "Charset must not be null");
return match(match.getBytes(charset));
| 545
| 58
| 603
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ScoredValue.java
|
ScoredValue
|
map
|
class ScoredValue<V> extends Value<V> {
private static final ScoredValue<Object> EMPTY = new ScoredValue<>(0, null);
private final double score;
/**
* Serializable constructor.
*/
protected ScoredValue() {
super(null);
this.score = 0;
}
private ScoredValue(double score, V value) {
super(value);
this.score = score;
}
/**
* Creates a {@link Value} from a {@code key} and an {@link Optional}. The resulting value contains the value from the
* {@link Optional} if a value is present. Value is empty if the {@link Optional} is empty.
*
* @param score the score.
* @param optional the optional. May be empty but never {@code null}.
* @return the {@link Value}.
*/
public static <T extends V, V> Value<V> from(double score, Optional<T> optional) {
LettuceAssert.notNull(optional, "Optional must not be null");
if (optional.isPresent()) {
return new ScoredValue<>(score, optional.get());
}
return empty();
}
/**
* Creates a {@link Value} from a {@code score} and {@code value}. The resulting value contains the value if the
* {@code value} is not null.
*
* @param score the score.
* @param value the value. May be {@code null}.
* @return the {@link Value}.
*/
public static <T extends V, V> Value<V> fromNullable(double score, T value) {
if (value == null) {
return empty();
}
return new ScoredValue<>(score, value);
}
/**
* Returns an empty {@code ScoredValue} instance. No value is present for this instance.
*
* @return the {@link ScoredValue}
*/
public static <V> ScoredValue<V> empty() {
return (ScoredValue<V>) EMPTY;
}
/**
* Creates a {@link ScoredValue} from a {@code key} and {@code value}. The resulting value contains the value.
*
* @param score the score.
* @param value the value. Must not be {@code null}.
* @return the {@link ScoredValue}.
*/
public static <T extends V, V> ScoredValue<V> just(double score, T value) {
LettuceAssert.notNull(value, "Value must not be null");
return new ScoredValue<>(score, value);
}
public double getScore() {
return score;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ScoredValue))
return false;
if (!super.equals(o))
return false;
ScoredValue<?> that = (ScoredValue<?>) o;
return Double.compare(that.score, score) == 0;
}
@Override
public int hashCode() {
long temp = Double.doubleToLongBits(score);
int result = (int) (temp ^ (temp >>> 32));
result = 31 * result + (hasValue() ? getValue().hashCode() : 0);
return result;
}
@Override
public String toString() {
return hasValue() ? String.format("ScoredValue[%f, %s]", score, getValue())
: String.format("ScoredValue[%f].empty", score);
}
/**
* Returns a {@link ScoredValue} consisting of the results of applying the given function to the value of this element.
* Mapping is performed only if a {@link #hasValue() value is present}.
*
* @param <R> element type of the new {@link ScoredValue}.
* @param mapper a stateless function to apply to each element.
* @return the new {@link ScoredValue}.
*/
@SuppressWarnings("unchecked")
public <R> ScoredValue<R> map(Function<? super V, ? extends R> mapper) {<FILL_FUNCTION_BODY>}
/**
* Returns a {@link ScoredValue} consisting of the results of applying the given function to the score of this element.
* Mapping is performed only if a {@link #hasValue() value is present}.
*
* @param mapper a stateless function to apply to each element.
* @return the new {@link ScoredValue} .
*/
@SuppressWarnings("unchecked")
public ScoredValue<V> mapScore(Function<? super Number, ? extends Number> mapper) {
LettuceAssert.notNull(mapper, "Mapper function must not be null");
if (hasValue()) {
return new ScoredValue<>(mapper.apply(score).doubleValue(), getValue());
}
return this;
}
}
|
LettuceAssert.notNull(mapper, "Mapper function must not be null");
if (hasValue()) {
return new ScoredValue<>(score, mapper.apply(getValue()));
}
return (ScoredValue<R>) this;
| 1,278
| 69
| 1,347
|
<methods>public static Value<V> empty() ,public boolean equals(java.lang.Object) ,public static Value<V> from(Optional<T>) ,public static Value<V> fromNullable(T) ,public V getValue() ,public V getValueOrElse(V) ,public V getValueOrElseGet(Supplier<V>) ,public V getValueOrElseThrow(Supplier<? extends X>) throws X,public boolean hasValue() ,public int hashCode() ,public void ifEmpty(java.lang.Runnable) ,public void ifHasValue(Consumer<? super V>) ,public void ifHasValueOrElse(Consumer<? super V>, java.lang.Runnable) ,public boolean isEmpty() ,public static Value<V> just(T) ,public Value<R> map(Function<? super V,? extends R>) ,public Optional<V> optional() ,public Stream<V> stream() ,public java.lang.String toString() <variables>private static final Value<java.lang.Object> EMPTY,private final non-sealed V value
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/SetArgs.java
|
Builder
|
ex
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link SetArgs} and enable {@literal EX}.
*
* @param timeout expire time in seconds.
* @return new {@link SetArgs} with {@literal EX} enabled.
* @see SetArgs#ex(long)
*/
public static SetArgs ex(long timeout) {
return new SetArgs().ex(timeout);
}
/**
* Creates new {@link SetArgs} and enable {@literal EX}.
*
* @param timeout expire time as duration.
* @return new {@link SetArgs} with {@literal EX} enabled.
* @see SetArgs#ex(long)
* @since 6.1
*/
public static SetArgs ex(Duration timeout) {
return new SetArgs().ex(timeout);
}
/**
* Creates new {@link SetArgs} and enable {@literal EXAT}.
*
* @param timestamp the timestamp type: posix time in seconds.
* @return new {@link SetArgs} with {@literal EXAT} enabled.
* @see SetArgs#exAt(long)
*/
public static SetArgs exAt(long timestamp) {
return new SetArgs().exAt(timestamp);
}
/**
* Creates new {@link SetArgs} and enable {@literal EXAT}.
*
* @param timestamp the timestamp type: posix time in seconds.
* @return new {@link SetArgs} with {@literal EXAT} enabled.
* @see SetArgs#exAt(Date)
* @since 6.1
*/
public static SetArgs exAt(Date timestamp) {
return new SetArgs().exAt(timestamp);
}
/**
* Creates new {@link SetArgs} and enable {@literal EXAT}.
*
* @param timestamp the timestamp type: posix time in seconds.
* @return new {@link SetArgs} with {@literal EXAT} enabled.
* @see SetArgs#exAt(Instant)
* @since 6.1
*/
public static SetArgs exAt(Instant timestamp) {
return new SetArgs().exAt(timestamp);
}
/**
* Creates new {@link SetArgs} and enable {@literal PX}.
*
* @param timeout expire time in milliseconds.
* @return new {@link SetArgs} with {@literal PX} enabled.
* @see SetArgs#px(long)
*/
public static SetArgs px(long timeout) {
return new SetArgs().px(timeout);
}
/**
* Creates new {@link SetArgs} and enable {@literal PX}.
*
* @param timeout expire time in milliseconds.
* @return new {@link SetArgs} with {@literal PX} enabled.
* @see SetArgs#px(long)
* @since 6.1
*/
public static SetArgs px(Duration timeout) {
return new SetArgs().px(timeout);
}
/**
* Creates new {@link SetArgs} and enable {@literal PXAT}.
*
* @param timestamp the timestamp type: posix time.
* @return new {@link SetArgs} with {@literal PXAT} enabled.
* @see SetArgs#pxAt(long)
*/
public static SetArgs pxAt(long timestamp) {
return new SetArgs().pxAt(timestamp);
}
/**
* Creates new {@link SetArgs} and enable {@literal PXAT}.
*
* @param timestamp the timestamp type: posix time.
* @return new {@link SetArgs} with {@literal PXAT} enabled.
* @see SetArgs#pxAt(Date)
* @since 6.1
*/
public static SetArgs pxAt(Date timestamp) {
return new SetArgs().pxAt(timestamp);
}
/**
* Creates new {@link SetArgs} and enable {@literal PXAT}.
*
* @param timestamp the timestamp type: posix time.
* @return new {@link SetArgs} with {@literal PXAT} enabled.
* @see SetArgs#pxAt(Instant)
* @since 6.1
*/
public static SetArgs pxAt(Instant timestamp) {
return new SetArgs().pxAt(timestamp);
}
/**
* Creates new {@link SetArgs} and enable {@literal NX}.
*
* @return new {@link SetArgs} with {@literal NX} enabled.
* @see SetArgs#nx()
*/
public static SetArgs nx() {
return new SetArgs().nx();
}
/**
* Creates new {@link SetArgs} and enable {@literal XX}.
*
* @return new {@link SetArgs} with {@literal XX} enabled.
* @see SetArgs#xx()
*/
public static SetArgs xx() {
return new SetArgs().xx();
}
/**
* Creates new {@link SetArgs} and enable {@literal KEEPTTL}.
*
* @return new {@link SetArgs} with {@literal KEEPTTL} enabled.
* @see SetArgs#keepttl()
* @since 5.3
*/
public static SetArgs keepttl() {
return new SetArgs().keepttl();
}
}
/**
* Set the specified expire time, in seconds.
*
* @param timeout expire time in seconds.
* @return {@code this} {@link SetArgs}.
*/
public SetArgs ex(long timeout) {
this.ex = timeout;
return this;
}
/**
* Set the specified expire time, in seconds.
*
* @param timeout expire time in seconds.
* @return {@code this} {@link SetArgs}.
* @since 6.1
*/
public SetArgs ex(Duration timeout) {<FILL_FUNCTION_BODY>
|
LettuceAssert.notNull(timeout, "Timeout must not be null");
this.ex = timeout.toMillis() / 1000;
return this;
| 1,543
| 48
| 1,591
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ShutdownArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link ShutdownArgs} and setting {@literal SAVE}.
*
* @return new {@link ShutdownArgs} with {@literal SAVE} set.
* @see ShutdownArgs#save(boolean)
*/
public static ShutdownArgs save(boolean save) {
return new ShutdownArgs().save(save);
}
/**
* Creates new {@link ShutdownArgs} and setting {@literal NOW}.
*
* @return new {@link ShutdownArgs} with {@literal NOW} set.
* @see ShutdownArgs#now()
*/
public static ShutdownArgs now() {
return new ShutdownArgs().now();
}
/**
* Creates new {@link ShutdownArgs} and setting {@literal FORCE}.
*
* @return new {@link ShutdownArgs} with {@literal FORCE} set.
* @see ShutdownArgs#force()
*/
public static ShutdownArgs force() {
return new ShutdownArgs().force();
}
/**
* Creates new {@link ShutdownArgs} and setting {@literal ABORT}.
*
* @return new {@link ShutdownArgs} with {@literal ABORT} set.
* @see ShutdownArgs#abort()
*/
public static ShutdownArgs abort() {
return new ShutdownArgs().abort();
}
}
/**
* Will force a DB saving operation even if no save points are configured.
*
* @param save {@code true} force save operation.
* @return {@code this}
*/
public ShutdownArgs save(boolean save) {
this.save = save;
return this;
}
/**
* Skips waiting for lagging replicas, i.e. it bypasses the first step in the shutdown sequence.
*
* @return {@code this}
*/
public ShutdownArgs now() {
this.now = true;
return this;
}
/**
* Ignores any errors that would normally prevent the server from exiting.
*
* @return {@code this}
*/
public ShutdownArgs force() {
this.force = true;
return this;
}
/**
* Cancels an ongoing shutdown and cannot be combined with other flags.
*
* @return {@code this}
*/
public ShutdownArgs abort() {
this.abort = true;
return this;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (save) {
args.add(CommandKeyword.SAVE);
} else {
args.add(CommandKeyword.NOSAVE);
}
if (now) {
args.add("NOW");
}
if (force) {
args.add(CommandKeyword.FORCE);
}
if (abort) {
args.add("ABORT");
}
| 693
| 109
| 802
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/SocketOptions.java
|
Builder
|
interval
|
class Builder {
private int count = DEFAULT_COUNT;
private boolean enabled = DEFAULT_SO_KEEPALIVE;
private Duration idle = DEFAULT_IDLE;
private Duration interval = DEFAULT_INTERVAL;
private Builder() {
}
/**
* Set the maximum number of keepalive probes TCP should send before dropping the connection. Defaults to {@code 9}.
* See also {@link #DEFAULT_COUNT} and {@code TCP_KEEPCNT}.
*
* @param count the maximum number of keepalive probes TCP
* @return {@code this}
*/
public KeepAliveOptions.Builder count(int count) {
LettuceAssert.isTrue(count >= 0, "Count must be greater 0");
this.count = count;
return this;
}
/**
* Enable TCP keepalive. Defaults to disabled. See {@link #DEFAULT_SO_KEEPALIVE}.
*
* @return {@code this}
* @see java.net.SocketOptions#SO_KEEPALIVE
*/
public KeepAliveOptions.Builder enable() {
return enable(true);
}
/**
* Disable TCP keepalive. Defaults to disabled. See {@link #DEFAULT_SO_KEEPALIVE}.
*
* @return {@code this}
* @see java.net.SocketOptions#SO_KEEPALIVE
*/
public KeepAliveOptions.Builder disable() {
return enable(false);
}
/**
* Enable TCP keepalive. Defaults to {@code false}. See {@link #DEFAULT_SO_KEEPALIVE}.
*
* @param enabled whether to enable TCP keepalive.
* @return {@code this}
* @see java.net.SocketOptions#SO_KEEPALIVE
*/
public KeepAliveOptions.Builder enable(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* The time the connection needs to remain idle before TCP starts sending keepalive probes if keepalive is enabled.
* Defaults to {@code 2 hours}. See also @link {@link #DEFAULT_IDLE} and {@code TCP_KEEPIDLE}.
* <p>
* The time granularity of is seconds.
*
* @param idle connection idle time, must be greater {@literal 0}.
* @return {@code this}
*/
public KeepAliveOptions.Builder idle(Duration idle) {
LettuceAssert.notNull(idle, "Idle time must not be null");
LettuceAssert.isTrue(!idle.isNegative(), "Idle time must not be begative");
this.idle = idle;
return this;
}
/**
* The time between individual keepalive probes. Defaults to {@code 75 second}. See also {@link #DEFAULT_INTERVAL}
* and {@code TCP_KEEPINTVL}.
* <p>
* The time granularity of is seconds.
*
* @param interval connection interval time, must be greater {@literal 0}
* @return {@code this}
*/
public KeepAliveOptions.Builder interval(Duration interval) {<FILL_FUNCTION_BODY>}
/**
* Create a new instance of {@link KeepAliveOptions}
*
* @return new instance of {@link KeepAliveOptions}
*/
public KeepAliveOptions build() {
return new KeepAliveOptions(this);
}
}
|
LettuceAssert.notNull(interval, "Idle time must not be null");
LettuceAssert.isTrue(!interval.isNegative(), "Idle time must not be begative");
this.interval = interval;
return this;
| 900
| 65
| 965
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/SortArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link SortArgs} setting {@literal PATTERN}.
*
* @param pattern must not be {@code null}.
* @return new {@link SortArgs} with {@literal PATTERN} set.
* @see SortArgs#by(String)
*/
public static SortArgs by(String pattern) {
return new SortArgs().by(pattern);
}
/**
* Creates new {@link SortArgs} setting {@literal LIMIT}.
*
* @param offset
* @param count
* @return new {@link SortArgs} with {@literal LIMIT} set.
* @see SortArgs#limit(long, long)
*/
public static SortArgs limit(long offset, long count) {
return new SortArgs().limit(offset, count);
}
/**
* Creates new {@link SortArgs} setting {@literal GET}.
*
* @param pattern must not be {@code null}.
* @return new {@link SortArgs} with {@literal GET} set.
* @see SortArgs#by(String)
*/
public static SortArgs get(String pattern) {
return new SortArgs().get(pattern);
}
/**
* Creates new {@link SortArgs} setting {@literal ASC}.
*
* @return new {@link SortArgs} with {@literal ASC} set.
* @see SortArgs#asc()
*/
public static SortArgs asc() {
return new SortArgs().asc();
}
/**
* Creates new {@link SortArgs} setting {@literal DESC}.
*
* @return new {@link SortArgs} with {@literal DESC} set.
* @see SortArgs#desc()
*/
public static SortArgs desc() {
return new SortArgs().desc();
}
/**
* Creates new {@link SortArgs} setting {@literal ALPHA}.
*
* @return new {@link SortArgs} with {@literal ALPHA} set.
* @see SortArgs#alpha()
*/
public static SortArgs alpha() {
return new SortArgs().alpha();
}
}
/**
* Sort keys by an external list. Key names are obtained substituting the first occurrence of {@code *} with the actual
* value of the element in the list.
*
* @param pattern key name pattern.
* @return {@code this} {@link SortArgs}.
*/
public SortArgs by(String pattern) {
LettuceAssert.notNull(pattern, "Pattern must not be null");
this.by = pattern;
return this;
}
/**
* Limit the number of returned elements.
*
* @param offset
* @param count
* @return {@code this} {@link SortArgs}.
*/
public SortArgs limit(long offset, long count) {
return limit(Limit.create(offset, count));
}
/**
* Limit the number of returned elements.
*
* @param limit must not be {@code null}.
* @return {@code this} {@link SortArgs}.
*/
public SortArgs limit(Limit limit) {
LettuceAssert.notNull(limit, "Limit must not be null");
this.limit = limit;
return this;
}
/**
* Retrieve external keys during sort. {@literal GET} supports {@code #} and {@code *} wildcards.
*
* @param pattern must not be {@code null}.
* @return {@code this} {@link SortArgs}.
*/
public SortArgs get(String pattern) {
LettuceAssert.notNull(pattern, "Pattern must not be null");
if (get == null) {
get = new ArrayList<>();
}
get.add(pattern);
return this;
}
/**
* Apply numeric sort in ascending order.
*
* @return {@code this} {@link SortArgs}.
*/
public SortArgs asc() {
order = ASC;
return this;
}
/**
* Apply numeric sort in descending order.
*
* @return {@code this} {@link SortArgs}.
*/
public SortArgs desc() {
order = DESC;
return this;
}
/**
* Apply lexicographically sort.
*
* @return {@code this} {@link SortArgs}.
*/
public SortArgs alpha() {
alpha = true;
return this;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (by != null) {
args.add(BY);
args.add(by);
}
if (get != null) {
for (String pattern : get) {
args.add(GET);
args.add(pattern);
}
}
if (limit != null && limit.isLimited()) {
args.add(LIMIT);
args.add(limit.getOffset());
args.add(limit.getCount());
}
if (order != null) {
args.add(order);
}
if (alpha) {
args.add(ALPHA);
}
| 1,205
| 172
| 1,377
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/SslConnectionBuilder.java
|
SslConnectionBuilder
|
toHostAndPort
|
class SslConnectionBuilder extends ConnectionBuilder {
private RedisURI redisURI;
public SslConnectionBuilder ssl(RedisURI redisURI) {
this.redisURI = redisURI;
return this;
}
public static SslConnectionBuilder sslConnectionBuilder() {
return new SslConnectionBuilder();
}
/**
* Check whether the {@link ChannelHandler} is a {@link SslChannelInitializer}.
*
* @param handler
* @return
* @since 6.0.8
*/
public static boolean isSslChannelInitializer(ChannelHandler handler) {
return handler instanceof SslChannelInitializer;
}
/**
* Create an updated {@link SslChannelInitializer} with the new {@link SocketAddress} in place.
*
* @param handler
* @param socketAddress
* @return
* @since 6.0.8
*/
public static ChannelHandler withSocketAddress(ChannelHandler handler, SocketAddress socketAddress) {
LettuceAssert.assertState(isSslChannelInitializer(handler), "handler must be SslChannelInitializer");
return ((SslChannelInitializer) handler).withHostAndPort(toHostAndPort(socketAddress));
}
@Override
protected List<ChannelHandler> buildHandlers() {
LettuceAssert.assertState(redisURI != null, "RedisURI must not be null");
LettuceAssert.assertState(redisURI.isSsl(), "RedisURI is not configured for SSL (ssl is false)");
return super.buildHandlers();
}
@Override
public ChannelInitializer<Channel> build(SocketAddress socketAddress) {
return new SslChannelInitializer(this::buildHandlers, toHostAndPort(socketAddress), redisURI.getVerifyMode(),
redisURI.isStartTls(), clientResources(), clientOptions().getSslOptions());
}
static HostAndPort toHostAndPort(SocketAddress socketAddress) {<FILL_FUNCTION_BODY>}
static class SslChannelInitializer extends io.netty.channel.ChannelInitializer<Channel> {
private final Supplier<List<ChannelHandler>> handlers;
private final HostAndPort hostAndPort;
private final SslVerifyMode verifyPeer;
private final boolean startTls;
private final ClientResources clientResources;
private final SslOptions sslOptions;
public SslChannelInitializer(Supplier<List<ChannelHandler>> handlers, HostAndPort hostAndPort, SslVerifyMode verifyPeer,
boolean startTls, ClientResources clientResources, SslOptions sslOptions) {
this.handlers = handlers;
this.hostAndPort = hostAndPort;
this.verifyPeer = verifyPeer;
this.startTls = startTls;
this.clientResources = clientResources;
this.sslOptions = sslOptions;
}
ChannelHandler withHostAndPort(HostAndPort hostAndPort) {
return new SslChannelInitializer(handlers, hostAndPort, verifyPeer, startTls, clientResources, sslOptions);
}
@Override
protected void initChannel(Channel channel) throws Exception {
SSLEngine sslEngine = initializeSSLEngine(channel.alloc());
SslHandler sslHandler = new SslHandler(sslEngine, startTls);
Duration sslHandshakeTimeout = sslOptions.getHandshakeTimeout();
sslHandler.setHandshakeTimeoutMillis(sslHandshakeTimeout.toMillis());
channel.pipeline().addLast(sslHandler);
for (ChannelHandler handler : handlers.get()) {
channel.pipeline().addLast(handler);
}
clientResources.nettyCustomizer().afterChannelInitialized(channel);
}
private SSLEngine initializeSSLEngine(ByteBufAllocator alloc) throws IOException, GeneralSecurityException {
SSLParameters sslParams = sslOptions.createSSLParameters();
SslContextBuilder sslContextBuilder = sslOptions.createSslContextBuilder();
if (verifyPeer == SslVerifyMode.FULL) {
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
} else if (verifyPeer == SslVerifyMode.CA) {
sslParams.setEndpointIdentificationAlgorithm("");
} else if (verifyPeer == SslVerifyMode.NONE) {
sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
}
SslContext sslContext = sslContextBuilder.build();
SSLEngine sslEngine = hostAndPort != null
? sslContext.newEngine(alloc, hostAndPort.getHostText(), hostAndPort.getPort())
: sslContext.newEngine(alloc);
sslEngine.setSSLParameters(sslParams);
return sslEngine;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.channel().attr(INIT_FAILURE).set(cause);
super.exceptionCaught(ctx, cause);
}
}
}
|
if (socketAddress instanceof InetSocketAddress) {
InetSocketAddress isa = (InetSocketAddress) socketAddress;
return HostAndPort.of(isa.getHostString(), isa.getPort());
}
return null;
| 1,305
| 67
| 1,372
|
<methods>public non-sealed void <init>() ,public void apply(io.lettuce.core.RedisURI) ,public io.lettuce.core.ConnectionBuilder bootstrap(Bootstrap) ,public Bootstrap bootstrap() ,public ChannelInitializer<Channel> build(java.net.SocketAddress) ,public io.lettuce.core.ConnectionBuilder channelGroup(ChannelGroup) ,public io.lettuce.core.ConnectionBuilder clientOptions(io.lettuce.core.ClientOptions) ,public io.lettuce.core.ClientOptions clientOptions() ,public io.lettuce.core.ConnectionBuilder clientResources(io.lettuce.core.resource.ClientResources) ,public io.lettuce.core.resource.ClientResources clientResources() ,public io.lettuce.core.ConnectionBuilder commandHandler(Supplier<io.lettuce.core.protocol.CommandHandler>) ,public void configureBootstrap(boolean, Function<Class<? extends EventLoopGroup>,EventLoopGroup>) ,public io.lettuce.core.ConnectionBuilder connection(RedisChannelHandler<?,?>) ,public RedisChannelHandler<?,?> connection() ,public static io.lettuce.core.ConnectionBuilder connectionBuilder() ,public io.lettuce.core.ConnectionBuilder connectionEvents(io.lettuce.core.ConnectionEvents) ,public io.lettuce.core.ConnectionBuilder connectionInitializer(io.lettuce.core.protocol.ConnectionInitializer) ,public io.lettuce.core.ConnectionBuilder endpoint(io.lettuce.core.protocol.Endpoint) ,public io.lettuce.core.protocol.Endpoint endpoint() ,public io.lettuce.core.RedisURI getRedisURI() ,public java.time.Duration getTimeout() ,public io.lettuce.core.ConnectionBuilder reconnectionListener(io.lettuce.core.protocol.ReconnectionListener) ,public Mono<java.net.SocketAddress> socketAddress() ,public io.lettuce.core.ConnectionBuilder socketAddressSupplier(Mono<java.net.SocketAddress>) ,public io.lettuce.core.ConnectionBuilder timeout(java.time.Duration) <variables>public static final AttributeKey<java.lang.Throwable> INIT_FAILURE,public static final AttributeKey<java.lang.String> REDIS_URI,private Bootstrap bootstrap,private ChannelGroup channelGroup,private io.lettuce.core.ClientOptions clientOptions,private io.lettuce.core.resource.ClientResources clientResources,private Supplier<io.lettuce.core.protocol.CommandHandler> commandHandlerSupplier,private RedisChannelHandler<?,?> connection,private io.lettuce.core.ConnectionEvents connectionEvents,private io.lettuce.core.protocol.ConnectionInitializer connectionInitializer,private io.lettuce.core.protocol.ConnectionWatchdog connectionWatchdog,private io.lettuce.core.protocol.Endpoint endpoint,private static final InternalLogger logger,private io.lettuce.core.protocol.ReconnectionListener reconnectionListener,private io.lettuce.core.RedisURI redisURI,private Mono<java.net.SocketAddress> socketAddressSupplier,private java.time.Duration timeout
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/StaticRedisCredentials.java
|
StaticRedisCredentials
|
equals
|
class StaticRedisCredentials implements RedisCredentials {
private final String username;
private final char[] password;
StaticRedisCredentials(String username, char[] password) {
this.username = username;
this.password = password != null ? Arrays.copyOf(password, password.length) : null;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean hasUsername() {
return username != null;
}
@Override
public char[] getPassword() {
return hasPassword() ? Arrays.copyOf(password, password.length) : null;
}
@Override
public boolean hasPassword() {
return password != null;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = username != null ? username.hashCode() : 0;
result = 31 * result + Arrays.hashCode(password);
return result;
}
}
|
if (this == o) {
return true;
}
if (!(o instanceof RedisCredentials)) {
return false;
}
RedisCredentials that = (RedisCredentials) o;
if (username != null ? !username.equals(that.getUsername()) : that.getUsername() != null) {
return false;
}
return Arrays.equals(password, that.getPassword());
| 283
| 114
| 397
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/StrAlgoArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link StrAlgoArgs} by keys.
*
* @return new {@link StrAlgoArgs} with {@literal By KEYS} set.
*/
public static StrAlgoArgs keys(String... keys) {
return new StrAlgoArgs().by(By.KEYS, keys);
}
/**
* Creates new {@link StrAlgoArgs} by strings.
*
* @return new {@link StrAlgoArgs} with {@literal By STRINGS} set.
*/
public static StrAlgoArgs strings(String... strings) {
return new StrAlgoArgs().by(By.STRINGS, strings);
}
/**
* Creates new {@link StrAlgoArgs} by strings and charset.
*
* @return new {@link StrAlgoArgs} with {@literal By STRINGS} set.
*/
public static StrAlgoArgs strings(Charset charset, String... strings) {
return new StrAlgoArgs().by(By.STRINGS, strings).charset(charset);
}
}
/**
* restrict the list of matches to the ones of a given minimal length.
*
* @return {@code this} {@link StrAlgoArgs}.
*/
public StrAlgoArgs minMatchLen(int minMatchLen) {
this.minMatchLen = minMatchLen;
return this;
}
/**
* Request just the length of the match for results.
*
* @return {@code this} {@link StrAlgoArgs}.
*/
public StrAlgoArgs justLen() {
justLen = true;
return this;
}
/**
* Request match len for results.
*
* @return {@code this} {@link StrAlgoArgs}.
*/
public StrAlgoArgs withMatchLen() {
withMatchLen = true;
return this;
}
/**
* Request match position in each strings for results.
*
* @return {@code this} {@link StrAlgoArgs}.
*/
public StrAlgoArgs withIdx() {
withIdx = true;
return this;
}
public StrAlgoArgs by(By by, String... keys) {
LettuceAssert.notNull(by, "By-selector must not be null");
LettuceAssert.notEmpty(keys, "Keys must not be empty");
this.by = by;
this.keys = keys;
return this;
}
public boolean isWithIdx() {
return withIdx;
}
public StrAlgoArgs charset(Charset charset) {
LettuceAssert.notNull(charset, "Charset must not be null");
this.charset = charset;
return this;
}
public enum By {
STRINGS, KEYS
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
args.add("LCS");
args.add(by.name());
for (String key : keys) {
if (by == By.STRINGS) {
args.add(key.getBytes(charset));
} else {
args.add(key);
}
}
if (justLen) {
args.add("LEN");
}
if (withIdx) {
args.add("IDX");
}
if (minMatchLen > 0) {
args.add("MINMATCHLEN");
args.add(minMatchLen);
}
if (withMatchLen) {
args.add("WITHMATCHLEN");
}
| 783
| 181
| 964
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/StreamMessage.java
|
StreamMessage
|
equals
|
class StreamMessage<K, V> {
private final K stream;
private final String id;
private final Map<K, V> body;
/**
* Create a new {@link StreamMessage}.
*
* @param stream the stream.
* @param id the message id.
* @param body map containing the message body.
*/
public StreamMessage(K stream, String id, Map<K, V> body) {
this.stream = stream;
this.id = id;
this.body = body;
}
public K getStream() {
return stream;
}
public String getId() {
return id;
}
/**
* @return the message body. Can be {@code null} for commands that do not return the message body.
*/
public Map<K, V> getBody() {
return body;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(stream, id, body);
}
@Override
public String toString() {
return String.format("StreamMessage[%s:%s]%s", stream, id, body);
}
}
|
if (this == o)
return true;
if (!(o instanceof StreamMessage))
return false;
StreamMessage<?, ?> that = (StreamMessage<?, ?>) o;
return Objects.equals(stream, that.stream) && Objects.equals(id, that.id) && Objects.equals(body, that.body);
| 328
| 89
| 417
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/TimeoutOptions.java
|
Builder
|
fixedTimeout
|
class Builder {
private boolean timeoutCommands = DEFAULT_TIMEOUT_COMMANDS;
private boolean applyConnectionTimeout = false;
private TimeoutSource source;
/**
* Enable command timeouts. Disabled by default, see {@link #DEFAULT_TIMEOUT_COMMANDS}.
*
* @return {@code this}
*/
public Builder timeoutCommands() {
return timeoutCommands(true);
}
/**
* Configure whether commands should timeout. Disabled by default, see {@link #DEFAULT_TIMEOUT_COMMANDS}.
*
* @param enabled {@code true} to enable timeout; {@code false} to disable timeouts.
* @return {@code this}
*/
public Builder timeoutCommands(boolean enabled) {
this.timeoutCommands = enabled;
return this;
}
/**
* Set a fixed timeout for all commands.
*
* @param duration the timeout {@link Duration}, must not be {@code null}.
* @return {@code this}
*/
public Builder fixedTimeout(Duration duration) {<FILL_FUNCTION_BODY>}
/**
* Configure a {@link TimeoutSource} that applies timeouts configured on the connection/client instance.
*
* @return {@code this}
*/
public Builder connectionTimeout() {
return timeoutSource(new DefaultTimeoutSource());
}
/**
* Set a {@link TimeoutSource} to obtain the timeout value per {@link RedisCommand}.
*
* @param source the timeout source.
* @return {@code this}
*/
public Builder timeoutSource(TimeoutSource source) {
LettuceAssert.notNull(source, "TimeoutSource must not be null");
timeoutCommands(true);
this.applyConnectionTimeout = source instanceof DefaultTimeoutSource;
this.source = source;
return this;
}
/**
* Create a new instance of {@link TimeoutOptions}.
*
* @return new instance of {@link TimeoutOptions}
*/
public TimeoutOptions build() {
if (timeoutCommands) {
if (source == null) {
throw new IllegalStateException("TimeoutSource is required for enabled timeouts");
}
}
return new TimeoutOptions(timeoutCommands, applyConnectionTimeout, source);
}
}
|
LettuceAssert.notNull(duration, "Duration must not be null");
return timeoutSource(new FixedTimeoutSource(duration.toNanos(), TimeUnit.NANOSECONDS));
| 586
| 52
| 638
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/TrackingArgs.java
|
Builder
|
prefixes
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link TrackingArgs} with {@literal CLIENT TRACKING ON}.
*
* @return new {@link TrackingArgs}.
* @see TrackingArgs#enabled(boolean)
*/
public static TrackingArgs enabled() {
return enabled(true);
}
/**
* Creates new {@link TrackingArgs} with {@literal CLIENT TRACKING ON} if {@code enabled} is {@code true}.
*
* @param enabled whether to enable key tracking for the currently connected client.
* @return new {@link TrackingArgs}.
* @see TrackingArgs#enabled(boolean)
*/
public static TrackingArgs enabled(boolean enabled) {
return new TrackingArgs().enabled(enabled);
}
}
/**
* Controls whether to enable key tracking for the currently connected client.
*
* @param enabled whether to enable key tracking for the currently connected client.
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs enabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Send redirection messages to the connection with the specified ID. The connection must exist, you can get the ID of such
* connection using {@code CLIENT ID}. If the connection we are redirecting to is terminated, when in RESP3 mode the
* connection with tracking enabled will receive tracking-redir-broken push messages in order to signal the condition.
*
* @param clientId process Id of the client for notification redirection.
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs redirect(long clientId) {
this.redirect = clientId;
return this;
}
/**
* Enable tracking in broadcasting mode. In this mode invalidation messages are reported for all the prefixes specified,
* regardless of the keys requested by the connection. Instead when the broadcasting mode is not enabled, Redis will track
* which keys are fetched using read-only commands, and will report invalidation messages only for such keys.
*
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs bcast() {
this.bcast = true;
return this;
}
/**
* For broadcasting, register a given key prefix, so that notifications will be provided only for keys starting with this
* string. This option can be given multiple times to register multiple prefixes. If broadcasting is enabled without this
* option, Redis will send notifications for every key.
*
* @param prefixes the key prefixes for broadcasting of change notifications. Encoded using
* {@link java.nio.charset.StandardCharsets#UTF_8}.
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs prefixes(String... prefixes) {
return prefixes(StandardCharsets.UTF_8, prefixes);
}
/**
* For broadcasting, register a given key prefix, so that notifications will be provided only for keys starting with this
* string. This option can be given multiple times to register multiple prefixes. If broadcasting is enabled without this
* option, Redis will send notifications for every key.
*
* @param charset the charset to use for {@code prefixes} encoding.
* @param prefixes the key prefixes for broadcasting of change notifications.
* @return {@code this} {@link TrackingArgs}.
*/
public TrackingArgs prefixes(Charset charset, String... prefixes) {<FILL_FUNCTION_BODY>
|
LettuceAssert.notNull(charset, "Charset must not be null");
this.prefixCharset = charset;
this.prefixes = prefixes;
return this;
| 911
| 49
| 960
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/XAddArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link XAddArgs} and setting {@literal MAXLEN}.
*
* @return new {@link XAddArgs} with {@literal MAXLEN} set.
* @see XAddArgs#maxlen(long)
*/
public static XAddArgs maxlen(long count) {
return new XAddArgs().maxlen(count);
}
/**
* Creates new {@link XAddArgs} and setting {@literal NOMKSTREAM}.
*
* @return new {@link XAddArgs} with {@literal NOMKSTREAM} set.
* @see XAddArgs#nomkstream()
* @since 6.1
*/
public static XAddArgs nomkstream() {
return new XAddArgs().nomkstream();
}
/**
* Creates new {@link XAddArgs} and setting {@literal MINID}.
*
* @param minid the oldest ID in the stream will be exactly the minimum between its original oldest ID and the specified
* threshold.
* @return new {@link XAddArgs} with {@literal MINID} set.
* @see XAddArgs#minId(String)
* @since 6.1
*/
public static XAddArgs minId(String minid) {
return new XAddArgs().minId(minid);
}
}
/**
* Specify the message {@code id}.
*
* @param id must not be {@code null}.
* @return {@code this}
*/
public XAddArgs id(String id) {
LettuceAssert.notNull(id, "Id must not be null");
this.id = id;
return this;
}
/**
* Limit stream to {@code maxlen} entries.
*
* @param maxlen number greater 0.
* @return {@code this}
*/
public XAddArgs maxlen(long maxlen) {
LettuceAssert.isTrue(maxlen > 0, "Maxlen must be greater 0");
this.maxlen = maxlen;
return this;
}
/**
* Limit stream entries by message Id.
*
* @param minid the oldest ID in the stream will be exactly the minimum between its original oldest ID and the specified
* threshold.
* @return {@code this}
* @since 6.1
*/
public XAddArgs minId(String minid) {
LettuceAssert.notNull(minid, "minId must not be null");
this.minid = minid;
return this;
}
/**
* The maximum number of entries to trim.
*
* @param limit has meaning only if {@link #approximateTrimming `~`} was set.
* @return {@code this}
* @since 6.1
*/
public XAddArgs limit(long limit) {
LettuceAssert.isTrue(limit > 0, "Limit must be greater 0");
this.limit = limit;
return this;
}
/**
* Apply efficient trimming for capped streams using the {@code ~} flag.
*
* @return {@code this}
*/
public XAddArgs approximateTrimming() {
return approximateTrimming(true);
}
/**
* Apply efficient trimming for capped streams using the {@code ~} flag.
*
* @param approximateTrimming {@code true} to apply efficient radix node trimming.
* @return {@code this}
*/
public XAddArgs approximateTrimming(boolean approximateTrimming) {
this.approximateTrimming = approximateTrimming;
return this;
}
/**
* Apply exact trimming for capped streams using the {@code =} flag.
*
* @return {@code this}
* @since 6.1
*/
public XAddArgs exactTrimming() {
return exactTrimming(true);
}
/**
* Apply exact trimming for capped streams using the {@code =} flag.
*
* @param exactTrimming {@code true} to apply exact radix node trimming.
* @return {@code this}
* @since 6.1
*/
public XAddArgs exactTrimming(boolean exactTrimming) {
this.exactTrimming = exactTrimming;
return this;
}
/**
* Do add the message if the stream does not already exist.
*
* @return {@code this}
* @since 6.1
*/
public XAddArgs nomkstream() {
return nomkstream(true);
}
/**
* Do add the message if the stream does not already exist.
*
* @param nomkstream {@code true} to not create a stream if it does not already exist.
* @return {@code this}
* @since 6.1
*/
public XAddArgs nomkstream(boolean nomkstream) {
this.nomkstream = nomkstream;
return this;
}
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (maxlen != null) {
args.add(CommandKeyword.MAXLEN);
if (approximateTrimming) {
args.add("~");
} else if (exactTrimming) {
args.add("=");
}
args.add(maxlen);
}
if (minid != null) {
args.add(CommandKeyword.MINID);
if (approximateTrimming) {
args.add("~");
} else if (exactTrimming) {
args.add("=");
}
args.add(minid);
}
if (limit != null && approximateTrimming) {
args.add(CommandKeyword.LIMIT).add(limit);
}
if (nomkstream) {
args.add(CommandKeyword.NOMKSTREAM);
}
if (id != null) {
args.add(id);
} else {
args.add("*");
}
| 1,360
| 268
| 1,628
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/XAutoClaimArgs.java
|
Builder
|
minIdleTime
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link XAutoClaimArgs} and set the {@code JUSTID} flag to return just the message id and do not increment
* the retry counter. The message body is not returned when calling {@code XAUTOCLAIM}.
*
* @param consumer
* @param minIdleTime
* @param startId
* @param <K>
* @return new {@link XAutoClaimArgs} with {@code minIdleTime} and {@code startId} configured.
*/
public static <K> XAutoClaimArgs<K> justid(Consumer<K> consumer, long minIdleTime, String startId) {
return new XAutoClaimArgs<K>().justid().consumer(consumer).minIdleTime(minIdleTime).startId(startId);
}
/**
* Creates new {@link XAutoClaimArgs} and set the {@code JUSTID} flag to return just the message id and do not increment
* the retry counter. The message body is not returned when calling {@code XAUTOCLAIM}.
*
* @param consumer
* @param minIdleTime
* @param startId
* @param <K>
* @return new {@link XAutoClaimArgs} with {@code minIdleTime} and {@code startId} configured.
*/
public static <K> XAutoClaimArgs<K> justid(Consumer<K> consumer, Duration minIdleTime, String startId) {
return new XAutoClaimArgs<K>().justid().consumer(consumer).minIdleTime(minIdleTime).startId(startId);
}
/**
* Creates new {@link XAutoClaimArgs}.
*
* @param consumer
* @param minIdleTime
* @param startId
* @param <K>
* @return new {@link XAutoClaimArgs} with {@code minIdleTime} and {@code startId} configured.
*/
public static <K> XAutoClaimArgs<K> xautoclaim(Consumer<K> consumer, long minIdleTime, String startId) {
return new XAutoClaimArgs<K>().consumer(consumer).minIdleTime(minIdleTime).startId(startId);
}
/**
* Creates new {@link XAutoClaimArgs}.
*
* @param consumer
* @param minIdleTime
* @param startId
* @param <K>
* @return new {@link XAutoClaimArgs} with {@code minIdleTime} and {@code startId} configured.
*/
public static <K> XAutoClaimArgs<K> xautoclaim(Consumer<K> consumer, Duration minIdleTime, String startId) {
return new XAutoClaimArgs<K>().consumer(consumer).minIdleTime(minIdleTime).startId(startId);
}
}
/**
* Configure the {@link Consumer}.
*
* @param consumer
* @return {@code this}.
*/
public XAutoClaimArgs<K> consumer(Consumer<K> consumer) {
LettuceAssert.notNull(consumer, "Consumer must not be null");
this.consumer = consumer;
return this;
}
/**
* The optional {@code count} argument, which defaults to {@code 100}, is the upper limit of the number of entries that the
* command attempts to claim.
*
* @param count
* @return {@code this}.
*/
public XAutoClaimArgs<K> count(long count) {
this.count = count;
return this;
}
/**
* The optional {@code JUSTID} argument changes the reply to return just an array of IDs of messages successfully claimed,
* without returning the actual message. Using this option means the retry counter is not incremented.
*
* @return {@code this}.
*/
public XAutoClaimArgs<K> justid() {
this.justid = true;
return this;
}
/**
* Return only messages that are idle for at least {@code milliseconds}.
*
* @param milliseconds min idle time.
* @return {@code this}.
*/
public XAutoClaimArgs<K> minIdleTime(long milliseconds) {
this.minIdleTime = milliseconds;
return this;
}
/**
* Return only messages that are idle for at least {@code minIdleTime}.
*
* @param minIdleTime min idle time.
* @return {@code this}.
*/
public XAutoClaimArgs<K> minIdleTime(Duration minIdleTime) {<FILL_FUNCTION_BODY>
|
LettuceAssert.notNull(minIdleTime, "Min idle time must not be null");
return minIdleTime(minIdleTime.toMillis());
| 1,234
| 46
| 1,280
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/XClaimArgs.java
|
Builder
|
minIdleTime
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link XClaimArgs} and set the {@code JUSTID} flag to return just the message id and do not increment the
* retry counter. The message body is not returned when calling {@code XCLAIM}.
*
* @return new {@link XClaimArgs} with min idle time set.
* @see XClaimArgs#justid()
* @since 5.3
*/
public static XClaimArgs justid() {
return new XClaimArgs().justid();
}
public static XClaimArgs minIdleTime(long milliseconds) {
return new XClaimArgs().minIdleTime(milliseconds);
}
/**
* Creates new {@link XClaimArgs} and set the minimum idle time.
*
* @return new {@link XClaimArgs} with min idle time set.
* @see XClaimArgs#minIdleTime(long)
*/
public static XClaimArgs minIdleTime(Duration minIdleTime) {<FILL_FUNCTION_BODY>}
}
|
LettuceAssert.notNull(minIdleTime, "Min idle time must not be null");
return minIdleTime(minIdleTime.toMillis());
| 302
| 46
| 348
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/XGroupCreateArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link XGroupCreateArgs} and set {@literal MKSTREAM}.
*
* @return new {@link XGroupCreateArgs} with {@literal MKSTREAM} set.
* @see XGroupCreateArgs#mkstream(boolean)
*/
public static XGroupCreateArgs mkstream() {
return mkstream(true);
}
/**
* Creates new {@link XGroupCreateArgs} and set {@literal MKSTREAM}.
*
* @param mkstream whether to apply {@literal MKSTREAM}.
* @return new {@link XGroupCreateArgs} with {@literal MKSTREAM} set.
* @see XGroupCreateArgs#mkstream(boolean)
*/
public static XGroupCreateArgs mkstream(boolean mkstream) {
return new XGroupCreateArgs().mkstream(mkstream);
}
/**
* Creates new {@link XGroupCreateArgs} and set {@literal ENTRIESREAD}.
*
* @param entriesRead number of read entries for lag tracking.
* @return new {@link XGroupCreateArgs} with {@literal ENTRIESREAD} set.
* @see XGroupCreateArgs#entriesRead(long)
* @since 6.2
*/
public static XGroupCreateArgs entriesRead(long entriesRead) {
return new XGroupCreateArgs().entriesRead(entriesRead);
}
}
/**
* Make a stream if it does not exists.
*
* @param mkstream whether to apply {@literal MKSTREAM}
* @return {@code this}
*/
public XGroupCreateArgs mkstream(boolean mkstream) {
this.mkstream = mkstream;
return this;
}
/**
* Configure the {@literal ENTRIESREAD} argument.
*
* @param entriesRead number of read entries for lag tracking.
*
* @return {@code this}
* @since 6.2
*/
public XGroupCreateArgs entriesRead(long entriesRead) {
this.entriesRead = entriesRead;
return this;
}
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (mkstream) {
args.add("MKSTREAM");
}
if (entriesRead != null) {
args.add("ENTRIESREAD").add(entriesRead);
}
| 601
| 60
| 661
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/XPendingArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Create a new {@link XPendingArgs} .
*
* @param consumer the consumer
* @param range the range of message Id's
* @param limit limit {@code COUNT}
* @return a new {@link XPendingArgs} with {@link Range} and {@link Limit} applied.
*/
public static <K> XPendingArgs<K> xpending(Consumer<K> consumer, Range<String> range, Limit limit) {
return new XPendingArgs<K>().consumer(consumer).range(range).limit(limit);
}
/**
* Create a new {@link XPendingArgs} .
*
* @param group the group
* @param range the range of message Id's
* @param limit limit {@code COUNT}
* @return a new {@link XPendingArgs} with {@link Range} and {@link Limit} applied.
* @since 6.1.9
*/
public static <K> XPendingArgs<K> xpending(K group, Range<String> range, Limit limit) {
return new XPendingArgs<K>().group(group).range(range).limit(limit);
}
}
public XPendingArgs<K> range(Range<String> range) {
LettuceAssert.notNull(range, "Range must not be null");
this.range = range;
return this;
}
public XPendingArgs<K> consumer(Consumer<K> consumer) {
LettuceAssert.notNull(consumer, "Consumer must not be null");
this.consumer = consumer.getName();
return group(consumer.getGroup());
}
/**
*
* @param group
* @return
* @since 6.1.9
*/
public XPendingArgs<K> group(K group) {
LettuceAssert.notNull(group, "Group must not be null");
this.group = group;
return this;
}
public XPendingArgs<K> limit(Limit limit) {
LettuceAssert.notNull(limit, "Limit must not be null");
this.limit = limit;
return this;
}
/**
* Include only entries that are idle for {@link Duration}.
*
* @param timeout
* @return {@code this} {@link XPendingArgs}.
*/
public XPendingArgs<K> idle(Duration timeout) {
LettuceAssert.notNull(timeout, "Timeout must not be null");
return idle(timeout.toMillis());
}
/**
* Include only entries that are idle for {@code milliseconds}.
*
* @param milliseconds
* @return {@code this} {@link XPendingArgs}.
*/
public XPendingArgs<K> idle(long milliseconds) {
this.idle = milliseconds;
return this;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
args.addKey((K) group);
if (idle != null) {
args.add(CommandKeyword.IDLE).add(idle);
}
if (range.getLower().equals(Range.Boundary.unbounded())) {
args.add("-");
} else {
args.add(range.getLower().getValue());
}
if (range.getUpper().equals(Range.Boundary.unbounded())) {
args.add("+");
} else {
args.add(range.getUpper().getValue());
}
args.add(limit.isLimited() ? limit.getCount() : Long.MAX_VALUE);
if (consumer != null) {
args.addKey((K) consumer);
}
| 799
| 203
| 1,002
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/XReadArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Create a new {@link XReadArgs} and set {@literal BLOCK}.
*
* @param milliseconds time to block.
* @return new {@link XReadArgs} with {@literal BLOCK} set.
* @see XReadArgs#block(long)
*/
public static XReadArgs block(long milliseconds) {
return new XReadArgs().block(milliseconds);
}
/**
* Create a new {@link XReadArgs} and set {@literal BLOCK}.
*
* @param timeout time to block.
* @return new {@link XReadArgs} with {@literal BLOCK} set.
* @see XReadArgs#block(Duration)
*/
public static XReadArgs block(Duration timeout) {
LettuceAssert.notNull(timeout, "Block timeout must not be null");
return block(timeout.toMillis());
}
/**
* Create a new {@link XReadArgs} and set {@literal COUNT}.
*
* @param count
* @return new {@link XReadArgs} with {@literal COUNT} set.
*/
public static XReadArgs count(long count) {
return new XReadArgs().count(count);
}
/**
* Create a new {@link XReadArgs} and set {@literal NOACK}.
*
* @return new {@link XReadArgs} with {@literal NOACK} set.
* @see XReadArgs#noack(boolean)
*/
public static XReadArgs noack() {
return noack(true);
}
/**
* Create a new {@link XReadArgs} and set {@literal NOACK}.
*
* @param noack
* @return new {@link XReadArgs} with {@literal NOACK} set.
* @see XReadArgs#noack(boolean)
*/
public static XReadArgs noack(boolean noack) {
return new XReadArgs().noack(noack);
}
}
/**
* Perform a blocking read and wait up to {@code milliseconds} for a new stream message.
*
* @param milliseconds max time to wait.
* @return {@code this}.
*/
public XReadArgs block(long milliseconds) {
this.block = milliseconds;
return this;
}
/**
* Perform a blocking read and wait up to a {@link Duration timeout} for a new stream message.
*
* @param timeout max time to wait.
* @return {@code this}.
*/
public XReadArgs block(Duration timeout) {
LettuceAssert.notNull(timeout, "Block timeout must not be null");
return block(timeout.toMillis());
}
/**
* Limit read to {@code count} messages.
*
* @param count number of messages.
* @return {@code this}.
*/
public XReadArgs count(long count) {
this.count = count;
return this;
}
/**
* Use NOACK option to disable auto-acknowledgement. Only valid for {@literal XREADGROUP}.
*
* @param noack {@code true} to disable auto-ack.
* @return {@code this}.
*/
public XReadArgs noack(boolean noack) {
this.noack = noack;
return this;
}
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (block != null) {
args.add(CommandKeyword.BLOCK).add(block);
}
if (count != null) {
args.add(CommandKeyword.COUNT).add(count);
}
if (noack) {
args.add(CommandKeyword.NOACK);
}
| 926
| 89
| 1,015
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/XTrimArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link XTrimArgs} and setting {@literal MAXLEN}.
*
* @return new {@link XTrimArgs} with {@literal MAXLEN} set.
* @see XTrimArgs#maxlen(long)
*/
public static XTrimArgs maxlen(long count) {
return new XTrimArgs().maxlen(count);
}
/**
* Creates new {@link XTrimArgs} and setting {@literal MINID}.
*
* @param minid the oldest ID in the stream will be exactly the minimum between its original oldest ID and the specified
* threshold.
* @return new {@link XTrimArgs} with {@literal MINID} set.
* @see XTrimArgs#minId(String)
*/
public static XTrimArgs minId(String minid) {
return new XTrimArgs().minId(minid);
}
}
/**
* Limit stream to {@code maxlen} entries.
*
* @param maxlen number greater 0.
* @return {@code this}
*/
public XTrimArgs maxlen(long maxlen) {
LettuceAssert.isTrue(maxlen >= 0, "Maxlen must be greater or equal to 0");
this.maxlen = maxlen;
return this;
}
/**
* Limit stream entries by message Id.
*
* @param minid the oldest ID in the stream will be exactly the minimum between its original oldest ID and the specified
* threshold.
* @return {@code this}
*/
public XTrimArgs minId(String minid) {
LettuceAssert.notNull(minid, "minId must not be null");
this.minId = minid;
return this;
}
/**
* The maximum number of entries to trim.
*
* @param limit has meaning only if {@link #approximateTrimming `~`} was set.
* @return {@code this}
*/
public XTrimArgs limit(long limit) {
LettuceAssert.isTrue(limit >= 0, "Limit must be greater 0");
this.limit = limit;
return this;
}
/**
* Apply efficient trimming for capped streams using the {@code ~} flag.
*
* @return {@code this}
*/
public XTrimArgs approximateTrimming() {
return approximateTrimming(true);
}
/**
* Apply efficient trimming for capped streams using the {@code ~} flag.
*
* @param approximateTrimming {@code true} to apply efficient radix node trimming.
* @return {@code this}
*/
public XTrimArgs approximateTrimming(boolean approximateTrimming) {
this.approximateTrimming = approximateTrimming;
return this;
}
/**
* Apply exact trimming for capped streams using the {@code =} flag.
*
* @return {@code this}
*/
public XTrimArgs exactTrimming() {
return exactTrimming(true);
}
/**
* Apply exact trimming for capped streams using the {@code =} flag.
*
* @param exactTrimming {@code true} to apply exact radix node trimming.
* @return {@code this}
*/
public XTrimArgs exactTrimming(boolean exactTrimming) {
this.exactTrimming = exactTrimming;
return this;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (maxlen != null) {
args.add(CommandKeyword.MAXLEN);
if (approximateTrimming) {
args.add("~");
} else if (exactTrimming) {
args.add("=");
}
args.add(maxlen);
} else if (minId != null) {
args.add(CommandKeyword.MINID);
if (approximateTrimming) {
args.add("~");
} else if (exactTrimming) {
args.add("=");
}
args.add(minId);
}
if (limit != null && approximateTrimming) {
args.add(CommandKeyword.LIMIT).add(limit);
}
| 968
| 201
| 1,169
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ZAddArgs.java
|
Builder
|
build
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link ZAddArgs} and enabling {@literal NX}.
*
* @return new {@link ZAddArgs} with {@literal NX} enabled.
* @see ZAddArgs#nx()
*/
public static ZAddArgs nx() {
return new ZAddArgs().nx();
}
/**
* Creates new {@link ZAddArgs} and enabling {@literal XX}.
*
* @return new {@link ZAddArgs} with {@literal XX} enabled.
* @see ZAddArgs#xx()
*/
public static ZAddArgs xx() {
return new ZAddArgs().xx();
}
/**
* Creates new {@link ZAddArgs} and enabling {@literal CH}.
*
* @return new {@link ZAddArgs} with {@literal CH} enabled.
* @see ZAddArgs#ch()
*/
public static ZAddArgs ch() {
return new ZAddArgs().ch();
}
/**
* Creates new {@link ZAddArgs} and enabling {@literal GT}.
*
* @return new {@link ZAddArgs} with {@literal GT} enabled.
* @see ZAddArgs#gt()
* @since 6.1
*/
public static ZAddArgs gt() {
return new ZAddArgs().gt();
}
/**
* Creates new {@link ZAddArgs} and enabling {@literal LT}.
*
* @return new {@link ZAddArgs} with {@literal LT} enabled.
* @see ZAddArgs#lt()
* @since 6.1
*/
public static ZAddArgs lt() {
return new ZAddArgs().lt();
}
}
/**
* Don't update already existing elements. Always add new elements.
*
* @return {@code this} {@link ZAddArgs}.
*/
public ZAddArgs nx() {
this.nx = true;
return this;
}
/**
* Only update elements that already exist. Never add elements.
*
* @return {@code this} {@link ZAddArgs}.
*/
public ZAddArgs xx() {
this.xx = true;
return this;
}
/**
* Modify the return value from the number of new elements added, to the total number of elements changed.
*
* @return {@code this} {@link ZAddArgs}.
*/
public ZAddArgs ch() {
this.ch = true;
return this;
}
/**
* Only update existing elements if the new score is greater than the current score. This flag doesn't prevent adding new
* elements.
*
* @return {@code this} {@link ZAddArgs}.
* @since 6.1
*/
public ZAddArgs gt() {
this.gt = true;
this.lt = false;
return this;
}
/**
* Only update existing elements if the new score is less than the current score. This flag doesn't prevent adding new
* elements.
*
* @return {@code this} {@link ZAddArgs}.
* @since 6.1
*/
public ZAddArgs lt() {
this.lt = true;
this.gt = false;
return this;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>
|
if (nx) {
args.add(NX);
}
if (xx) {
args.add(XX);
}
if (gt) {
args.add("GT");
}
if (lt) {
args.add("LT");
}
if (ch) {
args.add(CH);
}
| 918
| 100
| 1,018
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ZAggregateArgs.java
|
Builder
|
weights
|
class Builder {
/**
* Utility constructor.
*/
Builder() {
}
/**
* Creates new {@link ZAggregateArgs} setting {@literal WEIGHTS}.
*
* @return new {@link ZAddArgs} with {@literal WEIGHTS} set.
* @see ZAggregateArgs#weights(double...)
*/
public static ZAggregateArgs weights(double... weights) {
return new ZAggregateArgs().weights(weights);
}
/**
* Creates new {@link ZAggregateArgs} setting {@literal AGGREGATE SUM}.
*
* @return new {@link ZAddArgs} with {@literal AGGREGATE SUM} set.
* @see ZAggregateArgs#sum()
*/
public static ZAggregateArgs sum() {
return new ZAggregateArgs().sum();
}
/**
* Creates new {@link ZAggregateArgs} setting {@literal AGGREGATE MIN}.
*
* @return new {@link ZAddArgs} with {@literal AGGREGATE MIN} set.
* @see ZAggregateArgs#sum()
*/
public static ZAggregateArgs min() {
return new ZAggregateArgs().min();
}
/**
* Creates new {@link ZAggregateArgs} setting {@literal AGGREGATE MAX}.
*
* @return new {@link ZAddArgs} with {@literal AGGREGATE MAX} set.
* @see ZAggregateArgs#sum()
*/
public static ZAggregateArgs max() {
return new ZAggregateArgs().max();
}
}
/**
* Specify a multiplication factor for each input sorted set.
*
* @param weights must not be {@code null}.
* @return {@code this} {@link ZAggregateArgs}.
*/
public ZAggregateArgs weights(double... weights) {<FILL_FUNCTION_BODY>
|
LettuceAssert.notNull(weights, "Weights must not be null");
this.weights = new ArrayList<>(weights.length);
for (double weight : weights) {
this.weights.add(weight);
}
return this;
| 490
| 72
| 562
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/ZStoreArgs.java
|
Builder
|
weights
|
class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link ZStoreArgs} setting {@literal WEIGHTS} using long.
*
* @return new {@link ZAddArgs} with {@literal WEIGHTS} set.
* @see ZStoreArgs#weights(long[])
* @deprecated use {@link #weights(double...)}.
*/
@Deprecated
public static ZStoreArgs weights(long[] weights) {
return new ZStoreArgs().weights(toDoubleArray(weights));
}
/**
* Creates new {@link ZStoreArgs} setting {@literal WEIGHTS}.
*
* @return new {@link ZAddArgs} with {@literal WEIGHTS} set.
* @see ZStoreArgs#weights(double...)
*/
public static ZStoreArgs weights(double... weights) {
return new ZStoreArgs().weights(weights);
}
/**
* Creates new {@link ZStoreArgs} setting {@literal AGGREGATE SUM}.
*
* @return new {@link ZAddArgs} with {@literal AGGREGATE SUM} set.
* @see ZStoreArgs#sum()
*/
public static ZStoreArgs sum() {
return new ZStoreArgs().sum();
}
/**
* Creates new {@link ZStoreArgs} setting {@literal AGGREGATE MIN}.
*
* @return new {@link ZAddArgs} with {@literal AGGREGATE MIN} set.
* @see ZStoreArgs#sum()
*/
public static ZStoreArgs min() {
return new ZStoreArgs().min();
}
/**
* Creates new {@link ZStoreArgs} setting {@literal AGGREGATE MAX}.
*
* @return new {@link ZAddArgs} with {@literal AGGREGATE MAX} set.
* @see ZStoreArgs#sum()
*/
public static ZStoreArgs max() {
return new ZStoreArgs().max();
}
}
/**
* Specify a multiplication factor for each input sorted set.
*
* @param weights must not be {@code null}.
* @return {@code this} {@link ZStoreArgs}.
* @deprecated use {@link #weights(double...)}
*/
@Deprecated
public static ZStoreArgs weights(long[] weights) {<FILL_FUNCTION_BODY>
|
LettuceAssert.notNull(weights, "Weights must not be null");
return new ZStoreArgs().weights(toDoubleArray(weights));
| 619
| 44
| 663
|
<methods>public non-sealed void <init>() ,public void build(CommandArgs<K,V>) ,public io.lettuce.core.ZAggregateArgs max() ,public io.lettuce.core.ZAggregateArgs min() ,public io.lettuce.core.ZAggregateArgs sum() ,public transient io.lettuce.core.ZAggregateArgs weights(double[]) <variables>private io.lettuce.core.ZAggregateArgs.Aggregate aggregate,private List<java.lang.Double> weights
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/cluster/AbstractClusterNodeConnectionFactory.java
|
AbstractClusterNodeConnectionFactory
|
getSocketAddress
|
class AbstractClusterNodeConnectionFactory<K, V> implements ClusterNodeConnectionFactory<K, V> {
private static final InternalLogger logger = InternalLoggerFactory
.getInstance(PooledClusterConnectionProvider.DefaultClusterNodeConnectionFactory.class);
private final ClientResources clientResources;
private volatile Partitions partitions;
/**
* Create a new {@link AbstractClusterNodeConnectionFactory} given {@link ClientResources}.
*
* @param clientResources must not be {@code null}.
*/
public AbstractClusterNodeConnectionFactory(ClientResources clientResources) {
this.clientResources = clientResources;
}
public void setPartitions(Partitions partitions) {
this.partitions = partitions;
}
public Partitions getPartitions() {
return partitions;
}
/**
* Get a {@link Mono} of {@link SocketAddress} for a
* {@link io.lettuce.core.cluster.ClusterNodeConnectionFactory.ConnectionKey}.
* <p>
* This {@link Supplier} resolves the requested endpoint on each {@link Supplier#get()}.
*
* @param connectionKey must not be {@code null}.
* @return
*/
Mono<SocketAddress> getSocketAddressSupplier(ConnectionKey connectionKey) {
return Mono.fromCallable(() -> {
if (connectionKey.nodeId != null) {
SocketAddress socketAddress = getSocketAddress(connectionKey.nodeId);
logger.debug("Resolved SocketAddress {} using for Cluster node {}", socketAddress, connectionKey.nodeId);
return socketAddress;
}
SocketAddress socketAddress = resolve(RedisURI.create(connectionKey.host, connectionKey.port));
logger.debug("Resolved SocketAddress {} using for Cluster node at {}:{}", socketAddress, connectionKey.host,
connectionKey.port);
return socketAddress;
});
}
/**
* Get the {@link SocketAddress} for a {@code nodeId} from {@link Partitions}.
*
* @param nodeId
* @return the {@link SocketAddress}.
* @throws IllegalArgumentException if {@code nodeId} cannot be looked up.
*/
private SocketAddress getSocketAddress(String nodeId) {<FILL_FUNCTION_BODY>}
private SocketAddress resolve(RedisURI redisURI) {
return clientResources.socketAddressResolver().resolve(redisURI);
}
}
|
for (RedisClusterNode partition : partitions) {
if (partition.getNodeId().equals(nodeId)) {
return resolve(partition.getUri());
}
}
throw new IllegalArgumentException(String.format("Cannot resolve a RedisClusterNode for nodeId %s", nodeId));
| 610
| 77
| 687
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/cluster/AbstractNodeSelection.java
|
AbstractNodeSelection
|
asMap
|
class AbstractNodeSelection<API, CMD, K, V> implements NodeSelectionSupport<API, CMD> {
@Override
public Map<RedisClusterNode, API> asMap() {<FILL_FUNCTION_BODY>}
@Override
public int size() {
return nodes().size();
}
@Override
public RedisClusterNode node(int index) {
return nodes().get(index);
}
// This method is never called, the value is supplied by AOP magic, see NodeSelectionInvocationHandler
@Override
public CMD commands() {
return null;
}
@Override
public API commands(int index) {
return getApi(node(index)).join();
}
/**
* @return {@link Map} between a {@link RedisClusterNode} to its actual {@link StatefulRedisConnection}.
*/
protected Map<RedisClusterNode, CompletableFuture<? extends StatefulRedisConnection<K, V>>> statefulMap() {
return nodes().stream().collect(Collectors.toMap(redisClusterNode -> redisClusterNode, this::getConnection));
}
/**
* Template method to be implemented by implementing classes to obtain a {@link StatefulRedisConnection}.
*
* @param redisClusterNode must not be {@code null}.
* @return
*/
protected abstract CompletableFuture<? extends StatefulRedisConnection<K, V>> getConnection(
RedisClusterNode redisClusterNode);
/**
* Template method to be implemented by implementing classes to obtain a the API object given a {@link RedisClusterNode}.
*
* @param redisClusterNode must not be {@code null}.
* @return
*/
protected abstract CompletableFuture<API> getApi(RedisClusterNode redisClusterNode);
/**
* @return List of involved nodes
*/
protected abstract List<RedisClusterNode> nodes();
}
|
List<RedisClusterNode> list = new ArrayList<>(nodes());
Map<RedisClusterNode, API> map = new HashMap<>(list.size(), 1);
list.forEach((key) -> map.put(key, getApi(key).join()));
return map;
| 485
| 76
| 561
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/cluster/ClusterClientOptions.java
|
Builder
|
mutate
|
class Builder extends ClientOptions.Builder {
private boolean closeStaleConnections = DEFAULT_CLOSE_STALE_CONNECTIONS;
private int maxRedirects = DEFAULT_MAX_REDIRECTS;
private boolean validateClusterNodeMembership = DEFAULT_VALIDATE_CLUSTER_MEMBERSHIP;
private Predicate<RedisClusterNode> nodeFilter = DEFAULT_NODE_FILTER;
private ClusterTopologyRefreshOptions topologyRefreshOptions = null;
protected Builder() {
readOnlyCommands(DEFAULT_READ_ONLY_COMMANDS);
}
@Override
public Builder autoReconnect(boolean autoReconnect) {
super.autoReconnect(autoReconnect);
return this;
}
/**
* @param bufferUsageRatio the buffer usage ratio. Must be between {@code 0} and {@code 2^31-1}, typically a value
* between 1 and 10 representing 50% to 90%.
* @return {@code this}
* @deprecated since 6.0 in favor of {@link DecodeBufferPolicy}.
*/
@Override
@Deprecated
public Builder bufferUsageRatio(int bufferUsageRatio) {
super.bufferUsageRatio(bufferUsageRatio);
return this;
}
/**
*
* @param cancelCommandsOnReconnectFailure true/false
* @return
* @deprecated since 6.2, to be removed with 7.0. This feature is unsafe and may cause protocol offsets if true (i.e.
* Redis commands are completed with previous command values).
*/
@Override
@Deprecated
public Builder cancelCommandsOnReconnectFailure(boolean cancelCommandsOnReconnectFailure) {
super.cancelCommandsOnReconnectFailure(cancelCommandsOnReconnectFailure);
return this;
}
@Override
public Builder decodeBufferPolicy(DecodeBufferPolicy decodeBufferPolicy) {
super.decodeBufferPolicy(decodeBufferPolicy);
return this;
}
@Override
public Builder disconnectedBehavior(DisconnectedBehavior disconnectedBehavior) {
super.disconnectedBehavior(disconnectedBehavior);
return this;
}
/**
* Number of maximal cluster redirects ({@literal -MOVED} and {@literal -ASK}) to follow in case a key was moved from
* one node to another node. Defaults to {@literal 5}. See {@link ClusterClientOptions#DEFAULT_MAX_REDIRECTS}.
*
* @param maxRedirects the limit of maximal cluster redirects
* @return {@code this}
*/
public Builder maxRedirects(int maxRedirects) {
this.maxRedirects = maxRedirects;
return this;
}
@Override
public Builder pingBeforeActivateConnection(boolean pingBeforeActivateConnection) {
super.pingBeforeActivateConnection(pingBeforeActivateConnection);
return this;
}
@Override
public Builder protocolVersion(ProtocolVersion protocolVersion) {
super.protocolVersion(protocolVersion);
return this;
}
@Override
public Builder suspendReconnectOnProtocolFailure(boolean suspendReconnectOnProtocolFailure) {
super.suspendReconnectOnProtocolFailure(suspendReconnectOnProtocolFailure);
return this;
}
@Override
public Builder publishOnScheduler(boolean publishOnScheduler) {
super.publishOnScheduler(publishOnScheduler);
return this;
}
@Override
public Builder readOnlyCommands(ReadOnlyCommands.ReadOnlyPredicate readOnlyCommands) {
super.readOnlyCommands(readOnlyCommands);
return this;
}
@Override
public Builder requestQueueSize(int requestQueueSize) {
super.requestQueueSize(requestQueueSize);
return this;
}
@Override
public Builder scriptCharset(Charset scriptCharset) {
super.scriptCharset(scriptCharset);
return this;
}
@Override
public Builder socketOptions(SocketOptions socketOptions) {
super.socketOptions(socketOptions);
return this;
}
@Override
public Builder sslOptions(SslOptions sslOptions) {
super.sslOptions(sslOptions);
return this;
}
@Override
public Builder timeoutOptions(TimeoutOptions timeoutOptions) {
super.timeoutOptions(timeoutOptions);
return this;
}
/**
* Sets the {@link ClusterTopologyRefreshOptions} for detailed control of topology updates.
*
* @param topologyRefreshOptions the {@link ClusterTopologyRefreshOptions}
* @return {@code this}
*/
public Builder topologyRefreshOptions(ClusterTopologyRefreshOptions topologyRefreshOptions) {
this.topologyRefreshOptions = topologyRefreshOptions;
return this;
}
/**
* Validate the cluster node membership before allowing connections to a cluster node. Defaults to {@code true}. See
* {@link ClusterClientOptions#DEFAULT_VALIDATE_CLUSTER_MEMBERSHIP}.
*
* @param validateClusterNodeMembership {@code true} if validation is enabled.
* @return {@code this}
*/
public Builder validateClusterNodeMembership(boolean validateClusterNodeMembership) {
this.validateClusterNodeMembership = validateClusterNodeMembership;
return this;
}
/**
* Provide a {@link Predicate node filter} to filter cluster nodes from
* {@link io.lettuce.core.cluster.models.partitions.Partitions}.
*
* @param nodeFilter must not be {@code null}.
* @return {@code this}
* @since 6.1.6
*/
public Builder nodeFilter(Predicate<RedisClusterNode> nodeFilter) {
LettuceAssert.notNull(nodeFilter, "NodeFilter must not be null");
this.nodeFilter = nodeFilter;
return this;
}
/**
* Create a new instance of {@link ClusterClientOptions}
*
* @return new instance of {@link ClusterClientOptions}
*/
public ClusterClientOptions build() {
return new ClusterClientOptions(this);
}
}
/**
* Returns a builder to create new {@link ClusterClientOptions} whose settings are replicated from the current
* {@link ClusterClientOptions}.
*
* @return a {@link ClusterClientOptions.Builder} to create new {@link ClusterClientOptions} whose settings are replicated
* from the current {@link ClusterClientOptions}.
*
* @since 5.1
*/
public ClusterClientOptions.Builder mutate() {<FILL_FUNCTION_BODY>
|
Builder builder = new Builder();
builder.autoReconnect(isAutoReconnect())
.cancelCommandsOnReconnectFailure(isCancelCommandsOnReconnectFailure())
.decodeBufferPolicy(getDecodeBufferPolicy())
.disconnectedBehavior(getDisconnectedBehavior()).maxRedirects(getMaxRedirects())
.publishOnScheduler(isPublishOnScheduler()).pingBeforeActivateConnection(isPingBeforeActivateConnection())
.protocolVersion(getConfiguredProtocolVersion()).readOnlyCommands(getReadOnlyCommands())
.requestQueueSize(getRequestQueueSize())
.scriptCharset(getScriptCharset()).socketOptions(getSocketOptions()).sslOptions(getSslOptions())
.suspendReconnectOnProtocolFailure(isSuspendReconnectOnProtocolFailure()).timeoutOptions(getTimeoutOptions())
.topologyRefreshOptions(getTopologyRefreshOptions())
.validateClusterNodeMembership(isValidateClusterNodeMembership()).nodeFilter(getNodeFilter());
return builder;
| 1,691
| 249
| 1,940
|
<methods>public static io.lettuce.core.ClientOptions.Builder builder() ,public static io.lettuce.core.ClientOptions copyOf(io.lettuce.core.ClientOptions) ,public static io.lettuce.core.ClientOptions create() ,public int getBufferUsageRatio() ,public io.lettuce.core.protocol.ProtocolVersion getConfiguredProtocolVersion() ,public io.lettuce.core.protocol.DecodeBufferPolicy getDecodeBufferPolicy() ,public io.lettuce.core.ClientOptions.DisconnectedBehavior getDisconnectedBehavior() ,public io.lettuce.core.protocol.ProtocolVersion getProtocolVersion() ,public io.lettuce.core.protocol.ReadOnlyCommands.ReadOnlyPredicate getReadOnlyCommands() ,public int getRequestQueueSize() ,public java.nio.charset.Charset getScriptCharset() ,public io.lettuce.core.SocketOptions getSocketOptions() ,public io.lettuce.core.SslOptions getSslOptions() ,public io.lettuce.core.TimeoutOptions getTimeoutOptions() ,public boolean isAutoReconnect() ,public boolean isCancelCommandsOnReconnectFailure() ,public boolean isPingBeforeActivateConnection() ,public boolean isPublishOnScheduler() ,public boolean isSuspendReconnectOnProtocolFailure() ,public io.lettuce.core.ClientOptions.Builder mutate() <variables>public static final boolean DEFAULT_AUTO_RECONNECT,public static final int DEFAULT_BUFFER_USAGE_RATIO,public static final boolean DEFAULT_CANCEL_CMD_RECONNECT_FAIL,public static final io.lettuce.core.ClientOptions.DisconnectedBehavior DEFAULT_DISCONNECTED_BEHAVIOR,public static final boolean DEFAULT_PING_BEFORE_ACTIVATE_CONNECTION,public static final io.lettuce.core.protocol.ProtocolVersion DEFAULT_PROTOCOL_VERSION,public static final boolean DEFAULT_PUBLISH_ON_SCHEDULER,public static final io.lettuce.core.protocol.ReadOnlyCommands.ReadOnlyPredicate DEFAULT_READ_ONLY_COMMANDS,public static final int DEFAULT_REQUEST_QUEUE_SIZE,public static final java.nio.charset.Charset DEFAULT_SCRIPT_CHARSET,public static final io.lettuce.core.SocketOptions DEFAULT_SOCKET_OPTIONS,public static final io.lettuce.core.SslOptions DEFAULT_SSL_OPTIONS,public static final boolean DEFAULT_SUSPEND_RECONNECT_PROTO_FAIL,public static final io.lettuce.core.TimeoutOptions DEFAULT_TIMEOUT_OPTIONS,private final non-sealed boolean autoReconnect,private final non-sealed boolean cancelCommandsOnReconnectFailure,private final non-sealed io.lettuce.core.protocol.DecodeBufferPolicy decodeBufferPolicy,private final non-sealed io.lettuce.core.ClientOptions.DisconnectedBehavior disconnectedBehavior,private final non-sealed boolean pingBeforeActivateConnection,private final non-sealed io.lettuce.core.protocol.ProtocolVersion protocolVersion,private final non-sealed boolean publishOnScheduler,private final non-sealed io.lettuce.core.protocol.ReadOnlyCommands.ReadOnlyPredicate readOnlyCommands,private final non-sealed int requestQueueSize,private final non-sealed java.nio.charset.Charset scriptCharset,private final non-sealed io.lettuce.core.SocketOptions socketOptions,private final non-sealed io.lettuce.core.SslOptions sslOptions,private final non-sealed boolean suspendReconnectOnProtocolFailure,private final non-sealed io.lettuce.core.TimeoutOptions timeoutOptions
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/cluster/ClusterCommand.java
|
ClusterCommand
|
getError
|
class ClusterCommand<K, V, T> extends CommandWrapper<K, V, T> implements RedisCommand<K, V, T> {
private int redirections;
private final int maxRedirections;
private final RedisChannelWriter retry;
private boolean completed;
/**
*
* @param command
* @param retry
* @param maxRedirections
*/
ClusterCommand(RedisCommand<K, V, T> command, RedisChannelWriter retry, int maxRedirections) {
super(command);
this.retry = retry;
this.maxRedirections = maxRedirections;
}
@Override
public void complete() {
if (isMoved() || isAsk()) {
boolean retryCommand = maxRedirections > redirections;
redirections++;
if (retryCommand) {
try {
retry.write(this);
} catch (Exception e) {
completeExceptionally(e);
}
return;
}
}
super.complete();
completed = true;
}
public boolean isMoved() {
if (getError() != null && getError().startsWith(CommandKeyword.MOVED.name())) {
return true;
}
return false;
}
public boolean isAsk() {
if (getError() != null && getError().startsWith(CommandKeyword.ASK.name())) {
return true;
}
return false;
}
@Override
public CommandArgs<K, V> getArgs() {
return command.getArgs();
}
@Override
public void encode(ByteBuf buf) {
command.encode(buf);
}
@Override
public boolean completeExceptionally(Throwable ex) {
boolean result = command.completeExceptionally(ex);
completed = true;
return result;
}
@Override
public ProtocolKeyword getType() {
return command.getType();
}
public boolean isCompleted() {
return completed;
}
@Override
public boolean isDone() {
return isCompleted();
}
public String getError() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [command=").append(command);
sb.append(", redirections=").append(redirections);
sb.append(", maxRedirections=").append(maxRedirections);
sb.append(']');
return sb.toString();
}
}
|
if (command.getOutput() != null) {
return command.getOutput().getError();
}
return null;
| 702
| 36
| 738
|
<methods>public void <init>(RedisCommand<K,V,T>) ,public void cancel() ,public void complete() ,public boolean completeExceptionally(java.lang.Throwable) ,public void encode(ByteBuf) ,public boolean equals(java.lang.Object) ,public CommandArgs<K,V> getArgs() ,public RedisCommand<K,V,T> getDelegate() ,public CommandOutput<K,V,T> getOutput() ,public io.lettuce.core.protocol.ProtocolKeyword getType() ,public int hashCode() ,public boolean isCancelled() ,public boolean isDone() ,public void onComplete(Consumer<? super T>) ,public void onComplete(BiConsumer<? super T,java.lang.Throwable>) ,public void setOutput(CommandOutput<K,V,T>) ,public java.lang.String toString() ,public static RedisCommand<K,V,T> unwrap(RedisCommand<K,V,T>) ,public static R unwrap(RedisCommand<K,V,T>, Class<R>) <variables>private static final java.lang.Object[] COMPLETE,private static final java.lang.Object[] EMPTY,private static final AtomicReferenceFieldUpdater<CommandWrapper#RAW,java.lang.Object[]> ONCOMPLETE,protected final non-sealed RedisCommand<K,V,T> command,private volatile java.lang.Object[] onComplete
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/cluster/ClusterFutureSyncInvocationHandler.java
|
ClusterFutureSyncInvocationHandler
|
handleInvocation
|
class ClusterFutureSyncInvocationHandler<K, V> extends AbstractInvocationHandler {
private final StatefulConnection<K, V> connection;
private final TimeoutProvider timeoutProvider;
private final Class<?> asyncCommandsInterface;
private final Class<?> nodeSelectionInterface;
private final Class<?> nodeSelectionCommandsInterface;
private final Object asyncApi;
private final Map<Method, Method> apiMethodCache = new ConcurrentHashMap<>(RedisClusterCommands.class.getMethods().length,
1);
private final Map<Method, Method> connectionMethodCache = new ConcurrentHashMap<>(5, 1);
private final Map<Method, MethodHandle> methodHandleCache = new ConcurrentHashMap<>(5, 1);
ClusterFutureSyncInvocationHandler(StatefulConnection<K, V> connection, Class<?> asyncCommandsInterface,
Class<?> nodeSelectionInterface, Class<?> nodeSelectionCommandsInterface, Object asyncApi) {
this.connection = connection;
this.timeoutProvider = new TimeoutProvider(() -> connection.getOptions().getTimeoutOptions(),
() -> connection.getTimeout().toNanos());
this.asyncCommandsInterface = asyncCommandsInterface;
this.nodeSelectionInterface = nodeSelectionInterface;
this.nodeSelectionCommandsInterface = nodeSelectionCommandsInterface;
this.asyncApi = asyncApi;
}
/**
* @see AbstractInvocationHandler#handleInvocation(Object, Method, Object[])
*/
@Override
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {<FILL_FUNCTION_BODY>}
private long getTimeoutNs(RedisFuture<?> command) {
if (command instanceof RedisCommand) {
return timeoutProvider.getTimeoutNs((RedisCommand) command);
}
return connection.getTimeout().toNanos();
}
private Object getConnection(Method method, Object[] args) throws Exception {
Method targetMethod = connectionMethodCache.computeIfAbsent(method, this::lookupMethod);
Object result = targetMethod.invoke(connection, args);
if (result instanceof StatefulRedisClusterConnection) {
StatefulRedisClusterConnection<K, V> connection = (StatefulRedisClusterConnection<K, V>) result;
return connection.sync();
}
if (result instanceof StatefulRedisConnection) {
StatefulRedisConnection<K, V> connection = (StatefulRedisConnection<K, V>) result;
return connection.sync();
}
throw new IllegalArgumentException("Cannot call method " + method);
}
private Method lookupMethod(Method key) {
try {
return connection.getClass().getMethod(key.getName(), key.getParameterTypes());
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
}
protected Object nodes(Predicate<RedisClusterNode> predicate, ConnectionIntent connectionIntent, boolean dynamic) {
NodeSelectionSupport<RedisCommands<K, V>, ?> selection = null;
if (connection instanceof StatefulRedisClusterConnectionImpl) {
StatefulRedisClusterConnectionImpl<K, V> impl = (StatefulRedisClusterConnectionImpl<K, V>) connection;
if (dynamic) {
selection = new DynamicNodeSelection<RedisCommands<K, V>, Object, K, V>(
impl.getClusterDistributionChannelWriter(), predicate, connectionIntent, StatefulRedisConnection::sync);
} else {
selection = new StaticNodeSelection<RedisCommands<K, V>, Object, K, V>(
impl.getClusterDistributionChannelWriter(), predicate, connectionIntent, StatefulRedisConnection::sync);
}
}
if (connection instanceof StatefulRedisClusterPubSubConnectionImpl) {
StatefulRedisClusterPubSubConnectionImpl<K, V> impl = (StatefulRedisClusterPubSubConnectionImpl<K, V>) connection;
selection = new StaticNodeSelection<RedisCommands<K, V>, Object, K, V>(impl.getClusterDistributionChannelWriter(),
predicate, connectionIntent, StatefulRedisConnection::sync);
}
NodeSelectionInvocationHandler h = new NodeSelectionInvocationHandler((AbstractNodeSelection<?, ?, ?, ?>) selection,
asyncCommandsInterface, timeoutProvider);
return Proxy.newProxyInstance(NodeSelectionSupport.class.getClassLoader(),
new Class<?>[] { nodeSelectionCommandsInterface, nodeSelectionInterface }, h);
}
private static MethodHandle lookupDefaultMethod(Method method) {
try {
return DefaultMethods.lookupMethodHandle(method);
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException(e);
}
}
}
|
try {
if (method.isDefault()) {
return methodHandleCache.computeIfAbsent(method, ClusterFutureSyncInvocationHandler::lookupDefaultMethod)
.bindTo(proxy).invokeWithArguments(args);
}
if (method.getName().equals("getConnection") && args.length > 0) {
return getConnection(method, args);
}
if (method.getName().equals("readonly") && args.length == 1) {
return nodes((Predicate<RedisClusterNode>) args[0], ConnectionIntent.READ, false);
}
if (method.getName().equals("nodes") && args.length == 1) {
return nodes((Predicate<RedisClusterNode>) args[0], ConnectionIntent.WRITE, false);
}
if (method.getName().equals("nodes") && args.length == 2) {
return nodes((Predicate<RedisClusterNode>) args[0], ConnectionIntent.WRITE, (Boolean) args[1]);
}
Method targetMethod = apiMethodCache.computeIfAbsent(method, key -> {
try {
return asyncApi.getClass().getMethod(key.getName(), key.getParameterTypes());
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
}
});
Object result = targetMethod.invoke(asyncApi, args);
if (result instanceof RedisFuture) {
RedisFuture<?> command = (RedisFuture<?>) result;
if (!method.getName().equals("exec") && !method.getName().equals("multi")) {
if (connection instanceof StatefulRedisConnection && ((StatefulRedisConnection) connection).isMulti()) {
return null;
}
}
return Futures.awaitOrCancel(command, getTimeoutNs(command), TimeUnit.NANOSECONDS);
}
return result;
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
| 1,205
| 501
| 1,706
|
<methods>public non-sealed void <init>() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public final java.lang.Object invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) throws java.lang.Throwable,public java.lang.String toString() <variables>private static final java.lang.Object[] NO_ARGS
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/cluster/ClusterNodeEndpoint.java
|
ClusterNodeEndpoint
|
retriggerCommands
|
class ClusterNodeEndpoint extends DefaultEndpoint {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(ClusterNodeEndpoint.class);
private final RedisChannelWriter clusterChannelWriter;
/**
* Initialize a new instance that handles commands from the supplied queue.
*
* @param clientOptions client options for this connection.
* @param clientResources client resources for this connection.
* @param clusterChannelWriter top-most channel writer.
*/
public ClusterNodeEndpoint(ClientOptions clientOptions, ClientResources clientResources,
RedisChannelWriter clusterChannelWriter) {
super(clientOptions, clientResources);
this.clusterChannelWriter = clusterChannelWriter;
}
/**
* Move queued and buffered commands from the inactive connection to the upstream command writer. This is done only if the
* current connection is disconnected and auto-reconnect is enabled (command-retries). If the connection would be open, we
* could get into a race that the commands we're moving are right now in processing. Alive connections can handle redirects
* and retries on their own.
*/
@Override
public CompletableFuture<Void> closeAsync() {
logger.debug("{} closeAsync()", logPrefix());
if (clusterChannelWriter != null) {
retriggerCommands(doExclusive(this::drainCommands));
}
return super.closeAsync();
}
protected void retriggerCommands(Collection<RedisCommand<?, ?, ?>> commands) {<FILL_FUNCTION_BODY>}
}
|
for (RedisCommand<?, ?, ?> queuedCommand : commands) {
if (queuedCommand == null || queuedCommand.isCancelled()) {
continue;
}
try {
clusterChannelWriter.write(queuedCommand);
} catch (RedisException e) {
queuedCommand.completeExceptionally(e);
}
}
| 386
| 97
| 483
|
<methods>public void <init>(io.lettuce.core.ClientOptions, io.lettuce.core.resource.ClientResources) ,public void addListener(io.lettuce.core.api.push.PushListener) ,public void close() ,public CompletableFuture<java.lang.Void> closeAsync() ,public void disconnect() ,public void flushCommands() ,public io.lettuce.core.resource.ClientResources getClientResources() ,public java.lang.String getId() ,public List<io.lettuce.core.api.push.PushListener> getPushListeners() ,public void initialState() ,public boolean isClosed() ,public void notifyChannelActive(Channel) ,public void notifyChannelInactive(Channel) ,public void notifyDrainQueuedCommands(io.lettuce.core.protocol.HasQueuedCommands) ,public void notifyException(java.lang.Throwable) ,public void registerConnectionWatchdog(io.lettuce.core.protocol.ConnectionWatchdog) ,public void removeListener(io.lettuce.core.api.push.PushListener) ,public void reset() ,public void setAutoFlushCommands(boolean) ,public void setConnectionFacade(io.lettuce.core.protocol.ConnectionFacade) ,public RedisCommand<K,V,T> write(RedisCommand<K,V,T>) ,public Collection<RedisCommand<K,V,?>> write(Collection<? extends RedisCommand<K,V,?>>) <variables>private static final java.util.concurrent.atomic.AtomicLong ENDPOINT_COUNTER,private static final AtomicIntegerFieldUpdater<io.lettuce.core.protocol.DefaultEndpoint> QUEUE_SIZE,private static final AtomicIntegerFieldUpdater<io.lettuce.core.protocol.DefaultEndpoint> STATUS,private static final int ST_CLOSED,private static final int ST_OPEN,private boolean autoFlushCommands,private final non-sealed boolean boundedQueues,private final non-sealed java.lang.String cachedEndpointId,protected volatile Channel channel,private final non-sealed io.lettuce.core.ClientOptions clientOptions,private final non-sealed io.lettuce.core.resource.ClientResources clientResources,private final CompletableFuture<java.lang.Void> closeFuture,private final non-sealed Queue<RedisCommand<?,?,?>> commandBuffer,private volatile java.lang.Throwable connectionError,private io.lettuce.core.protocol.ConnectionFacade connectionFacade,private io.lettuce.core.protocol.ConnectionWatchdog connectionWatchdog,private final boolean debugEnabled,private final non-sealed Queue<RedisCommand<?,?,?>> disconnectedBuffer,private final long endpointId,private boolean inActivation,private java.lang.String logPrefix,private static final InternalLogger logger,private final List<io.lettuce.core.api.push.PushListener> pushListeners,private volatile int queueSize,private final non-sealed boolean rejectCommandsWhileDisconnected,private final non-sealed io.lettuce.core.protocol.DefaultEndpoint.Reliability reliability,private final io.lettuce.core.protocol.SharedLock sharedLock,private volatile int status
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/cluster/ClusterPubSubConnectionProvider.java
|
PubSubNodeConnectionFactory
|
apply
|
class PubSubNodeConnectionFactory extends AbstractClusterNodeConnectionFactory<K, V> {
PubSubNodeConnectionFactory(ClientResources clientResources) {
super(clientResources);
}
@Override
public ConnectionFuture<StatefulRedisConnection<K, V>> apply(ConnectionKey key) {<FILL_FUNCTION_BODY>}
}
|
if (key.nodeId != null) {
// NodeId connections do not provide command recovery due to cluster reconfiguration
return redisClusterClient.connectPubSubToNodeAsync((RedisCodec) redisCodec, key.nodeId,
getSocketAddressSupplier(key));
}
// Host and port connections do provide command recovery due to cluster reconfiguration
return redisClusterClient.connectPubSubToNodeAsync((RedisCodec) redisCodec, key.host + ":" + key.port,
getSocketAddressSupplier(key));
| 88
| 140
| 228
|
<methods>public void <init>(io.lettuce.core.cluster.RedisClusterClient, io.lettuce.core.RedisChannelWriter, RedisCodec<K,V>, io.lettuce.core.cluster.ClusterEventListener) ,public void addListener(io.lettuce.core.cluster.api.push.RedisClusterPushListener) ,public void close() ,public CompletableFuture<java.lang.Void> closeAsync() ,public void closeStaleConnections() ,public void flushCommands() ,public StatefulRedisConnection<K,V> getConnection(io.lettuce.core.protocol.ConnectionIntent, int) ,public StatefulRedisConnection<K,V> getConnection(io.lettuce.core.protocol.ConnectionIntent, java.lang.String) ,public StatefulRedisConnection<K,V> getConnection(io.lettuce.core.protocol.ConnectionIntent, java.lang.String, int) ,public CompletableFuture<StatefulRedisConnection<K,V>> getConnectionAsync(io.lettuce.core.protocol.ConnectionIntent, int) ,public CompletableFuture<StatefulRedisConnection<K,V>> getConnectionAsync(io.lettuce.core.protocol.ConnectionIntent, java.lang.String) ,public CompletableFuture<StatefulRedisConnection<K,V>> getConnectionAsync(io.lettuce.core.protocol.ConnectionIntent, java.lang.String, int) ,public Collection<io.lettuce.core.cluster.api.push.RedisClusterPushListener> getPushListeners() ,public io.lettuce.core.ReadFrom getReadFrom() ,public void removeListener(io.lettuce.core.cluster.api.push.RedisClusterPushListener) ,public void reset() ,public void setAutoFlushCommands(boolean) ,public void setPartitions(io.lettuce.core.cluster.models.partitions.Partitions) ,public void setReadFrom(io.lettuce.core.ReadFrom) <variables>private boolean autoFlushCommands,private final non-sealed io.lettuce.core.cluster.ClusterEventListener clusterEventListener,private final non-sealed io.lettuce.core.RedisChannelWriter clusterWriter,private final non-sealed ClusterNodeConnectionFactory<K,V> connectionFactory,private final non-sealed AsyncConnectionProvider<io.lettuce.core.cluster.ClusterNodeConnectionFactory.ConnectionKey,StatefulRedisConnection<K,V>,ConnectionFuture<StatefulRedisConnection<K,V>>> connectionProvider,private final boolean debugEnabled,private static final InternalLogger logger,private final non-sealed io.lettuce.core.cluster.ClusterClientOptions options,private io.lettuce.core.cluster.models.partitions.Partitions partitions,private final List<io.lettuce.core.cluster.api.push.RedisClusterPushListener> pushListeners,private io.lettuce.core.ReadFrom readFrom,private final CompletableFuture<StatefulRedisConnection<K,V>>[][] readers,private final non-sealed io.lettuce.core.cluster.RedisClusterClient redisClusterClient,private final non-sealed RedisCodec<K,V> redisCodec,private final java.lang.Object stateLock,private final CompletableFuture<StatefulRedisConnection<K,V>>[] writers
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/cluster/CommandSet.java
|
CommandSet
|
hasCommand
|
class CommandSet {
private final Map<String, CommandDetail> commands;
private final EnumSet<CommandType> availableCommands = EnumSet.noneOf(CommandType.class);
public CommandSet(Collection<CommandDetail> commands) {
Map<String, CommandDetail> map = new HashMap<>();
for (CommandDetail command : commands) {
map.put(command.getName().toLowerCase(), command);
CommandType commandType = getCommandType(command);
if (commandType != null) {
availableCommands.add(commandType);
}
}
this.commands = map;
}
private static CommandType getCommandType(CommandDetail command) {
try {
return CommandType.valueOf(command.getName().toUpperCase(Locale.US));
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* Check whether Redis supports a particular command given a {@link ProtocolKeyword}. Querying commands using
* {@link CommandType} yields a better performance than other subtypes of {@link ProtocolKeyword}.
*
* @param commandName the command name, must not be {@code null}.
* @return {@code true} if the command is supported/available.
*/
public boolean hasCommand(ProtocolKeyword commandName) {<FILL_FUNCTION_BODY>}
}
|
if (commandName instanceof CommandType) {
return availableCommands.contains(commandName);
}
return commands.containsKey(commandName.name().toLowerCase());
| 351
| 48
| 399
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/cluster/DynamicNodeSelection.java
|
DynamicNodeSelection
|
getConnection
|
class DynamicNodeSelection<API, CMD, K, V> extends AbstractNodeSelection<API, CMD, K, V> {
private final ClusterDistributionChannelWriter writer;
private final Predicate<RedisClusterNode> selector;
private final ConnectionIntent connectionIntent;
private final Function<StatefulRedisConnection<K, V>, API> apiExtractor;
public DynamicNodeSelection(ClusterDistributionChannelWriter writer, Predicate<RedisClusterNode> selector,
ConnectionIntent connectionIntent, Function<StatefulRedisConnection<K, V>, API> apiExtractor) {
this.selector = selector;
this.connectionIntent = connectionIntent;
this.writer = writer;
this.apiExtractor = apiExtractor;
}
@Override
protected CompletableFuture<StatefulRedisConnection<K, V>> getConnection(RedisClusterNode redisClusterNode) {<FILL_FUNCTION_BODY>}
@Override
protected CompletableFuture<API> getApi(RedisClusterNode redisClusterNode) {
return getConnection(redisClusterNode).thenApply(apiExtractor);
}
@Override
protected List<RedisClusterNode> nodes() {
return writer.getPartitions().stream().filter(selector).collect(Collectors.toList());
}
}
|
RedisURI uri = redisClusterNode.getUri();
AsyncClusterConnectionProvider async = (AsyncClusterConnectionProvider) writer.getClusterConnectionProvider();
return async.getConnectionAsync(connectionIntent, uri.getHost(), uri.getPort());
| 330
| 64
| 394
|
<methods>public Map<io.lettuce.core.cluster.models.partitions.RedisClusterNode,API> asMap() ,public CMD commands() ,public API commands(int) ,public io.lettuce.core.cluster.models.partitions.RedisClusterNode node(int) ,public int size() <variables>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.