Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
918 | final Object otherNextVal = makeDbCall(iOtherDb, new ODbRelatedCall<Object>() {
public Object call() {
return otherIterator.next();
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java |
2,533 | new HashMap<String, Object>() {{
put("field", "value");
put("field2", "value2");
}})); | 0true
| src_test_java_org_elasticsearch_common_xcontent_support_XContentMapValuesTests.java |
3,400 | public static class SendEventOperation extends AbstractOperation {
private EventPacket eventPacket;
private int orderKey;
public SendEventOperation() {
}
public SendEventOperation(EventPacket eventPacket, int orderKey) {
this.eventPacket = eventPacket;
this.orderKey = orderKey;
}
@Override
public void run() throws Exception {
EventServiceImpl eventService = (EventServiceImpl) getNodeEngine().getEventService();
eventService.executeEvent(eventService.new EventPacketProcessor(eventPacket, orderKey));
}
@Override
public boolean returnsResponse() {
return true;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
eventPacket.writeData(out);
out.writeInt(orderKey);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
eventPacket = new EventPacket();
eventPacket.readData(in);
orderKey = in.readInt();
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_spi_impl_EventServiceImpl.java |
1,264 | public class OfferActivity extends BaseActivity<PricingContext> {
@Resource(name="blOfferService")
private OfferService offerService;
@Override
public PricingContext execute(PricingContext context) throws Exception {
Order order = context.getSeedData();
List<Offer> offers = offerService.buildOfferListForOrder(order);
offerService.applyOffersToOrder(offers, order);
context.setSeedData(order);
return context;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_workflow_OfferActivity.java |
366 | public interface Translation {
public Long getId();
public void setId(Long id);
public TranslatedEntity getEntityType();
public void setEntityType(TranslatedEntity entityType);
public String getEntityId();
public void setEntityId(String entityId);
public String getFieldName();
public void setFieldName(String fieldName);
public String getLocaleCode();
public void setLocaleCode(String localeCode);
public String getTranslatedValue();
public void setTranslatedValue(String translatedValue);
} | 0true
| common_src_main_java_org_broadleafcommerce_common_i18n_domain_Translation.java |
1,112 | public class ProductOptionValidationException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String errorCode;
public ProductOptionValidationException() {
super();
}
public ProductOptionValidationException(String message, String errorCode, Throwable cause) {
super(message, cause);
this.setErrorCode(errorCode);
}
public ProductOptionValidationException(String message, String errorCode) {
super(message);
this.setErrorCode(errorCode);
}
public ProductOptionValidationException(Throwable cause) {
super(cause);
}
public String getErrorCode() {
return errorCode;
}
protected void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_exception_ProductOptionValidationException.java |
3,442 | blobContainer.readBlob(transIt.next().name(), new BlobContainer.ReadBlobListener() {
BytesStreamOutput bos = new BytesStreamOutput();
boolean ignore = false;
@Override
public synchronized void onPartial(byte[] data, int offset, int size) throws IOException {
if (ignore) {
return;
}
bos.write(data, offset, size);
// if we don't have enough to read the header size of the first translog, bail and wait for the next one
if (bos.size() < 4) {
return;
}
BytesStreamInput si = new BytesStreamInput(bos.bytes());
int position;
while (true) {
try {
position = si.position();
if (position + 4 > bos.size()) {
break;
}
int opSize = si.readInt();
int curPos = si.position();
if ((si.position() + opSize) > bos.size()) {
break;
}
Translog.Operation operation = TranslogStreams.readTranslogOperation(si);
if ((si.position() - curPos) != opSize) {
logger.warn("mismatch in size, expected [{}], got [{}]", opSize, si.position() - curPos);
}
recoveryStatus.translog().addTranslogOperations(1);
indexShard.performRecoveryOperation(operation);
if (si.position() >= bos.size()) {
position = si.position();
break;
}
} catch (Throwable e) {
logger.warn("failed to retrieve translog after [{}] operations, ignoring the rest, considered corrupted", e, recoveryStatus.translog().currentTranslogOperations());
ignore = true;
latch.countDown();
return;
}
}
BytesStreamOutput newBos = new BytesStreamOutput();
int leftOver = bos.size() - position;
if (leftOver > 0) {
newBos.write(bos.bytes().array(), position, leftOver);
}
bos = newBos;
}
@Override
public synchronized void onCompleted() {
if (ignore) {
return;
}
if (!transIt.hasNext()) {
latch.countDown();
return;
}
blobContainer.readBlob(transIt.next().name(), this);
}
@Override
public void onFailure(Throwable t) {
failure.set(t);
latch.countDown();
}
}); | 0true
| src_main_java_org_elasticsearch_index_gateway_blobstore_BlobStoreIndexShardGateway.java |
1,568 | @SuppressWarnings("serial")
public class LabeledTable extends JPanel {
private final static Logger LOGGER = LoggerFactory.getLogger(LabeledTable.class);
/** The delay, in milliseconds, between the time that the column widths
* or order changes and the time that a change event is sent to
* listeners.
*/
static final int TABLE_SAVE_DELAY = 1000;
/** The delay, in milliseconds, between the time that the table detects
* a selection change and the time that a change event is sent to
* listeners.
*/
static final int SELECTION_CHANGE_DELAY = 50;
private static final int DEFAULT_ROW_HEIGHT = 14;
private static final int DEFAULT_COLUMN_WIDTH = 100;
private static final int ROW_HEADER_MARGIN = 0;
private Timer selectionChangeTimer = new Timer(SELECTION_CHANGE_DELAY, null);
private ListenerManager listenerManager = new ListenerManager();
private JTable table;
private JList rowHeaders;
private JList titleLabelList;
private Border headerBorder = null;
private NoSizeList<ContentAlignment> rowHeaderAlignments = new NoSizeList<ContentAlignment>();
private NoSizeList<ContentAlignment> columnHeaderAlignments = new NoSizeList<ContentAlignment>();
private NoSizeList<Integer> rowHeaderHeights = new NoSizeList<Integer>();
private NoSizeList<JVMFontFamily> rowHeaderFontNames = new NoSizeList<JVMFontFamily>();
private NoSizeList<JVMFontFamily> columnHeaderFontNames = new NoSizeList<JVMFontFamily>();
private NoSizeList<Integer> rowHeaderFontStyles = new NoSizeList<Integer>();
private NoSizeList<Integer> columnHeaderFontStyles = new NoSizeList<Integer>();
private NoSizeList<Integer> rowHeaderTextAttributes = new NoSizeList<Integer>();
private NoSizeList<BorderState> rowHeaderBorderStates = new NoSizeList<BorderState>();
private NoSizeList<Integer> columnHeaderTextAttributes = new NoSizeList<Integer>();
private NoSizeList<BorderState> columnHeaderBorderStates = new NoSizeList<BorderState>();
private NoSizeList<Color> rowHeaderFontColors = new NoSizeList<Color>();
private NoSizeList<Color> columnHeaderFontColors = new NoSizeList<Color>();
private NoSizeList<Color> rowHeaderBackgroundColors = new NoSizeList<Color>();
private NoSizeList<Color> columnHeaderBackgroundColors = new NoSizeList<Color>();
private NoSizeList<Color> rowHeaderBorderColors = new NoSizeList<Color>();
private NoSizeList<Color> columnHeaderBorderColors = new NoSizeList<Color>();
private NoSizeList<Integer> rowHeaderFontSizes = new NoSizeList<Integer>();
private NoSizeList<Integer> columnHeaderFontSizes = new NoSizeList<Integer>();
private boolean isRestoringSettings = false;
/**
* Creates a new table whose data is managed by a labeled table model.
*
* @param model the model holding the table data
*/
public LabeledTable(final LabeledTableModel model) {
selectionChangeTimer.setRepeats(false);
// Set up a timer action that notifies listeners of changes to the table
// selection.
selectionChangeTimer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fireSelectionChanged();
table.getTableHeader().repaint();
rowHeaders.repaint();
}
});
table = new JTable(model) {
@Override
public void setRowHeight(int row, int rowHeight) {
super.setRowHeight(row, rowHeight);
updateRowHeaders();
}
@Override
public void setRowHeight(int rowHeight) {
super.setRowHeight(rowHeight);
updateRowHeaders();
}
};
table.setAutoCreateColumnsFromModel(false);
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
table.setCellSelectionEnabled(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
setTableFont(table);
table.setRowHeight(DEFAULT_ROW_HEIGHT);
for (int col=0; col < model.getColumnCount(); ++col) {
table.getColumnModel().getColumn(col).setPreferredWidth(DEFAULT_COLUMN_WIDTH);
}
final TableCellRenderer defaultHeaderRenderer = table.getTableHeader().getDefaultRenderer();
final TableCellRenderer headerRenderer = new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel) defaultHeaderRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
ContentAlignment alignment = LabeledTable.this.getColumnHeaderAlignment(column);
label.setHorizontalAlignment(alignment.getComponentAlignment());
Border padding = BorderFactory.createEmptyBorder(0, 5, 0, 5);
if (headerBorder != null) label.setBorder(headerBorder);
label.setBorder(BorderFactory.createCompoundBorder(label.getBorder(), padding));
Font headerFont = new Font(LabeledTable.this.getColumnHeaderFontName(column).name(),
getColumnHeaderFontStyle(column).intValue(),
getColumnHeaderFontSize(column).intValue());
if (LabeledTable.this.getColumnHeaderTextAttribute(column).equals(TextAttribute.UNDERLINE_ON)) {
headerFont = headerFont.deriveFont(TableFormattingConstants.underlineMap);
}
label.setFont(headerFont);
// Set the table header height to fit the font size
int rowHeight = label.getFont().getSize() + 2;
Dimension d = label.getMinimumSize();
d.setSize(d.getWidth() + 2*ROW_HEADER_MARGIN, rowHeight);
label.setPreferredSize(d);
int c = column - table.getSelectedColumn();
if (c >= 0 && c < table.getSelectedColumnCount() &&
row == -1 && table.getSelectedRowCount() == table.getRowCount()) {
label.setBackground(table.getSelectionBackground());
label.setForeground(table.getSelectionForeground());
} else {
label.setBackground(table.getTableHeader().getBackground());
label.setForeground(table.getTableHeader().getForeground());
}
label.setForeground(getColumnHeaderFontColor(column));
label.setBackground(LabeledTable.this.getColumnHeaderBackgroundColor(column));
BorderState b = getColumnHeaderBorderState(column);
if (b != null) {
boolean hasNorth = b.hasNorthBorder();
boolean hasWest = b.hasWestBorder();
boolean hasSouth = b.hasSouthBorder();
boolean hasEast = b.hasEastBorder();
int w = TableCellFormatter.getBorderWidth();
Border outside = BorderFactory.createMatteBorder(hasNorth ? w : 0, hasWest ? w : 0, hasSouth ? w : 0, hasEast ? w : 0,
getColumnHeaderBorderColor(column));
Border inside = BorderFactory.createEmptyBorder(hasNorth ? 0 : w, hasWest ? 0 : w, hasSouth ? 0 : w, hasEast ? 0 : w);
label.setBorder(BorderFactory.createCompoundBorder(outside,inside));
}
return label;
}
};
table.getTableHeader().setDefaultRenderer(headerRenderer);
rowHeaders = new JList(model.getRowLabelModel());
rowHeaders.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
rowHeaders.setCellRenderer(new ListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected,
boolean hasFocus) {
JLabel label = (JLabel) defaultHeaderRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, 0, index);
ContentAlignment alignment = LabeledTable.this.getRowHeaderAlignment(index);
label.setHorizontalAlignment(alignment.getComponentAlignment());
Border padding = BorderFactory.createEmptyBorder(0, 5, 0, 5);
if (headerBorder != null) label.setBorder(headerBorder);
label.setBorder(BorderFactory.createCompoundBorder(label.getBorder(), padding));
Font headerFont = new Font(LabeledTable.this.getRowHeaderFontName(index).name(),
getRowHeaderFontStyle(index).intValue(),
getRowHeaderFontSize(index).intValue());
if (LabeledTable.this.getRowHeaderTextAttribute(index).equals(TextAttribute.UNDERLINE_ON)) {
headerFont = headerFont.deriveFont(TableFormattingConstants.underlineMap);
}
label.setFont(headerFont);
// Set the row header height to match the table row.
int rowHeight = table.getRowHeight(index);
Dimension d = label.getMinimumSize();
d.setSize(d.getWidth() + 2*ROW_HEADER_MARGIN, rowHeight);
label.setPreferredSize(d);
int r = index - table.getSelectedRow();
if (r >= 0 && r < table.getSelectedRowCount() &&
table.getSelectedColumnCount() == table.getColumnCount()) {
label.setBackground(table.getSelectionBackground());
label.setForeground(table.getSelectionForeground());
} else {
label.setBackground(LabeledTable.this.getRowHeaderBackgroundColor(index));
label.setForeground(table.getTableHeader().getForeground());
}
label.setForeground(getRowHeaderFontColor(index));
label.setBackground(LabeledTable.this.getRowHeaderBackgroundColor(index));
BorderState b = getRowHeaderBorderState(index);
if (b != null) {
boolean hasNorth = b.hasNorthBorder();
boolean hasWest = b.hasWestBorder();
boolean hasSouth = b.hasSouthBorder();
boolean hasEast = b.hasEastBorder();
int w = TableCellFormatter.getBorderWidth();
Border outside = BorderFactory.createMatteBorder(hasNorth ? w : 0, hasWest ? w : 0, hasSouth ? w : 0, hasEast ? w : 0,
getRowHeaderBorderColor(index));
Border inside = BorderFactory.createEmptyBorder(hasNorth ? 0 : w, hasWest ? 0 : w, hasSouth ? 0 : w, hasEast ? 0 : w);
label.setBorder(BorderFactory.createCompoundBorder(outside,inside));
}
return label;
}
});
titleLabelList = new JList(new String[]{" "});
titleLabelList.setEnabled(false);
setTableFont(titleLabelList);
titleLabelList.setCellRenderer(new ListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected,
boolean hasFocus) {
Component comp = headerRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, 0, 0);
// setTableFont(comp);
// Set the row header height to match the table header height.
// int rowHeight = comp.getFont().getSize() + 2; //no longer true with adjustable fonts
// Dimension d = comp.getMinimumSize();
// d.setSize(d.getWidth() + 2*ROW_HEADER_MARGIN, d.getHeight());
// comp.setPreferredSize(d);
comp.setBackground(Color.black);
return comp;
}
});
ListSelectionListener repaintingListener = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent arg0) {
table.getTableHeader().repaint();
rowHeaders.repaint();
}
};
table.getSelectionModel().addListSelectionListener(repaintingListener);
JPanel filler = new JPanel();
filler.setMinimumSize(new Dimension(0,0));
filler.setPreferredSize(new Dimension(0,0));
filler.setOpaque(false);
filler.setName("dummy");
ConstraintBuilder builder = new ConstraintBuilder(this);
builder.hvfill().weight(0,0).add(titleLabelList);
builder.nw().add(table.getTableHeader());
builder.span(2,1).hvfill().add(filler);
builder.nextRow().nw().vfill().add(rowHeaders);
builder.nw().vfill().add(table);
setBackground(LafColor.WINDOW);
setRowHeadersVisible(model.hasRowLabels() || model.isSkeleton());
setColumnHeadersVisible(model.hasColumnLabels() || model.isSkeleton());
model.addLabelChangeListener(new LabelChangeListener() {
@Override
public void labelsChanged() {
setRowHeadersVisible(model.hasRowLabels() || model.isSkeleton());
setColumnHeadersVisible(model.hasColumnLabels() || model.isSkeleton());
}
});
// Add a listener for clicks in the table header.
JTableHeader header = table.getTableHeader();
header.setReorderingAllowed(false);
header.addMouseListener(new TableHeaderListener(table, rowHeaders));
table.getColumnModel().addColumnModelListener(new TableColumnModelListener() {
@Override
public void columnAdded(TableColumnModelEvent e) {
possiblySaveStateAfterDelay();
}
@Override
public void columnMarginChanged(ChangeEvent e) {
possiblySaveStateAfterDelay();
}
@Override
public void columnMoved(TableColumnModelEvent e) {
// If the indices are different, a column was moved.
if (e.getFromIndex() != e.getToIndex()) {
possiblySaveStateAfterDelay();
}
}
@Override
public void columnRemoved(TableColumnModelEvent e) {
possiblySaveStateAfterDelay();
}
@Override
public void columnSelectionChanged(ListSelectionEvent e) {
// If the selection is not whole rows, then we should clear the
// row list selection and set the new row list anchor position.
if (table.getSelectedColumnCount() < table.getColumnCount()) {
if (!e.getValueIsAdjusting()) {
int anchorSelectionIndex = table.getSelectionModel().getAnchorSelectionIndex();
if (anchorSelectionIndex > -1) {
rowHeaders.getSelectionModel().setAnchorSelectionIndex(anchorSelectionIndex);
} else {
LOGGER.warn("table.getSelectionModel().getAnchorSelectionIndex(): {} is <= -1 (Row index out of range)", table.getSelectionModel().getAnchorSelectionIndex());
}
rowHeaders.clearSelection();
}
}
// Notify listeners that the selection has changed.
if (!e.getValueIsAdjusting()) {
selectionChangeTimer.restart();
}
}
});
rowHeaders.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
try {
if (!e.getValueIsAdjusting()
&& rowHeaders.getSelectedIndex() > -1) {
// Adjust the cell selection to match the row list selection.
// We have to set the column selection first, so that the table knows
// we've clicked on an entire row and doesn't try to deselect the
// row selection immediately.
table.setColumnSelectionInterval(0,
table.getColumnCount() - 1);
table.setRowSelectionInterval(
rowHeaders.getMinSelectionIndex(),
rowHeaders.getMaxSelectionIndex());
}
if (!e.getValueIsAdjusting()) {
selectionChangeTimer.restart();
}
} catch (Exception ex) {
LOGGER.warn("ListSelectionEvent Exception: {0}", ex);
}
}
});
model.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
if (e.getColumn() == TableModelEvent.ALL_COLUMNS || e.getType() != TableModelEvent.UPDATE) {
updateColumnsFromModel(null);
setRowHeadersVisible(LabeledTableModel.class.cast(table.getModel()).hasRowLabels());
setColumnHeadersVisible(LabeledTableModel.class.cast(table.getModel()).hasColumnLabels());
updateColumnsHeaderValuesOnly();
}
}
});
}
/**
* Updates the columns in the table to match the current columns in the model.
* Optionally, sets all column widths to new values, otherwise preserves the existing
* widths. If too few widths are supplied, or the model has new columns, then the rest
* of the columns will get a default width.
*
* @param columnWidths an array of new column widths, or null to preserve existing widths
*/
public void updateColumnsFromModel(int[] columnWidths) {
LabeledTableModel model = LabeledTableModel.class.cast(table.getModel());
TableColumnModel columnModel = table.getColumnModel();
if (columnWidths == null) {
columnWidths = new int[columnModel.getColumnCount()];
for (int i=0; i < columnWidths.length; ++i) {
columnWidths[i] = columnModel.getColumn(i).getPreferredWidth();
}
}
while (columnModel.getColumnCount() > 0) {
columnModel.removeColumn(columnModel.getColumn(0));
}
for (int i=0; i < model.getColumnCount(); ++i) {
TableColumn column = new TableColumn(i, (columnWidths.length > i ? columnWidths[i] : DEFAULT_COLUMN_WIDTH));
column.setHeaderValue(model.getColumnName(i));
columnModel.addColumn(column);
}
}
/**
* Update the header values of all columns.
*/
public void updateColumnsHeaderValuesOnly() {
LabeledTableModel model = LabeledTableModel.class.cast(table.getModel());
TableColumnModel columnModel = table.getColumnModel();
// Note: cannot iterate over model.getColumnCount() because it is sometimes zero
Enumeration<TableColumn> allCols = columnModel.getColumns();
int i = 0;
while (allCols.hasMoreElements()) {
TableColumn tc = allCols.nextElement();
tc.setHeaderValue(model.getColumnName(i++));
}
}
/**
* Sets a flag indicating that the table settings are being restored from
* persistent storage. While the flag is set, changes to table settings
* don't cause listeners to fire.
*
* @param flag true, if the settings are being restored, false otherwise
*/
public void setRestoringSettings(boolean flag) {
isRestoringSettings = flag;
}
private void possiblySaveStateAfterDelay() {
if (!isRestoringSettings) {
fireTableLayoutChanged();
}
}
/**
* Add a listener for table visual layout changes. If the
* same listener is added more than once, only the first call
* has effect.
*
* @param l
*/
public void addTableLayoutListener(TableLayoutListener l) {
listenerManager.addListener(TableLayoutListener.class, l);
}
/**
* Remove a listener for table visual layout changes. If the
* listener was never added, the call has no effect.
*
* @param l the listener to remove
*/
public void removeTableLayoutListener(TableLayoutListener l) {
listenerManager.removeListener(TableLayoutListener.class, l);
}
/**
* Add a listener for selection changes on the table.
*
* @param l the listener to add
*/
public void addTableSelectionListener(TableSelectionListener l) {
listenerManager.addListener(TableSelectionListener.class, l);
}
/**
* Remove a listener for selection changes on the table.
*
* @param l the listener to remove
*/
public void removeTableSelectionListener(TableSelectionListener l) {
listenerManager.removeListener(TableSelectionListener.class, l);
}
/**
* Notify listeners that the visual layout of the table has changed.
*/
protected void fireTableLayoutChanged() {
listenerManager.fireEvent(TableLayoutListener.class, new ListenerNotifier<TableLayoutListener>() {
@Override
public void notifyEvent(TableLayoutListener listener) {
listener.tableChanged(this);
}
});
}
/**
* Notify listeners that the table selection has changed.
*/
protected void fireSelectionChanged() {
final int[] selectedRows = table.getSelectedRows();
final int[] selectedColumns = table.getSelectedColumns();
listenerManager.fireEvent(TableSelectionListener.class, new ListenerNotifier<TableSelectionListener> () {
@Override
public void notifyEvent(TableSelectionListener listener) {
listener.selectionChanged(selectedRows, selectedColumns);
}
});
}
/**
* Returns the indices of all selected rows.
*
* @return an array of integers containing the indices of all selected rows, or an empty array if no row is selected
*/
public int[] getSelectedRows() {
return table.getSelectedRows();
}
/**
* Returns the indices of all selected columns.
*
* @return an array of integers containing the indices of all selected columns, or an empty array if no column is selected
*/
public int[] getSelectedColumns() {
return table.getSelectedColumns();
}
/**
* Gets the widths of each column.
*
* @return an array of column widths, in display order (not model order)
*/
public int[] getColumnWidths() {
int[] widths = new int[table.getColumnCount()];
for (int i=0; i<widths.length; ++i) {
TableColumn col = table.getColumnModel().getColumn(i);
widths[i] = col.getPreferredWidth();
}
return widths;
}
/**
* Sets the column widths to a given set of values.
*
* @param widths an array of column widths, one entry for each column
*/
public void setColumnWidths(int[] widths) {
boolean changed = false;
for (int i=0; i<table.getColumnCount(); ++i) {
int desiredWidth = DEFAULT_COLUMN_WIDTH;
if (widths!=null && i < widths.length && widths[i] > 0) {
desiredWidth = widths[i];
}
changed = setOneColumnWidth(i, desiredWidth) || changed;
}
}
/**
* Sets the widths of selected columns in the table to the same value.
*
* @param columnIndices an array with the indices of columns for which the width should be changed
* @param width the new width of the indicated columns
*/
public void setColumnWidths(int[] columnIndices, int width) {
boolean changed = false;
for (int columnIndex : columnIndices) {
changed = setOneColumnWidth(columnIndex, width) || changed;
}
}
private boolean setOneColumnWidth(int columnIndex, int width) {
TableColumn col = table.getColumnModel().getColumn(columnIndex);
if (width == col.getPreferredWidth()) {
return false;
} else {
col.setPreferredWidth(width);
return true;
}
}
/**
* Gets the order of model columns in the display.
*
* @return an array of model indices in the order they are shown in the displayed table
*/
public int[] getColumnOrder() {
int[] order = new int[table.getColumnCount()];
for (int i=0; i<order.length; ++i) {
TableColumn col = table.getColumnModel().getColumn(i);
order[i] = col.getModelIndex();
}
return order;
}
/**
* Sets the order of model columns in the display.
*
* @param order an array of model indices in the order they are to be shown in the displayed table
*/
public void setColumnOrder(int[] order) {
TableColumnModel colModel = table.getColumnModel();
for (int i=0; i<colModel.getColumnCount() && i<order.length; ++i) {
if (order[i]>=0 && order[i]!=colModel.getColumn(i).getModelIndex()) {
// The wrong column was found at position i. The right column
// must be to the right. Find the proper column for this position
// and move it into position.
for (int j=i+1; j < table.getColumnCount(); ++j) {
if (colModel.getColumn(j).getModelIndex() == order[i]) {
colModel.moveColumn(j, i);
break;
}
}
}
}
}
/**
* Gets the heights of each row.
*
* @return an array of row heights, in display order
*/
/* public int[] getRowHeights() {
int[] heights = new int[table.getRowCount()];
for (int i=0; i<heights.length; ++i) {
heights[i] = table.getRowHeight(i);
}
return heights;
}*/
/**
* Gets the heights of each row.
*
* @return an array of row heights, in display order
*/
public Integer[] getRowHeights() {
Integer[] rowHeights = new Integer[table.getRowCount()];
for (int i=0; i < rowHeights.length; ++i) {
rowHeights[i] = getRowHeight(i);
}
return rowHeights;
}
/**
* Gets the row height of a single row .
*
* @param rowIndex the index of the row
* @return the row height of the row
*/
public Integer getRowHeight(int rowIndex) {
Integer rowHeight = rowHeaderHeights.get(rowIndex);
return (rowHeight !=null ? rowHeight :
Integer.valueOf(TableFormattingConstants.defaultRowHeight));
}
/**
* Sets the row heights to a given set of values.
*
* @param heights an array of row heights, one entry for each column
*/
public void setRowHeights(int[] heights) {
rowHeaderHeights.clear();
for (int i=0; i < heights.length && i < getTable().getRowCount(); ++i) {
rowHeaderHeights.set(i, Integer.valueOf(heights[i]));
setOneRowHeight(i, heights[i]);
}
}
/**
* Sets the height of a single row. Both the table row height and
* the header row height are changed to match.
*
* @param rowIndices the indices of the rows to change
* @param height the new height of the rows
*/
public void setRowHeights(int[] rowIndices, int height) {
boolean changed = false;
for (int rowIndex : rowIndices) {
changed = setOneRowHeight(rowIndex, height) || changed;
}
}
/**
* Sets the height of a single row. Both the table row height and
* the header row height are changed to match.
*
* @param rowIndex the index of the rows to change
* @param height the new height of the rows
*/
public void setRowHeight(int rowIndex, int height) {
if (rowIndex < table.getRowCount()) {
while (rowHeaderHeights.size() < rowIndex-1) {
rowHeaderHeights.add(Integer.valueOf(TableFormattingConstants.defaultRowHeight));
}
rowHeaderHeights.set(rowIndex, Integer.valueOf(height));
}
boolean changed = false;
changed = setOneRowHeight(rowIndex, height) || changed;
}
private boolean setOneRowHeight(int rowIndex, int height) {
if (height == table.getRowHeight(rowIndex)) {
return false;
} else {
table.setRowHeight(rowIndex, height);
return true;
}
}
/**
* Sets the alignments of all row headers.
*
* @param alignments an array with the new row header alignments
*/
public void setRowHeaderAlignments(ContentAlignment[] alignments) {
rowHeaderAlignments.clear();
for (int i=0; i < alignments.length && i < getTable().getRowCount(); ++i) {
rowHeaderAlignments.set(i, alignments[i]);
}
}
/**
* Sets the alignment for a single row header.
*
* @param rowIndex the index of the row header to change
* @param newAlignment the new alignment for the for header
*/
public void setRowHeaderAlignment(int rowIndex, ContentAlignment newAlignment) {
if (rowIndex < table.getRowCount()) {
while (rowHeaderAlignments.size() < rowIndex-1) {
rowHeaderAlignments.add(ContentAlignment.LEFT);
}
rowHeaderAlignments.set(rowIndex, newAlignment);
}
}
/**
* Sets the Border States of all row headers.
*
* @param borderStates an array with the new row header BorderStates
*/
public void setRowHeaderBorderStates(BorderState[] borderStates) {
rowHeaderBorderStates.clear();
for (int i=0; i < borderStates.length && i < getTable().getRowCount(); ++i) {
rowHeaderBorderStates.set(i, borderStates[i]);
}
}
/**
* Sets the borderStates for a single row header.
*
* @param rowIndex the index of the row header to change
* @param newBorderState the new Border State for the for header
*/
public void setRowHeaderBorderState(int rowIndex, BorderState newBorderState) {
if (rowIndex < table.getRowCount()) {
while (rowHeaderBorderStates.size() < rowIndex-1) {
rowHeaderBorderStates.add(new BorderState(BorderEdge.NONE.value()));
}
rowHeaderBorderStates.set(rowIndex, newBorderState);
}
}
/**
* Gets the font names of all row headers.
*
* @return an array of row header font names
*/
public JVMFontFamily[] getRowHeaderFontNames() {
JVMFontFamily[] fontNames = new JVMFontFamily[table.getRowCount()];
for (int i=0; i < fontNames.length; ++i) {
fontNames[i] = getRowHeaderFontName(i);
}
return fontNames;
}
/**
* Gets the font name of a single row header.
*
* @param rowIndex the index of the row header
* @return the font name of the row header
*/
public JVMFontFamily getRowHeaderFontName(int rowIndex) {
JVMFontFamily fontName = rowHeaderFontNames.get(rowIndex);
return (fontName !=null ? fontName : TableFormattingConstants.defaultJVMFontFamily);
}
/**
* Sets the font names of all row headers.
*
* @param fontNames an array with the new row header alignments
*/
public void setRowHeaderFontNames(JVMFontFamily[] fontNames) {
rowHeaderFontNames.clear();
for (int i=0; i < fontNames.length && i < getTable().getRowCount(); ++i) {
rowHeaderFontNames.set(i, fontNames[i]);
}
}
/**
* Sets the font name for a single row header.
*
* @param rowIndex the index of the row header to change
* @param fontName the new font name for the row header
*/
public void setRowHeaderFontName(int rowIndex, JVMFontFamily fontName) {
if (rowIndex < table.getRowCount()) {
while (rowHeaderFontNames.size() < rowIndex-1) {
rowHeaderFontNames.add(TableFormattingConstants.defaultJVMFontFamily);
}
rowHeaderFontNames.set(rowIndex, fontName);
}
}
/**
* Sets the font colors of all row headers.
*
* @param fontColors an array with the new row font colors
*/
public void setRowHeaderFontColors(Color[] fontColors) {
rowHeaderFontColors.clear();
for (int i=0; i < fontColors.length && i < getTable().getRowCount(); ++i) {
rowHeaderFontColors.set(i, fontColors[i]);
}
}
/**
* Sets the font color for a single row header.
*
* @param rowIndex the index of the row header to change
* @param fontColor the new font color for the row header
*/
public void setRowHeaderFontColor(int rowIndex, Color fontColor) {
if (rowIndex < table.getRowCount()) {
while (rowHeaderFontColors.size() < rowIndex-1) {
rowHeaderFontColors.add(TableFormattingConstants.defaultFontColor);
}
rowHeaderFontColors.set(rowIndex, fontColor);
}
}
/**
* Sets the border colors of all row headers.
*
* @param borderColors an array with the new row header border colors
*/
public void setRowHeaderBorderColors(Color[] borderColors) {
rowHeaderBorderColors.clear();
for (int i=0; i < borderColors.length && i < getTable().getRowCount(); ++i) {
rowHeaderBorderColors.set(i, borderColors[i]);
}
}
/**
* Sets the border color for a single row header.
*
* @param rowIndex the index of the row header to change
* @param borderColor the new border color for the row header
*/
public void setRowHeaderBorderColor(int rowIndex, Color borderColor) {
if (rowIndex < table.getRowCount()) {
while (rowHeaderBorderColors.size() < rowIndex-1) {
rowHeaderBorderColors.add(TableFormattingConstants.defaultFontColor);
}
rowHeaderBorderColors.set(rowIndex, borderColor);
}
}
/**
* Sets the background colors of all row headers.
*
* @param bgColors an array with the new row background colors
*/
public void setRowHeaderBackgroundColors(Color[] bgColors) {
rowHeaderBackgroundColors.clear();
for (int i=0; i < bgColors.length && i < getTable().getRowCount(); ++i) {
rowHeaderBackgroundColors.set(i, bgColors[i]);
}
}
/**
* Sets the background color for a single row header.
*
* @param rowIndex the index of the row header to change
* @param bgColor the new background color for the row header
*/
public void setRowHeaderBackgroundColor(int rowIndex, Color bgColor) {
if (rowIndex < table.getRowCount()) {
while (rowHeaderBackgroundColors.size() < rowIndex-1) {
rowHeaderBackgroundColors.add(TableFormattingConstants.defaultBackgroundColor);
}
rowHeaderBackgroundColors.set(rowIndex, bgColor);
}
}
/**
* Sets the font styles of all row headers.
*
* @param fontStyles an array with the new row header font styles
*/
public void setRowHeaderFontStyles(Integer[] fontStyles) {
rowHeaderFontStyles.clear();
for (int i=0; i < fontStyles.length && i < getTable().getRowCount(); ++i) {
rowHeaderFontStyles.set(i, fontStyles[i]);
}
}
/**
* Sets the font style for a single row header.
*
* @param rowIndex the index of the row header to change
* @param fontStyle the new font style for the for header
*/
public void setRowHeaderFontStyle(int rowIndex, Integer fontStyle) {
if (rowIndex < table.getRowCount()) {
while (rowHeaderFontStyles.size() < rowIndex-1) {
rowHeaderFontStyles.add(Font.PLAIN);
}
rowHeaderFontStyles.set(rowIndex, Integer.valueOf(fontStyle));
}
}
/**
* Sets the Text Attributes of all row headers.
*
* @param attributes an array with the new row header TextAttributes
*/
public void setRowHeaderTextAttributes(Integer[] attributes) {
rowHeaderTextAttributes.clear();
for (int i=0; i < attributes.length && i < getTable().getRowCount(); ++i) {
rowHeaderTextAttributes.set(i, attributes[i]);
}
}
/**
* Sets the Text Attributes for a single row header.
*
* @param rowIndex the index of the row header to change
* @param attribute the new Text Attributes for the row header
*/
public void setRowHeaderTextAttribute(int rowIndex, Integer attribute) {
if (rowIndex < table.getRowCount()) {
while (rowHeaderTextAttributes.size() < rowIndex-1) {
rowHeaderTextAttributes.add(TableFormattingConstants.UNDERLINE_OFF);
}
rowHeaderTextAttributes.set(rowIndex, Integer.valueOf(attribute));
}
}
/**
* Sets the font sizes of all row headers.
*
* @param fontSizes an array with the new row header font sizes
*/
public void setRowHeaderFontSizes(Integer[] fontSizes) {
rowHeaderFontSizes.clear();
for (int i=0; i < fontSizes.length && i < getTable().getRowCount(); ++i) {
rowHeaderFontSizes.set(i, fontSizes[i]);
}
}
/**
* Sets the font size for a single row header.
*
* @param rowIndex the index of the row header to change
* @param fontSize the new font size for the row header
*/
public void setRowHeaderFontSize(int rowIndex, Integer fontSize) {
if (rowIndex < table.getRowCount()) {
while (rowHeaderFontSizes.size() < rowIndex-1) {
rowHeaderFontSizes.add(Integer.valueOf(TableFormattingConstants.defaultFontSize));
}
rowHeaderFontSizes.set(rowIndex, fontSize);
}
}
/**
* Sets the font styles of all column headers.
*
* @param fontStyles an array with the new column header font styles
*/
public void setColumnHeaderFontStyles(Integer[] fontStyles) {
columnHeaderFontStyles.clear();
for (int i=0; i < fontStyles.length && i < getTable().getColumnCount(); ++i) {
columnHeaderFontStyles.set(i, fontStyles[i]);
}
}
/**
* Sets the font style for a single column header.
*
* @param columnIndex the index of the column header to change
* @param fontStyle the new font style for the column header
*/
public void setColumnHeaderFontStyle(int columnIndex, Integer fontStyle) {
if (columnIndex < table.getColumnCount()) {
while (columnHeaderFontStyles.size() < columnIndex-1) {
columnHeaderFontStyles.add(Font.PLAIN);
}
columnHeaderFontStyles.set(columnIndex, fontStyle);
}
}
/**
* Sets the font sizes of all column headers.
*
* @param fontSizes an array with the new column header font sizes
*/
public void setColumnHeaderFontSizes(Integer[] fontSizes) {
columnHeaderFontSizes.clear();
for (int i=0; i < fontSizes.length && i < getTable().getRowCount(); ++i) {
columnHeaderFontSizes.set(i, fontSizes[i]);
}
}
/**
* Sets the font size for a single column header.
*
* @param columnIndex the index of the column header to change
* @param fontSize the new font size for the column header
*/
public void setColumnHeaderFontSize(int columnIndex, Integer fontSize) {
if (columnIndex < table.getColumnCount()) {
while (columnHeaderFontSizes.size() < columnIndex-1) {
columnHeaderFontSizes.add(TableFormattingConstants.defaultFontSize);
}
columnHeaderFontSizes.set(columnIndex, fontSize);
}
}
/**
* Gets the font names of all column headers.
*
* @return an array of column header font names
*/
public JVMFontFamily[] getColumnHeaderFontNames() {
JVMFontFamily[] fontNames = new JVMFontFamily[table.getColumnCount()];
for (int i=0; i < fontNames.length; ++i) {
fontNames[i] = getColumnHeaderFontName(i);
}
return fontNames;
}
/**
* Gets the font name of a single col header.
*
* @param colIndex the index of the col header
* @return the font name of the col header
*/
public JVMFontFamily getColumnHeaderFontName(int colIndex) {
JVMFontFamily fontName = columnHeaderFontNames.get(colIndex);
return (fontName !=null ? fontName : TableFormattingConstants.defaultJVMFontFamily);
}
/**
* Sets the font names of all col headers.
*
* @param fontNames an array with the new col header font names
*/
public void setColumnHeaderFontNames(JVMFontFamily[] fontNames) {
columnHeaderFontNames.clear();
for (int i=0; i < fontNames.length && i < getTable().getColumnCount(); ++i) {
columnHeaderFontNames.set(i, fontNames[i]);
}
}
/**
* Sets the font name for a single col header.
*
* @param columnIndex the index of the col header to change
* @param fontName the new font name for the col header
*/
public void setColumnHeaderFontName(int columnIndex, JVMFontFamily fontName) {
if (columnIndex < table.getColumnCount()) {
while (columnHeaderFontNames.size() < columnIndex-1) {
columnHeaderFontNames.add(TableFormattingConstants.defaultJVMFontFamily);
}
columnHeaderFontNames.set(columnIndex, fontName);
}
}
/**
* Sets the font color for all the col headers.
*
* @param fontColors an array of the new font colors for the columns
*/
public void setColumnHeaderFontColors(Color[] fontColors) {
columnHeaderFontColors.clear();
for (int i=0; i < fontColors.length && i < getTable().getColumnCount(); ++i) {
columnHeaderFontColors.set(i, fontColors[i]);
}
}
/**
* Sets the font color for a single col header.
*
* @param columnIndex the index of the col header to change
* @param fontColor the new font color for the col header
*/
public void setColumnHeaderFontColor(int columnIndex, Color fontColor) {
if (columnIndex < table.getColumnCount()) {
while (columnHeaderFontColors.size() < columnIndex-1) {
columnHeaderFontColors.add(table.getTableHeader().getForeground());
}
columnHeaderFontColors.set(columnIndex, fontColor);
}
}
/**
* Sets the border color for all the col headers.
*
* @param borderColors an array of the new border colors for the columns
*/
public void setColumnHeaderBorderColors(Color[] borderColors) {
columnHeaderBorderColors.clear();
for (int i=0; i < borderColors.length && i < getTable().getColumnCount(); ++i) {
columnHeaderBorderColors.set(i, borderColors[i]);
}
}
/**
* Sets the border color for a single col header.
*
* @param columnIndex the index of the col header to change
* @param borderColor the new border color for the col header
*/
public void setColumnHeaderBorderColor(int columnIndex, Color borderColor) {
if (columnIndex < table.getColumnCount()) {
while (columnHeaderBorderColors.size() < columnIndex-1) {
columnHeaderBorderColors.add(TableFormattingConstants.defaultFontColor);
}
columnHeaderBorderColors.set(columnIndex, borderColor);
}
}
/**
* Sets the background color for all the col headers.
*
* @param bgColors an array of the new background colors for the columns
*/
public void setColumnHeaderBackgroundColors(Color[] bgColors) {
columnHeaderBackgroundColors.clear();
for (int i=0; i < bgColors.length && i < getTable().getColumnCount(); ++i) {
columnHeaderBackgroundColors.set(i, bgColors[i]);
}
}
/**
* Sets the background color for a single col header.
*
* @param columnIndex the index of the col header to change
* @param bgColor the new background for the col header
*/
public void setColumnHeaderBackgroundColor(int columnIndex, Color bgColor) {
if (columnIndex < table.getColumnCount()) {
while (columnHeaderBackgroundColors.size() < columnIndex-1) {
columnHeaderBackgroundColors.add(TableFormattingConstants.defaultBackgroundColor);
}
columnHeaderBackgroundColors.set(columnIndex, bgColor);
}
}
/**
* Sets the Text Attributes of all column headers.
*
* @param attributes an array with the new column header TextAttributes
*/
public void setColumnHeaderTextAttributes(Integer[] attributes) {
columnHeaderTextAttributes.clear();
for (int i=0; i < attributes.length && i < getTable().getColumnCount(); ++i) {
columnHeaderTextAttributes.set(i, attributes[i]);
}
}
/**
* Sets the Text Attributes for a single column header.
*
* @param colIndex the index of the column header to change
* @param attribute the new Text Attributes for the column header
*/
public void setColumnHeaderTextAttribute(int colIndex, Integer attribute) {
if (colIndex < table.getColumnCount()) {
while (columnHeaderTextAttributes.size() < colIndex-1) {
columnHeaderTextAttributes.add(TableFormattingConstants.UNDERLINE_OFF);
}
columnHeaderTextAttributes.set(colIndex, attribute);
}
}
/**
* Gets the alignments of all row headers.
*
* @return an array of row header alignments
*/
public ContentAlignment[] getRowHeaderAlignments() {
ContentAlignment[] alignments = new ContentAlignment[table.getRowCount()];
for (int i=0; i < alignments.length; ++i) {
alignments[i] = getRowHeaderAlignment(i);
}
return alignments;
}
/**
* Gets the alignment of a single row header.
*
* @param rowIndex the index of the row header
* @return the alignment of the row header
*/
public ContentAlignment getRowHeaderAlignment(int rowIndex) {
ContentAlignment alignment = rowHeaderAlignments.get(rowIndex);
return (alignment!=null ? alignment : ContentAlignment.LEFT);
}
/**
* Gets the border state of all row headers.
*
* @return an array of row header border states
*/
public BorderState[] getRowHeaderBorderStates() {
BorderState[] borderStates = new BorderState[table.getRowCount()];
for (int i=0; i < borderStates.length; ++i) {
borderStates[i] = getRowHeaderBorderState(i);
}
return borderStates;
}
/**
* Gets the border state of a single row header.
*
* @param rowIndex the index of the row header
* @return the border states of the row header
*/
public BorderState getRowHeaderBorderState(int rowIndex) {
BorderState borderState = rowHeaderBorderStates.get(rowIndex);
return (borderState !=null ? borderState : new BorderState(BorderEdge.NONE.value()));
}
/**
* Gets the font styles of all row headers.
*
* @return an array of row header font styles
*/
public Integer[] getRowHeaderFontStyles() {
Integer[] fontStyles = new Integer[table.getRowCount()];
for (int i=0; i < fontStyles.length; ++i) {
fontStyles[i] = getRowHeaderFontStyle(i);
}
return fontStyles;
}
/**
* Gets the font style of a single row header.
*
* @param rowIndex the index of the row header
* @return the font style of the row header
*/
public Integer getRowHeaderFontStyle(int rowIndex) {
Integer fontStyle = rowHeaderFontStyles.get(rowIndex);
return (fontStyle !=null ? fontStyle : Integer.valueOf(Font.PLAIN));
}
/**
* Gets the Text Attribute of all row headers.
*
* @return an array of row header TextAttributes
*/
public Integer[] getRowHeaderTextAttributes() {
Integer[] textAttributes = new Integer[table.getRowCount()];
for (int i=0; i < textAttributes.length; ++i) {
textAttributes[i] = getRowHeaderTextAttribute(i);
}
return textAttributes;
}
/**
* Gets the Text Attribute of a single row header.
*
* @param rowIndex the index of the row header
* @return the Text Attribute of the row header
*/
public Integer getRowHeaderTextAttribute(int rowIndex) {
Integer textAttribute = rowHeaderTextAttributes.get(rowIndex);
return (textAttribute !=null ? textAttribute :
Integer.valueOf(TableFormattingConstants.UNDERLINE_OFF));
}
/**
* Gets the Text Attribute of all column headers.
*
* @return an array of column header TextAttributes
*/
public Integer[] getColumnHeaderTextAttributes() {
Integer[] textAttributes = new Integer[table.getColumnCount()];
for (int i=0; i < textAttributes.length; ++i) {
textAttributes[i] = getColumnHeaderTextAttribute(i);
}
return textAttributes;
}
/**
* Gets the Text Attribute of a single column header.
*
* @param colIndex the index of the column header
* @return textAttribute the Text Attribute of the column header
*/
public Integer getColumnHeaderTextAttribute(int colIndex) {
Integer textAttribute = columnHeaderTextAttributes.get(colIndex);
return (textAttribute !=null ? textAttribute :
Integer.valueOf(TableFormattingConstants.UNDERLINE_OFF));
}
/**
* Gets the font color of all row headers.
*
* @return fontColors an array of row header font colors
*/
public Color[] getRowHeaderFontColors() {
Color[] fontColors = new Color[table.getRowCount()];
for (int i=0; i < fontColors.length; ++i) {
fontColors[i] = getRowHeaderFontColor(i);
}
return fontColors;
}
/**
* Gets the font color of a single row header.
*
* @param rowIndex the index of the row header
* @return fontColor the font color of the row header
*/
public Color getRowHeaderFontColor(int rowIndex) {
Color fontColor = rowHeaderFontColors.get(rowIndex);
return (fontColor !=null ? fontColor : TableFormattingConstants.defaultFontColor);
}
/**
* Gets the border color of all row headers.
*
* @return borderColors an array of row header border colors
*/
public Color[] getRowHeaderBorderColors() {
Color[] borderColors = new Color[table.getRowCount()];
for (int i=0; i < borderColors.length; ++i) {
borderColors[i] = getRowHeaderBorderColor(i);
}
return borderColors;
}
/**
* Gets the border color of a single row header.
*
* @param rowIndex the index of the row header
* @return fontColor the border color of the row header
*/
public Color getRowHeaderBorderColor(int rowIndex) {
Color borderColor = rowHeaderBorderColors.get(rowIndex);
return (borderColor !=null ? borderColor : TableFormattingConstants.defaultFontColor);
}
/**
* Gets the background color of all row headers.
*
* @return bgColors an array of row header background colors
*/
public Color[] getRowHeaderBackgroundColors() {
Color[] bgColors = new Color[table.getRowCount()];
for (int i=0; i < bgColors.length; ++i) {
bgColors[i] = getRowHeaderBackgroundColor(i);
}
return bgColors;
}
/**
* Gets the background color of a single row header.
*
* @param rowIndex the index of the row header
* @return bgColor the background color of the row header
*/
public Color getRowHeaderBackgroundColor(int rowIndex) {
Color bgColor = rowHeaderBackgroundColors.get(rowIndex);
return (bgColor !=null ? bgColor : TableFormattingConstants.defaultBackgroundColor);
}
/**
* Gets the font sizes of all row headers.
*
* @return an array of row header font sizes
*/
public Integer[] getRowHeaderFontSizes() {
Integer[] fontSizes = new Integer[table.getRowCount()];
for (int i=0; i < fontSizes.length; ++i) {
fontSizes[i] = getRowHeaderFontSize(i);
}
return fontSizes;
}
/**
* Gets the font size of a single row header.
*
* @param rowIndex the index of the row header
* @return the font size of the row header
*/
public Integer getRowHeaderFontSize(int rowIndex) {
Integer fontSize = rowHeaderFontSizes.get(rowIndex);
return (fontSize !=null ? fontSize :
Integer.valueOf(TableFormattingConstants.defaultFontSize));
}
/**
* Gets the font style of all column headers.
*
* @return an array of column header font styles
*/
public Integer[] getColumnHeaderFontStyles() {
Integer[] fontStyles = new Integer[table.getColumnCount()];
for (int i=0; i < fontStyles.length; ++i) {
fontStyles[i] = getColumnHeaderFontStyle(i);
}
return fontStyles;
}
/**
* Gets the font style of a single column header.
*
* @param colIndex the index of the column header
* @return the font style of the column header
*/
public Integer getColumnHeaderFontStyle(int colIndex) {
Integer fontStyle = columnHeaderFontStyles.get(colIndex);
return (fontStyle!=null ? fontStyle : Integer.valueOf(Font.PLAIN));
}
/**
* Gets the font sizes of all column headers.
*
* @return an array of column header font sizes
*/
public Integer[] getColumnHeaderFontSizes() {
Integer[] fontSizes = new Integer[table.getColumnCount()];
for (int i=0; i < fontSizes.length; ++i) {
fontSizes[i] = getColumnHeaderFontSize(i);
}
return fontSizes;
}
/**
* Gets the font size of a single column header.
*
* @param colIndex the index of the column header
* @return the font size of the column header
*/
public Integer getColumnHeaderFontSize(int colIndex) {
Integer fontSize = columnHeaderFontSizes.get(colIndex);
return (fontSize!=null ? fontSize : TableFormattingConstants.defaultFontSize);
}
/**
* Gets the font colors of all column headers.
*
* @return an array of column header font colors
*/
public Color[] getColumnHeaderFontColors() {
Color[] fontColors = new Color[table.getColumnCount()];
for (int i=0; i < fontColors.length; ++i) {
fontColors[i] = getColumnHeaderFontColor(i);
}
return fontColors;
}
/**
* Gets the font color of a single column header.
*
* @param colIndex the index of the column header
* @return the font color of the column header
*/
public Color getColumnHeaderFontColor(int colIndex) {
Color fontColor = columnHeaderFontColors.get(colIndex);
return (fontColor!=null ? fontColor : TableFormattingConstants.defaultFontColor);
}
/**
* Gets the border colors of all column headers.
*
* @return an array of column header border colors
*/
public Color[] getColumnHeaderBorderColors() {
Color[] borderColors = new Color[table.getColumnCount()];
for (int i=0; i < borderColors.length; ++i) {
borderColors[i] = getColumnHeaderFontColor(i);
}
return borderColors;
}
/**
* Gets the border color of a single column header.
*
* @param colIndex the index of the column header
* @return the border color of the column header
*/
public Color getColumnHeaderBorderColor(int colIndex) {
Color borderColor = columnHeaderBorderColors.get(colIndex);
return (borderColor!=null ? borderColor : TableFormattingConstants.defaultFontColor);
}
/**
* Gets the background colors of all column headers.
*
* @return bgColors an array of column header background colors
*/
public Color[] getColumnHeaderBackgroundColors() {
Color[] bgColors = new Color[table.getColumnCount()];
for (int i=0; i < bgColors.length; ++i) {
bgColors[i] = getColumnHeaderBackgroundColor(i);
}
return bgColors;
}
/**
* Gets the background color of a single column header.
*
* @param colIndex the index of the column header
* @return bgColor the background color of the column header
*/
public Color getColumnHeaderBackgroundColor(int colIndex) {
Color bgColor = columnHeaderBackgroundColors.get(colIndex);
return (bgColor!=null ? bgColor : TableFormattingConstants.defaultBackgroundColor);
}
/**
* Sets the alignments of all column headers.
*
* @param alignments an array containing the new column header alignments
*/
public void setColumnHeaderAlignments(ContentAlignment[] alignments) {
columnHeaderAlignments.clear();
for (int i=0; i < alignments.length && i < getTable().getColumnCount(); ++i) {
columnHeaderAlignments.set(i, alignments[i]);
}
}
/**
* Sets the alignment of a single column header.
*
* @param columnIndex the index of the column
* @param newAlignment the new alignment for the column header
*/
public void setColumnHeaderAlignment(int columnIndex, ContentAlignment newAlignment) {
if (columnIndex < table.getColumnCount()) {
while (columnHeaderAlignments.size() < columnIndex-1) {
columnHeaderAlignments.add(ContentAlignment.LEFT);
}
columnHeaderAlignments.set(columnIndex, newAlignment);
}
}
/**
* Sets the Border States of all col headers.
*
* @param borderStates an array with the new col header BorderStates
*/
public void setColumnHeaderBorderStates(BorderState[] borderStates) {
columnHeaderBorderStates.clear();
for (int i=0; i < borderStates.length && i < getTable().getColumnCount(); ++i) {
columnHeaderBorderStates.set(i, borderStates[i]);
}
}
/**
* Sets the borderStates for a single col header.
*
* @param colIndex the index of the row header to change
* @param newBorderState the new Border State for the col header
*/
public void setColumnHeaderBorderState(int colIndex, BorderState newBorderState) {
if (colIndex < table.getColumnCount()) {
while (columnHeaderBorderStates.size() < colIndex-1) {
columnHeaderBorderStates.add(new BorderState(BorderEdge.NONE.value()));
}
columnHeaderBorderStates.set(colIndex, newBorderState);
}
}
/**
* Gets all the column header alignments.
*
* @return an array of column header alignments
*/
public ContentAlignment[] getColummnHeaderAlignments() {
ContentAlignment[] alignments = new ContentAlignment[table.getColumnCount()];
for (int i=0; i < alignments.length; ++i) {
alignments[i] = getColumnHeaderAlignment(i);
}
return alignments;
}
/**
* Gets a single column header alignment.
*
* @param columnIndex the index of the column
* @return the alignment of the column header
*/
public ContentAlignment getColumnHeaderAlignment(int columnIndex) {
ContentAlignment alignment = columnHeaderAlignments.get(columnIndex);
return (alignment!=null ? alignment : ContentAlignment.LEFT);
}
/**
* Gets the border state of all col headers.
*
* @return an array of col header border states
*/
public BorderState[] getColumnHeaderBorderStates() {
BorderState[] borderStates = new BorderState[table.getColumnCount()];
for (int i=0; i < borderStates.length; ++i) {
borderStates[i] = getColumnHeaderBorderState(i);
}
return borderStates;
}
/**
* Gets the border state of a single col header.
*
* @param colIndex the index of the col header
* @return the border states of the col header
*/
public BorderState getColumnHeaderBorderState(int colIndex) {
BorderState borderState = columnHeaderBorderStates.get(colIndex);
return (borderState !=null ? borderState : new BorderState(BorderEdge.NONE.value()));
}
/**
* Tests whether a grid is shown, dividing the table cells up with
* narrow lines.
*
* @return true, if the grid is visible
*/
public boolean getShowGrid() {
return table.getShowHorizontalLines();
}
/**
* Shows or hides the grid.
*
* @param showGrid true, if the grid should be visible
*/
public void setShowGrid(boolean showGrid) {
if (showGrid != getShowGrid()) {
table.setShowGrid(showGrid);
// possiblyFireTableLayoutChanged();
}
}
/**
* Gets the table widget underlying the labeled table.
*
* @return the table widget
*/
public JTable getTable() {
return table;
}
/**
* Gets the widget for the row headers of the labeled table.
*
* @return the row headers widget
*/
public JList getRowHeaders() {
return rowHeaders;
}
/**
* Tests whether the row headers are visible.
*
* @return true, if the row headers are visible
*/
public boolean isRowHeadersVisible() {
return rowHeaders.isVisible();
}
/**
* Tests whether the column headers are visible.
*
* @return true, if the column headers are visible
*/
public boolean isColumnHeadersVisible() {
return table.getTableHeader().isVisible();
}
/**
* Shows or hides the row headers.
*
* @param isVisible true, if the row headers should be shown
*/
public void setRowHeadersVisible(boolean isVisible) {
rowHeaders.setVisible(isVisible);
titleLabelList.setVisible(isVisible && isColumnHeadersVisible());
}
/**
* Shows or hides the column headers.
*
* @param isVisible true, if the column headers should be shown
*/
public void setColumnHeadersVisible(boolean isVisible) {
table.getTableHeader().setVisible(isVisible);
titleLabelList.setVisible(isVisible && isRowHeadersVisible());
}
/**
* Controls whether the table title is visible in the upper-left corner.
*
* @param visible true, if the title should be visible, false otherwise
*/
public void setTitleVisible(boolean visible) {
titleLabelList.setVisible(visible);
}
/**
* Updates the drop mode allowed based on what type of table is being viewed.
* In a one dimensional table we only allow insertion in one direction, depending
* on the table orientation, while in a two dimensional table we allow
* insertions in both directions.
*/
public void updateDropMode() {
LabeledTableModel model = LabeledTableModel.class.cast(table.getModel());
if (model.getTableType() == TableType.TWO_DIMENSIONAL) {
table.setDropMode(DropMode.ON_OR_INSERT);
} else if (model.getOrientation() == TableOrientation.ROW_MAJOR) {
table.setDropMode(DropMode.ON_OR_INSERT_ROWS);
} else {
table.setDropMode(DropMode.ON_OR_INSERT_COLS);
}
}
/**
* Sets the font for a component to be the correct size for rendering
* in a table, as either a row or column header or a table cell.
*
* @param comp the component that should be rendered in a table
*/
private void setTableFont(Component comp) {
Integer fontSize = 12; // Default
try {
Object fontSizeValue = UIManager.get("TableViewManifestation.fontSize");
if (fontSizeValue != null && fontSizeValue instanceof String) {
fontSize = Integer.parseInt((String) fontSizeValue);
}
} catch (NumberFormatException nfe) {
LOGGER.error("Could not parse font size as integer; using default");
}
if (comp.getFont().getSize() != fontSize) {
comp.setFont(comp.getFont().deriveFont((float) fontSize));
}
}
/**
* Set the border to be placed around header elements.
*
* @param border the border to surround header elements
*/
public void setHeaderBorder(Border border) {
this.headerBorder = border;
}
/**
* Update row headers to match height of table
*/
private void updateRowHeaders() {
if (rowHeaders != null) {
/* Trick row headers into updating */
rowHeaders.setFixedCellHeight(1);
rowHeaders.setFixedCellHeight(-1);
}
}
} | 1no label
| tableViews_src_main_java_gov_nasa_arc_mct_table_gui_LabeledTable.java |
3,554 | public static class Builder extends AbstractFieldMapper.Builder<Builder, BooleanFieldMapper> {
private Boolean nullValue = Defaults.NULL_VALUE;
public Builder(String name) {
super(name, new FieldType(Defaults.FIELD_TYPE));
this.builder = this;
}
public Builder nullValue(boolean nullValue) {
this.nullValue = nullValue;
return this;
}
@Override
public Builder tokenized(boolean tokenized) {
if (tokenized) {
throw new ElasticsearchIllegalArgumentException("bool field can't be tokenized");
}
return super.tokenized(tokenized);
}
@Override
public BooleanFieldMapper build(BuilderContext context) {
return new BooleanFieldMapper(buildNames(context), boost, fieldType, nullValue, postingsProvider,
docValuesProvider, similarity, normsLoading, fieldDataSettings, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_core_BooleanFieldMapper.java |
1,182 | public class OQueryOperatorIn extends OQueryOperatorEqualityNotNulls {
public OQueryOperatorIn() {
super("IN", 5, false);
}
@Override
@SuppressWarnings("unchecked")
protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft,
final Object iRight, OCommandContext iContext) {
if (iLeft instanceof Collection<?>) {
final Collection<Object> sourceCollection = (Collection<Object>) iLeft;
if (iRight instanceof Collection<?>) {
// AGAINST COLLECTION OF ITEMS
final Collection<Object> collectionToMatch = (Collection<Object>) iRight;
boolean found = false;
for (final Object o1 : sourceCollection) {
for (final Object o2 : collectionToMatch) {
if (OQueryOperatorEquals.equals(o1, o2)) {
found = true;
break;
}
}
}
return found;
} else {
// AGAINST SINGLE ITEM
if (sourceCollection instanceof Set<?>)
return sourceCollection.contains(iRight);
for (final Object o : sourceCollection) {
if (OQueryOperatorEquals.equals(iRight, o))
return true;
}
}
} else if (iRight instanceof Collection<?>) {
final Collection<Object> sourceCollection = (Collection<Object>) iRight;
if (sourceCollection instanceof Set<?>)
return sourceCollection.contains(iLeft);
for (final Object o : sourceCollection) {
if (OQueryOperatorEquals.equals(iLeft, o))
return true;
}
} else if (iLeft.getClass().isArray()) {
for (final Object o : (Object[]) iLeft) {
if (OQueryOperatorEquals.equals(iRight, o))
return true;
}
} else if (iRight.getClass().isArray()) {
for (final Object o : (Object[]) iRight) {
if (OQueryOperatorEquals.equals(iLeft, o))
return true;
}
}
return iLeft.equals(iRight);
}
@Override
public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) {
return OIndexReuseType.INDEX_METHOD;
}
@SuppressWarnings("unchecked")
@Override
public Object executeIndexQuery(OCommandContext iContext, OIndex<?> index, INDEX_OPERATION_TYPE iOperationType,
List<Object> keyParams, IndexResultListener resultListener, int fetchLimit) {
final OIndexDefinition indexDefinition = index.getDefinition();
final Object result;
final OIndexInternal<?> internalIndex = index.getInternal();
if (!internalIndex.canBeUsedInEqualityOperators())
return null;
if (indexDefinition.getParamCount() == 1) {
final Object inKeyValue = keyParams.get(0);
final List<Object> inParams;
if (inKeyValue instanceof List<?>)
inParams = (List<Object>) inKeyValue;
else if (inKeyValue instanceof OSQLFilterItem)
inParams = (List<Object>) ((OSQLFilterItem) inKeyValue).getValue(null, iContext);
else
throw new IllegalArgumentException("Key '" + inKeyValue + "' is not valid");
final List<Object> inKeys = new ArrayList<Object>();
boolean containsNotCompatibleKey = false;
for (final Object keyValue : inParams) {
final Object key = indexDefinition.createValue(OSQLHelper.getValue(keyValue));
if (key == null) {
containsNotCompatibleKey = true;
break;
}
inKeys.add(key);
}
if (containsNotCompatibleKey)
return null;
if (INDEX_OPERATION_TYPE.COUNT.equals(iOperationType))
result = index.getValues(inKeys).size();
else if (resultListener != null) {
index.getValues(inKeys, resultListener);
result = resultListener.getResult();
} else
result = index.getValues(inKeys);
} else
return null;
updateProfiler(iContext, internalIndex, keyParams, indexDefinition);
return result;
}
@Override
public ORID getBeginRidRange(Object iLeft, Object iRight) {
final Iterable<?> ridCollection;
final int ridSize;
if (iRight instanceof OSQLFilterItemField && ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iRight).getRoot())) {
if (iLeft instanceof OSQLFilterItem)
iLeft = ((OSQLFilterItem) iLeft).getValue(null, null);
ridCollection = OMultiValue.getMultiValueIterable(iLeft);
ridSize = OMultiValue.getSize(iLeft);
} else if (iLeft instanceof OSQLFilterItemField
&& ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iLeft).getRoot())) {
if (iRight instanceof OSQLFilterItem)
iRight = ((OSQLFilterItem) iRight).getValue(null, null);
ridCollection = OMultiValue.getMultiValueIterable(iRight);
ridSize = OMultiValue.getSize(iRight);
} else
return null;
final List<ORID> rids = addRangeResults(ridCollection, ridSize);
return rids == null ? null : Collections.min(rids);
}
@Override
public ORID getEndRidRange(Object iLeft, Object iRight) {
final Iterable<?> ridCollection;
final int ridSize;
if (iRight instanceof OSQLFilterItemField && ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iRight).getRoot())) {
if (iLeft instanceof OSQLFilterItem)
iLeft = ((OSQLFilterItem) iLeft).getValue(null, null);
ridCollection = OMultiValue.getMultiValueIterable(iLeft);
ridSize = OMultiValue.getSize(iLeft);
} else if (iLeft instanceof OSQLFilterItemField
&& ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iLeft).getRoot())) {
if (iRight instanceof OSQLFilterItem)
iRight = ((OSQLFilterItem) iRight).getValue(null, null);
ridCollection = OMultiValue.getMultiValueIterable(iRight);
ridSize = OMultiValue.getSize(iRight);
} else
return null;
final List<ORID> rids = addRangeResults(ridCollection, ridSize);
return rids == null ? null : Collections.max(rids);
}
protected List<ORID> addRangeResults(final Iterable<?> ridCollection, final int ridSize) {
if (ridCollection == null)
return null;
List<ORID> rids = null;
for (Object rid : ridCollection) {
if (rid instanceof OSQLFilterItemParameter)
rid = ((OSQLFilterItemParameter) rid).getValue(null, null);
if (rid instanceof OIdentifiable) {
final ORID r = ((OIdentifiable) rid).getIdentity();
if (r.isPersistent()) {
if (rids == null)
// LAZY CREATE IT
rids = new ArrayList<ORID>(ridSize);
rids.add(r);
}
}
}
return rids;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorIn.java |
24 | class FindOccurrenceLocationVisitor extends Visitor
implements NaturalVisitor {
private Node node;
private int offset;
private OccurrenceLocation occurrence;
private boolean inTypeConstraint = false;
FindOccurrenceLocationVisitor(int offset, Node node) {
this.offset = offset;
this.node = node;
}
OccurrenceLocation getOccurrenceLocation() {
return occurrence;
}
@Override
public void visitAny(Node that) {
if (inBounds(that)) {
super.visitAny(that);
}
//otherwise, as a performance optimization
//don't go any further down this branch
}
@Override
public void visit(Tree.Condition that) {
if (inBounds(that)) {
occurrence = EXPRESSION;
}
super.visit(that);
}
@Override
public void visit(Tree.ExistsCondition that) {
super.visit(that);
if (that.getVariable()==null ?
inBounds(that) :
inBounds(that.getVariable().getIdentifier())) {
occurrence = EXISTS;
}
}
@Override
public void visit(Tree.NonemptyCondition that) {
super.visit(that);
if (that.getVariable()==null ?
inBounds(that) :
inBounds(that.getVariable().getIdentifier())) {
occurrence = NONEMPTY;
}
}
@Override
public void visit(Tree.IsCondition that) {
super.visit(that);
boolean inBounds;
if (that.getVariable()!=null) {
inBounds = inBounds(that.getVariable().getIdentifier());
}
else if (that.getType()!=null) {
inBounds = inBounds(that) && offset>that.getType().getStopIndex()+1;
}
else {
inBounds = false;
}
if (inBounds) {
occurrence = IS;
}
}
public void visit(Tree.TypeConstraint that) {
inTypeConstraint=true;
super.visit(that);
inTypeConstraint=false;
}
public void visit(Tree.ImportMemberOrTypeList that) {
if (inBounds(that)) {
occurrence = IMPORT;
}
super.visit(that);
}
public void visit(Tree.ExtendedType that) {
if (inBounds(that)) {
occurrence = EXTENDS;
}
super.visit(that);
}
public void visit(Tree.SatisfiedTypes that) {
if (inBounds(that)) {
occurrence = inTypeConstraint?
UPPER_BOUND : SATISFIES;
}
super.visit(that);
}
public void visit(Tree.CaseTypes that) {
if (inBounds(that)) {
occurrence = OF;
}
super.visit(that);
}
public void visit(Tree.CatchClause that) {
if (inBounds(that) &&
!inBounds(that.getBlock())) {
occurrence = CATCH;
}
else {
super.visit(that);
}
}
public void visit(Tree.CaseClause that) {
if (inBounds(that) &&
!inBounds(that.getBlock())) {
occurrence = CASE;
}
super.visit(that);
}
@Override
public void visit(Tree.BinaryOperatorExpression that) {
Term right = that.getRightTerm();
if (right==null) {
right = that;
}
Term left = that.getLeftTerm();
if (left==null) {
left = that;
}
if (inBounds(left, right)) {
occurrence = EXPRESSION;
}
super.visit(that);
}
@Override
public void visit(Tree.UnaryOperatorExpression that) {
Term term = that.getTerm();
if (term==null) {
term = that;
}
if (inBounds(that, term) || inBounds(term, that)) {
occurrence = EXPRESSION;
}
super.visit(that);
}
@Override
public void visit(Tree.ParameterList that) {
if (inBounds(that)) {
occurrence = PARAMETER_LIST;
}
super.visit(that);
}
@Override
public void visit(Tree.TypeParameterList that) {
if (inBounds(that)) {
occurrence = TYPE_PARAMETER_LIST;
}
super.visit(that);
}
@Override
public void visit(Tree.TypeSpecifier that) {
if (inBounds(that)) {
occurrence = TYPE_ALIAS;
}
super.visit(that);
}
@Override
public void visit(Tree.ClassSpecifier that) {
if (inBounds(that)) {
occurrence = CLASS_ALIAS;
}
super.visit(that);
}
@Override
public void visit(Tree.SpecifierOrInitializerExpression that) {
if (inBounds(that)) {
occurrence = EXPRESSION;
}
super.visit(that);
}
@Override
public void visit(Tree.ArgumentList that) {
if (inBounds(that)) {
occurrence = EXPRESSION;
}
super.visit(that);
}
@Override
public void visit(Tree.TypeArgumentList that) {
if (inBounds(that)) {
occurrence = TYPE_ARGUMENT_LIST;
}
super.visit(that);
}
@Override
public void visit(QualifiedMemberOrTypeExpression that) {
if (inBounds(that.getMemberOperator(), that.getIdentifier())) {
occurrence = EXPRESSION;
}
else {
super.visit(that);
}
}
@Override
public void visit(Tree.Declaration that) {
if (inBounds(that)) {
if (occurrence!=PARAMETER_LIST) {
occurrence=null;
}
}
super.visit(that);
}
public void visit(Tree.MetaLiteral that) {
super.visit(that);
if (inBounds(that)) {
if (occurrence!=TYPE_ARGUMENT_LIST) {
switch (that.getNodeType()) {
case "ModuleLiteral":
occurrence=MODULE_REF;
break;
case "PackageLiteral":
occurrence=PACKAGE_REF;
break;
case "ValueLiteral":
occurrence=VALUE_REF;
break;
case "FunctionLiteral":
occurrence=FUNCTION_REF;
break;
case "InterfaceLiteral":
occurrence=INTERFACE_REF;
break;
case "ClassLiteral":
occurrence=CLASS_REF;
break;
case "TypeParameterLiteral":
occurrence=TYPE_PARAMETER_REF;
break;
case "AliasLiteral":
occurrence=ALIAS_REF;
break;
default:
occurrence = META;
}
}
}
}
public void visit(Tree.StringLiteral that) {
if (inBounds(that)) {
occurrence = DOCLINK;
}
}
public void visit(Tree.DocLink that) {
if (this.node instanceof Tree.DocLink) {
occurrence = DOCLINK;
}
}
private boolean inBounds(Node that) {
return inBounds(that, that);
}
private boolean inBounds(Node left, Node right) {
if (left==null) return false;
if (right==null) right=left;
Integer startIndex = left.getStartIndex();
Integer stopIndex = right.getStopIndex();
return startIndex!=null && stopIndex!=null &&
startIndex <= node.getStartIndex() &&
stopIndex >= node.getStopIndex();
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_FindOccurrenceLocationVisitor.java |
1,885 | Runnable runnable = new Runnable() {
public void run() {
try {
final int oneThird = size / 3;
final int threshold = new Random().nextInt(oneThird) + oneThird;
h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
for (int i = 0; i < size; i++) {
if (i == threshold) {
latch2.countDown();
}
txMap.put(i, i);
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
latch.countDown();
}
return true;
}
});
fail();
} catch (Exception ignored) {
}
latch.countDown();
}
}; | 0true
| hazelcast_src_test_java_com_hazelcast_map_MapTransactionTest.java |
521 | public class TypesExistsRequest extends MasterNodeReadOperationRequest<TypesExistsRequest> {
private String[] indices;
private String[] types;
private IndicesOptions indicesOptions = IndicesOptions.strict();
TypesExistsRequest() {
}
public TypesExistsRequest(String[] indices, String... types) {
this.indices = indices;
this.types = types;
}
public String[] indices() {
return indices;
}
public void indices(String[] indices) {
this.indices = indices;
}
public String[] types() {
return types;
}
public void types(String[] types) {
this.types = types;
}
public IndicesOptions indicesOptions() {
return indicesOptions;
}
public TypesExistsRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (indices == null) { // Specifying '*' via rest api results in an empty array
validationException = addValidationError("index/indices is missing", validationException);
}
if (types == null || types.length == 0) {
validationException = addValidationError("type/types is missing", validationException);
}
return validationException;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeStringArray(indices);
out.writeStringArray(types);
indicesOptions.writeIndicesOptions(out);
writeLocal(out, Version.V_1_0_0_RC2);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
indices = in.readStringArray();
types = in.readStringArray();
indicesOptions = IndicesOptions.readIndicesOptions(in);
readLocal(in, Version.V_1_0_0_RC2);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_exists_types_TypesExistsRequest.java |
141 | public interface VertexLabelMaker {
/**
* Returns the name of the to-be-build vertex label
* @return the label name
*/
public String getName();
/**
* Enables partitioning for this vertex label. If a vertex label is partitioned, all of its
* vertices are partitioned across the partitions of the graph.
*
* @return this VertexLabelMaker
*/
public VertexLabelMaker partition();
/**
* Makes this vertex label static, which means that vertices of this label cannot be modified outside of the transaction
* in which they were created.
*
* @return this VertexLabelMaker
*/
public VertexLabelMaker setStatic();
/**
* Creates a {@link VertexLabel} according to the specifications of this builder.
*
* @return the created vertex label
*/
public VertexLabel make();
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_schema_VertexLabelMaker.java |
1,325 | public abstract class OAbstractCheckPointStartRecord implements OWALRecord {
private OLogSequenceNumber previousCheckpoint;
protected OAbstractCheckPointStartRecord() {
}
protected OAbstractCheckPointStartRecord(OLogSequenceNumber previousCheckpoint) {
this.previousCheckpoint = previousCheckpoint;
}
public OLogSequenceNumber getPreviousCheckpoint() {
return previousCheckpoint;
}
@Override
public int toStream(byte[] content, int offset) {
if (previousCheckpoint == null) {
content[offset] = 0;
offset++;
return offset;
}
content[offset] = 1;
offset++;
OLongSerializer.INSTANCE.serializeNative(previousCheckpoint.getSegment(), content, offset);
offset += OLongSerializer.LONG_SIZE;
OLongSerializer.INSTANCE.serializeNative(previousCheckpoint.getPosition(), content, offset);
offset += OLongSerializer.LONG_SIZE;
return offset;
}
@Override
public int fromStream(byte[] content, int offset) {
if (content[offset] == 0) {
offset++;
return offset;
}
offset++;
long segment = OLongSerializer.INSTANCE.deserializeNative(content, offset);
offset += OLongSerializer.LONG_SIZE;
long position = OLongSerializer.INSTANCE.deserializeNative(content, offset);
offset += OLongSerializer.LONG_SIZE;
previousCheckpoint = new OLogSequenceNumber(segment, position);
return offset;
}
@Override
public int serializedSize() {
if (previousCheckpoint == null)
return 1;
return 2 * OLongSerializer.LONG_SIZE + 1;
}
@Override
public boolean isUpdateMasterRecord() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
OAbstractCheckPointStartRecord that = (OAbstractCheckPointStartRecord) o;
if (previousCheckpoint != null ? !previousCheckpoint.equals(that.previousCheckpoint) : that.previousCheckpoint != null)
return false;
return true;
}
@Override
public int hashCode() {
return previousCheckpoint != null ? previousCheckpoint.hashCode() : 0;
}
@Override
public String toString() {
return "OAbstractCheckPointStartRecord{" + "previousCheckpoint=" + previousCheckpoint + '}';
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_OAbstractCheckPointStartRecord.java |
2,903 | public class NumericIntegerTokenizer extends NumericTokenizer {
public NumericIntegerTokenizer(Reader reader, int precisionStep, char[] buffer) throws IOException {
super(reader, new NumericTokenStream(precisionStep), buffer, null);
}
@Override
protected void setValue(NumericTokenStream tokenStream, String value) {
tokenStream.setIntValue(Integer.parseInt(value));
}
} | 0true
| src_main_java_org_elasticsearch_index_analysis_NumericIntegerTokenizer.java |
1,778 | public static class InternalLineStringBuilder extends BaseLineStringBuilder<InternalLineStringBuilder> {
private final MultiLineStringBuilder collection;
public InternalLineStringBuilder(MultiLineStringBuilder collection) {
super();
this.collection = collection;
}
public MultiLineStringBuilder end() {
return collection;
}
public Coordinate[] coordinates() {
return super.coordinates(false);
}
@Override
public GeoShapeType type() {
return null;
}
} | 0true
| src_main_java_org_elasticsearch_common_geo_builders_MultiLineStringBuilder.java |
1,869 | class MembersInjectorStore {
private final InjectorImpl injector;
private final ImmutableList<TypeListenerBinding> typeListenerBindings;
private final FailableCache<TypeLiteral<?>, MembersInjectorImpl<?>> cache
= new FailableCache<TypeLiteral<?>, MembersInjectorImpl<?>>() {
@Override
protected MembersInjectorImpl<?> create(TypeLiteral<?> type, Errors errors)
throws ErrorsException {
return createWithListeners(type, errors);
}
};
MembersInjectorStore(InjectorImpl injector,
List<TypeListenerBinding> typeListenerBindings) {
this.injector = injector;
this.typeListenerBindings = ImmutableList.copyOf(typeListenerBindings);
}
/**
* Returns true if any type listeners are installed. Other code may take shortcuts when there
* aren't any type listeners.
*/
public boolean hasTypeListeners() {
return !typeListenerBindings.isEmpty();
}
/**
* Returns a new complete members injector with injection listeners registered.
*/
@SuppressWarnings("unchecked") // the MembersInjector type always agrees with the passed type
public <T> MembersInjectorImpl<T> get(TypeLiteral<T> key, Errors errors) throws ErrorsException {
return (MembersInjectorImpl<T>) cache.get(key, errors);
}
/**
* Creates a new members injector and attaches both injection listeners and method aspects.
*/
private <T> MembersInjectorImpl<T> createWithListeners(TypeLiteral<T> type, Errors errors)
throws ErrorsException {
int numErrorsBefore = errors.size();
Set<InjectionPoint> injectionPoints;
try {
injectionPoints = InjectionPoint.forInstanceMethodsAndFields(type);
} catch (ConfigurationException e) {
errors.merge(e.getErrorMessages());
injectionPoints = e.getPartialValue();
}
ImmutableList<SingleMemberInjector> injectors = getInjectors(injectionPoints, errors);
errors.throwIfNewErrors(numErrorsBefore);
EncounterImpl<T> encounter = new EncounterImpl<T>(errors, injector.lookups);
for (TypeListenerBinding typeListener : typeListenerBindings) {
if (typeListener.getTypeMatcher().matches(type)) {
try {
typeListener.getListener().hear(type, encounter);
} catch (RuntimeException e) {
errors.errorNotifyingTypeListener(typeListener, type, e);
}
}
}
encounter.invalidate();
errors.throwIfNewErrors(numErrorsBefore);
return new MembersInjectorImpl<T>(injector, type, encounter, injectors);
}
/**
* Returns the injectors for the specified injection points.
*/
ImmutableList<SingleMemberInjector> getInjectors(
Set<InjectionPoint> injectionPoints, Errors errors) {
List<SingleMemberInjector> injectors = Lists.newArrayList();
for (InjectionPoint injectionPoint : injectionPoints) {
try {
Errors errorsForMember = injectionPoint.isOptional()
? new Errors(injectionPoint)
: errors.withSource(injectionPoint);
SingleMemberInjector injector = injectionPoint.getMember() instanceof Field
? new SingleFieldInjector(this.injector, injectionPoint, errorsForMember)
: new SingleMethodInjector(this.injector, injectionPoint, errorsForMember);
injectors.add(injector);
} catch (ErrorsException ignoredForNow) {
// ignored for now
}
}
return ImmutableList.copyOf(injectors);
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_MembersInjectorStore.java |
3,338 | public class FloatArrayIndexFieldData extends AbstractIndexFieldData<FloatArrayAtomicFieldData> implements IndexNumericFieldData<FloatArrayAtomicFieldData> {
private final CircuitBreakerService breakerService;
public static class Builder implements IndexFieldData.Builder {
@Override
public IndexFieldData<?> build(Index index, @IndexSettings Settings indexSettings, FieldMapper<?> mapper, IndexFieldDataCache cache,
CircuitBreakerService breakerService) {
return new FloatArrayIndexFieldData(index, indexSettings, mapper.names(), mapper.fieldDataType(), cache, breakerService);
}
}
public FloatArrayIndexFieldData(Index index, @IndexSettings Settings indexSettings, FieldMapper.Names fieldNames,
FieldDataType fieldDataType, IndexFieldDataCache cache, CircuitBreakerService breakerService) {
super(index, indexSettings, fieldNames, fieldDataType, cache);
this.breakerService = breakerService;
}
@Override
public NumericType getNumericType() {
return NumericType.FLOAT;
}
@Override
public boolean valuesOrdered() {
// because we might have single values? we can dynamically update a flag to reflect that
// based on the atomic field data loaded
return false;
}
@Override
public FloatArrayAtomicFieldData loadDirect(AtomicReaderContext context) throws Exception {
AtomicReader reader = context.reader();
Terms terms = reader.terms(getFieldNames().indexName());
FloatArrayAtomicFieldData data = null;
// TODO: Use an actual estimator to estimate before loading.
NonEstimatingEstimator estimator = new NonEstimatingEstimator(breakerService.getBreaker());
if (terms == null) {
data = FloatArrayAtomicFieldData.empty(reader.maxDoc());
estimator.afterLoad(null, data.getMemorySizeInBytes());
return data;
}
// TODO: how can we guess the number of terms? numerics end up creating more terms per value...
final BigFloatArrayList values = new BigFloatArrayList();
values.add(0); // first "t" indicates null value
final float acceptableTransientOverheadRatio = fieldDataType.getSettings().getAsFloat("acceptable_transient_overhead_ratio", OrdinalsBuilder.DEFAULT_ACCEPTABLE_OVERHEAD_RATIO);
OrdinalsBuilder builder = new OrdinalsBuilder(reader.maxDoc(), acceptableTransientOverheadRatio);
boolean success = false;
try {
BytesRefIterator iter = builder.buildFromTerms(getNumericType().wrapTermsEnum(terms.iterator(null)));
BytesRef term;
while ((term = iter.next()) != null) {
values.add(NumericUtils.sortableIntToFloat(NumericUtils.prefixCodedToInt(term)));
}
Ordinals build = builder.build(fieldDataType.getSettings());
if (!build.isMultiValued() && CommonSettings.removeOrdsOnSingleValue(fieldDataType)) {
Docs ordinals = build.ordinals();
final FixedBitSet set = builder.buildDocsWithValuesSet();
// there's sweet spot where due to low unique value count, using ordinals will consume less memory
long singleValuesArraySize = reader.maxDoc() * RamUsageEstimator.NUM_BYTES_FLOAT + (set == null ? 0 : RamUsageEstimator.sizeOf(set.getBits()) + RamUsageEstimator.NUM_BYTES_INT);
long uniqueValuesArraySize = values.sizeInBytes();
long ordinalsSize = build.getMemorySizeInBytes();
if (uniqueValuesArraySize + ordinalsSize < singleValuesArraySize) {
data = new FloatArrayAtomicFieldData.WithOrdinals(values, reader.maxDoc(), build);
success = true;
return data;
}
int maxDoc = reader.maxDoc();
BigFloatArrayList sValues = new BigFloatArrayList(maxDoc);
for (int i = 0; i < maxDoc; i++) {
sValues.add(values.get(ordinals.getOrd(i)));
}
assert sValues.size() == maxDoc;
if (set == null) {
data = new FloatArrayAtomicFieldData.Single(sValues, maxDoc, ordinals.getNumOrds());
} else {
data = new FloatArrayAtomicFieldData.SingleFixedSet(sValues, maxDoc, set, ordinals.getNumOrds());
}
} else {
data = new FloatArrayAtomicFieldData.WithOrdinals(values, reader.maxDoc(), build);
}
success = true;
return data;
} finally {
if (success) {
estimator.afterLoad(null, data.getMemorySizeInBytes());
}
builder.close();
}
}
@Override
public XFieldComparatorSource comparatorSource(@Nullable Object missingValue, SortMode sortMode) {
return new FloatValuesComparatorSource(this, missingValue, sortMode);
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_FloatArrayIndexFieldData.java |
1,138 | public enum EventType {
CREATED, DESTROYED
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_DistributedObjectEvent.java |
36 | public class OMVRBTreeEntryPosition<K, V> {
public OMVRBTreeEntry<K, V> entry;
public int position;
public OMVRBTreeEntryPosition(final OMVRBTreeEntryPosition<K, V> entryPosition) {
this.entry = entryPosition.entry;
this.position = entryPosition.position;
}
public OMVRBTreeEntryPosition(final OMVRBTreeEntry<K, V> entry) {
assign(entry);
}
public OMVRBTreeEntryPosition(final OMVRBTreeEntry<K, V> entry, final int iPosition) {
assign(entry, iPosition);
}
public void assign(final OMVRBTreeEntry<K, V> entry, final int iPosition) {
this.entry = entry;
this.position = iPosition;
}
public void assign(final OMVRBTreeEntry<K, V> entry) {
this.entry = entry;
this.position = entry != null ? entry.getTree().getPageIndex() : -1;
}
public K getKey() {
return entry != null ? entry.getKey(position) : null;
}
public V getValue() {
return entry != null ? entry.getValue(position) : null;
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeEntryPosition.java |
1,407 | public class OHostInfo {
/**
* Gets mac address of current host.
*
* @return mac address
*/
public static byte[] getMac() {
try {
final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
final byte[] mac = networkInterface.getHardwareAddress();
if (mac != null && mac.length == 6)
return mac;
}
} catch (SocketException e) {
throw new IllegalStateException("Error during MAC address retrieval.", e);
}
throw new IllegalStateException("Node id is possible to generate only on machine which have at least"
+ " one network interface with mac address.");
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_util_OHostInfo.java |
935 | public static interface ODbRelatedCall<T> {
public T call();
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java |
4,050 | public class ChildrenQuery extends Query {
private final String parentType;
private final String childType;
private final Filter parentFilter;
private final ScoreType scoreType;
private final Query originalChildQuery;
private final int shortCircuitParentDocSet;
private final Filter nonNestedDocsFilter;
private Query rewrittenChildQuery;
private IndexReader rewriteIndexReader;
public ChildrenQuery(String parentType, String childType, Filter parentFilter, Query childQuery, ScoreType scoreType, int shortCircuitParentDocSet, Filter nonNestedDocsFilter) {
this.parentType = parentType;
this.childType = childType;
this.parentFilter = parentFilter;
this.originalChildQuery = childQuery;
this.scoreType = scoreType;
this.shortCircuitParentDocSet = shortCircuitParentDocSet;
this.nonNestedDocsFilter = nonNestedDocsFilter;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
ChildrenQuery that = (ChildrenQuery) obj;
if (!originalChildQuery.equals(that.originalChildQuery)) {
return false;
}
if (!childType.equals(that.childType)) {
return false;
}
if (getBoost() != that.getBoost()) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = originalChildQuery.hashCode();
result = 31 * result + childType.hashCode();
result = 31 * result + Float.floatToIntBits(getBoost());
return result;
}
@Override
public String toString(String field) {
StringBuilder sb = new StringBuilder();
sb.append("ChildrenQuery[").append(childType).append("/").append(parentType).append("](").append(originalChildQuery
.toString(field)).append(')').append(ToStringUtils.boost(getBoost()));
return sb.toString();
}
@Override
// See TopChildrenQuery#rewrite
public Query rewrite(IndexReader reader) throws IOException {
if (rewrittenChildQuery == null) {
rewriteIndexReader = reader;
rewrittenChildQuery = originalChildQuery.rewrite(reader);
}
return this;
}
@Override
public void extractTerms(Set<Term> terms) {
rewrittenChildQuery.extractTerms(terms);
}
@Override
public Weight createWeight(IndexSearcher searcher) throws IOException {
SearchContext searchContext = SearchContext.current();
searchContext.idCache().refresh(searchContext.searcher().getTopReaderContext().leaves());
Recycler.V<ObjectFloatOpenHashMap<HashedBytesArray>> uidToScore = searchContext.cacheRecycler().objectFloatMap(-1);
Recycler.V<ObjectIntOpenHashMap<HashedBytesArray>> uidToCount = null;
final Collector collector;
switch (scoreType) {
case AVG:
uidToCount = searchContext.cacheRecycler().objectIntMap(-1);
collector = new AvgChildUidCollector(scoreType, searchContext, parentType, uidToScore.v(), uidToCount.v());
break;
default:
collector = new ChildUidCollector(scoreType, searchContext, parentType, uidToScore.v());
}
final Query childQuery;
if (rewrittenChildQuery == null) {
childQuery = rewrittenChildQuery = searcher.rewrite(originalChildQuery);
} else {
assert rewriteIndexReader == searcher.getIndexReader();
childQuery = rewrittenChildQuery;
}
IndexSearcher indexSearcher = new IndexSearcher(searcher.getIndexReader());
indexSearcher.setSimilarity(searcher.getSimilarity());
indexSearcher.search(childQuery, collector);
int size = uidToScore.v().size();
if (size == 0) {
uidToScore.release();
if (uidToCount != null) {
uidToCount.release();
}
return Queries.newMatchNoDocsQuery().createWeight(searcher);
}
final Filter parentFilter;
if (size == 1) {
BytesRef id = uidToScore.v().keys().iterator().next().value.toBytesRef();
if (nonNestedDocsFilter != null) {
List<Filter> filters = Arrays.asList(
new TermFilter(new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(parentType, id))),
nonNestedDocsFilter
);
parentFilter = new AndFilter(filters);
} else {
parentFilter = new TermFilter(new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(parentType, id)));
}
} else if (size <= shortCircuitParentDocSet) {
parentFilter = new ParentIdsFilter(parentType, uidToScore.v().keys, uidToScore.v().allocated, nonNestedDocsFilter);
} else {
parentFilter = new ApplyAcceptedDocsFilter(this.parentFilter);
}
ParentWeight parentWeight = new ParentWeight(rewrittenChildQuery.createWeight(searcher), parentFilter, searchContext, size, uidToScore, uidToCount);
searchContext.addReleasable(parentWeight);
return parentWeight;
}
private final class ParentWeight extends Weight implements Releasable {
private final Weight childWeight;
private final Filter parentFilter;
private final SearchContext searchContext;
private final Recycler.V<ObjectFloatOpenHashMap<HashedBytesArray>> uidToScore;
private final Recycler.V<ObjectIntOpenHashMap<HashedBytesArray>> uidToCount;
private int remaining;
private ParentWeight(Weight childWeight, Filter parentFilter, SearchContext searchContext, int remaining, Recycler.V<ObjectFloatOpenHashMap<HashedBytesArray>> uidToScore, Recycler.V<ObjectIntOpenHashMap<HashedBytesArray>> uidToCount) {
this.childWeight = childWeight;
this.parentFilter = parentFilter;
this.searchContext = searchContext;
this.remaining = remaining;
this.uidToScore = uidToScore;
this.uidToCount= uidToCount;
}
@Override
public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
return new Explanation(getBoost(), "not implemented yet...");
}
@Override
public Query getQuery() {
return ChildrenQuery.this;
}
@Override
public float getValueForNormalization() throws IOException {
float sum = childWeight.getValueForNormalization();
sum *= getBoost() * getBoost();
return sum;
}
@Override
public void normalize(float norm, float topLevelBoost) {
}
@Override
public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException {
DocIdSet parentsSet = parentFilter.getDocIdSet(context, acceptDocs);
if (DocIdSets.isEmpty(parentsSet) || remaining == 0) {
return null;
}
IdReaderTypeCache idTypeCache = searchContext.idCache().reader(context.reader()).type(parentType);
// We can't be sure of the fact that liveDocs have been applied, so we apply it here. The "remaining"
// count down (short circuit) logic will then work as expected.
DocIdSetIterator parentsIterator = BitsFilteredDocIdSet.wrap(parentsSet, context.reader().getLiveDocs()).iterator();
switch (scoreType) {
case AVG:
return new AvgParentScorer(this, idTypeCache, uidToScore.v(), uidToCount.v(), parentsIterator);
default:
return new ParentScorer(this, idTypeCache, uidToScore.v(), parentsIterator);
}
}
@Override
public boolean release() throws ElasticsearchException {
Releasables.release(uidToScore, uidToCount);
return true;
}
private class ParentScorer extends Scorer {
final ObjectFloatOpenHashMap<HashedBytesArray> uidToScore;
final IdReaderTypeCache idTypeCache;
final DocIdSetIterator parentsIterator;
int currentDocId = -1;
float currentScore;
ParentScorer(Weight weight, IdReaderTypeCache idTypeCache, ObjectFloatOpenHashMap<HashedBytesArray> uidToScore, DocIdSetIterator parentsIterator) {
super(weight);
this.idTypeCache = idTypeCache;
this.parentsIterator = parentsIterator;
this.uidToScore = uidToScore;
}
@Override
public float score() throws IOException {
return currentScore;
}
@Override
public int freq() throws IOException {
// We don't have the original child query hit info here...
// But the freq of the children could be collector and returned here, but makes this Scorer more expensive.
return 1;
}
@Override
public int docID() {
return currentDocId;
}
@Override
public int nextDoc() throws IOException {
if (remaining == 0) {
return currentDocId = NO_MORE_DOCS;
}
while (true) {
currentDocId = parentsIterator.nextDoc();
if (currentDocId == DocIdSetIterator.NO_MORE_DOCS) {
return currentDocId;
}
HashedBytesArray uid = idTypeCache.idByDoc(currentDocId);
if (uidToScore.containsKey(uid)) {
// Can use lget b/c uidToScore is only used by one thread at the time (via CacheRecycler)
currentScore = uidToScore.lget();
remaining--;
return currentDocId;
}
}
}
@Override
public int advance(int target) throws IOException {
if (remaining == 0) {
return currentDocId = NO_MORE_DOCS;
}
currentDocId = parentsIterator.advance(target);
if (currentDocId == DocIdSetIterator.NO_MORE_DOCS) {
return currentDocId;
}
HashedBytesArray uid = idTypeCache.idByDoc(currentDocId);
if (uidToScore.containsKey(uid)) {
// Can use lget b/c uidToScore is only used by one thread at the time (via CacheRecycler)
currentScore = uidToScore.lget();
remaining--;
return currentDocId;
} else {
return nextDoc();
}
}
@Override
public long cost() {
return parentsIterator.cost();
}
}
private final class AvgParentScorer extends ParentScorer {
final ObjectIntOpenHashMap<HashedBytesArray> uidToCount;
AvgParentScorer(Weight weight, IdReaderTypeCache idTypeCache, ObjectFloatOpenHashMap<HashedBytesArray> uidToScore, ObjectIntOpenHashMap<HashedBytesArray> uidToCount, DocIdSetIterator parentsIterator) {
super(weight, idTypeCache, uidToScore, parentsIterator);
this.uidToCount = uidToCount;
}
@Override
public int nextDoc() throws IOException {
if (remaining == 0) {
return currentDocId = NO_MORE_DOCS;
}
while (true) {
currentDocId = parentsIterator.nextDoc();
if (currentDocId == DocIdSetIterator.NO_MORE_DOCS) {
return currentDocId;
}
HashedBytesArray uid = idTypeCache.idByDoc(currentDocId);
if (uidToScore.containsKey(uid)) {
// Can use lget b/c uidToScore is only used by one thread at the time (via CacheRecycler)
currentScore = uidToScore.lget();
currentScore /= uidToCount.get(uid);
remaining--;
return currentDocId;
}
}
}
@Override
public int advance(int target) throws IOException {
if (remaining == 0) {
return currentDocId = NO_MORE_DOCS;
}
currentDocId = parentsIterator.advance(target);
if (currentDocId == DocIdSetIterator.NO_MORE_DOCS) {
return currentDocId;
}
HashedBytesArray uid = idTypeCache.idByDoc(currentDocId);
if (uidToScore.containsKey(uid)) {
// Can use lget b/c uidToScore is only used by one thread at the time (via CacheRecycler)
currentScore = uidToScore.lget();
currentScore /= uidToCount.get(uid);
remaining--;
return currentDocId;
} else {
return nextDoc();
}
}
}
}
private static class ChildUidCollector extends ParentIdCollector {
protected final ObjectFloatOpenHashMap<HashedBytesArray> uidToScore;
private final ScoreType scoreType;
protected Scorer scorer;
ChildUidCollector(ScoreType scoreType, SearchContext searchContext, String childType, ObjectFloatOpenHashMap<HashedBytesArray> uidToScore) {
super(childType, searchContext);
this.uidToScore = uidToScore;
this.scoreType = scoreType;
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
}
@Override
protected void collect(int doc, HashedBytesArray parentUid) throws IOException {
float currentScore = scorer.score();
switch (scoreType) {
case SUM:
uidToScore.addTo(parentUid, currentScore);
break;
case MAX:
if (uidToScore.containsKey(parentUid)) {
float previousScore = uidToScore.lget();
if (currentScore > previousScore) {
uidToScore.lset(currentScore);
}
} else {
uidToScore.put(parentUid, currentScore);
}
break;
case AVG:
assert false : "AVG has its own collector";
default:
assert false : "Are we missing a score type here? -- " + scoreType;
break;
}
}
}
private final static class AvgChildUidCollector extends ChildUidCollector {
private final ObjectIntOpenHashMap<HashedBytesArray> uidToCount;
AvgChildUidCollector(ScoreType scoreType, SearchContext searchContext, String childType, ObjectFloatOpenHashMap<HashedBytesArray> uidToScore, ObjectIntOpenHashMap<HashedBytesArray> uidToCount) {
super(scoreType, searchContext, childType, uidToScore);
this.uidToCount = uidToCount;
assert scoreType == ScoreType.AVG;
}
@Override
protected void collect(int doc, HashedBytesArray parentUid) throws IOException {
float currentScore = scorer.score();
uidToCount.addTo(parentUid, 1);
uidToScore.addTo(parentUid, currentScore);
}
}
} | 1no label
| src_main_java_org_elasticsearch_index_search_child_ChildrenQuery.java |
887 | public final class SetCountRequest extends KeyBasedClientRequest
implements Portable, SecureRequest {
private String name;
private int count;
public SetCountRequest() {
}
public SetCountRequest(String name, int count) {
this.name = name;
this.count = count;
}
@Override
protected Object getKey() {
return name;
}
@Override
protected Operation prepareOperation() {
return new SetCountOperation(name, count);
}
@Override
public String getServiceName() {
return CountDownLatchService.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return CountDownLatchPortableHook.F_ID;
}
@Override
public int getClassId() {
return CountDownLatchPortableHook.SET_COUNT;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("name", name);
writer.writeInt("count", count);
}
@Override
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("name");
count = reader.readInt("count");
}
@Override
public Permission getRequiredPermission() {
return new CountDownLatchPermission(name, ActionConstants.ACTION_MODIFY);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_countdownlatch_client_SetCountRequest.java |
1,341 | public static class MappingUpdatedRequest extends MasterNodeOperationRequest<MappingUpdatedRequest> {
private String index;
private String indexUUID = IndexMetaData.INDEX_UUID_NA_VALUE;
private String type;
private CompressedString mappingSource;
private long order = -1; // -1 means not set...
private String nodeId = null; // null means not set
MappingUpdatedRequest() {
}
public MappingUpdatedRequest(String index, String indexUUID, String type, CompressedString mappingSource, long order, String nodeId) {
this.index = index;
this.indexUUID = indexUUID;
this.type = type;
this.mappingSource = mappingSource;
this.order = order;
this.nodeId = nodeId;
}
public String index() {
return index;
}
public String indexUUID() {
return indexUUID;
}
public String type() {
return type;
}
public CompressedString mappingSource() {
return mappingSource;
}
/**
* Returns -1 if not set...
*/
public long order() {
return this.order;
}
/**
* Returns null for not set.
*/
public String nodeId() {
return this.nodeId;
}
@Override
public ActionRequestValidationException validate() {
return null;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
index = in.readString();
type = in.readString();
mappingSource = CompressedString.readCompressedString(in);
indexUUID = in.readString();
order = in.readLong();
nodeId = in.readOptionalString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(index);
out.writeString(type);
mappingSource.writeTo(out);
out.writeString(indexUUID);
out.writeLong(order);
out.writeOptionalString(nodeId);
}
@Override
public String toString() {
return "index [" + index + "], indexUUID [" + indexUUID + "], type [" + type + "] and source [" + mappingSource + "]";
}
} | 0true
| src_main_java_org_elasticsearch_cluster_action_index_MappingUpdatedAction.java |
1,535 | public class OSchemaProxyObject implements OSchema {
protected OSchema underlying;
public OSchemaProxyObject(OSchema iUnderlying) {
underlying = iUnderlying;
}
@Override
public int countClasses() {
return underlying.countClasses();
}
@Override
public OClass createClass(Class<?> iClass) {
return underlying.createClass(iClass);
}
@Override
public OClass createClass(Class<?> iClass, int iDefaultClusterId) {
return underlying.createClass(iClass, iDefaultClusterId);
}
@Override
public OClass createClass(String iClassName) {
return underlying.createClass(iClassName);
}
@Override
public OClass createClass(String iClassName, OClass iSuperClass) {
return underlying.createClass(iClassName, iSuperClass);
}
@Override
public OClass createClass(String iClassName, OClass iSuperClass, CLUSTER_TYPE iType) {
return underlying.createClass(iClassName, iSuperClass, iType);
}
@Override
public OClass createClass(String iClassName, int iDefaultClusterId) {
return underlying.createClass(iClassName, iDefaultClusterId);
}
@Override
public OClass createClass(String iClassName, OClass iSuperClass, int iDefaultClusterId) {
return underlying.createClass(iClassName, iSuperClass, iDefaultClusterId);
}
@Override
public OClass createClass(String iClassName, OClass iSuperClass, int[] iClusterIds) {
return underlying.createClass(iClassName, iSuperClass, iClusterIds);
}
@Override
public OClass createAbstractClass(Class<?> iClass) {
return underlying.createAbstractClass(iClass);
}
@Override
public OClass createAbstractClass(String iClassName) {
return underlying.createAbstractClass(iClassName);
}
@Override
public OClass createAbstractClass(String iClassName, OClass iSuperClass) {
return underlying.createAbstractClass(iClassName, iSuperClass);
}
@Override
public void dropClass(String iClassName) {
underlying.dropClass(iClassName);
}
@Override
public <RET extends ODocumentWrapper> RET reload() {
return underlying.reload();
}
@Override
public boolean existsClass(String iClassName) {
return underlying.existsClass(iClassName);
}
@Override
public OClass getClass(Class<?> iClass) {
return underlying.getClass(iClass);
}
@Override
public OClass getClass(String iClassName) {
return underlying.getClass(iClassName);
}
@Override
public OClass getOrCreateClass(String iClassName) {
return underlying.getOrCreateClass(iClassName);
}
@Override
public OClass getOrCreateClass(String iClassName, OClass iSuperClass) {
return underlying.getOrCreateClass(iClassName, iSuperClass);
}
@Override
public Collection<OClass> getClasses() {
return underlying.getClasses();
}
@Override
public void create() {
underlying.create();
}
@Override
@Deprecated
public int getVersion() {
return underlying.getVersion();
}
@Override
public ORID getIdentity() {
return underlying.getIdentity();
}
@Override
public <RET extends ODocumentWrapper> RET save() {
return underlying.save();
}
@Override
public Set<OClass> getClassesRelyOnCluster(String iClusterName) {
return underlying.getClassesRelyOnCluster(iClusterName);
}
public OSchema getUnderlying() {
return underlying;
}
/**
* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
*
* @param iPackageName
* The base package
*/
public synchronized void generateSchema(final String iPackageName) {
generateSchema(iPackageName, Thread.currentThread().getContextClassLoader());
}
/**
* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
*
* @param iPackageName
* The base package
*/
public synchronized void generateSchema(final String iPackageName, final ClassLoader iClassLoader) {
OLogManager.instance().debug(this, "Generating schema inside package: %s", iPackageName);
List<Class<?>> classes = null;
try {
classes = OReflectionHelper.getClassesFor(iPackageName, iClassLoader);
} catch (ClassNotFoundException e) {
throw new OException(e);
}
for (Class<?> c : classes) {
generateSchema(c);
}
}
/**
* Generate/updates the SchemaClass and properties from given Class<?>.
*
* @param iClass
* :- the Class<?> to generate
*/
public synchronized void generateSchema(final Class<?> iClass) {
generateSchema(iClass, ODatabaseRecordThreadLocal.INSTANCE.get());
}
/**
* Generate/updates the SchemaClass and properties from given Class<?>.
*
* @param iClass
* :- the Class<?> to generate
*/
public synchronized void generateSchema(final Class<?> iClass, ODatabaseRecord database) {
if (iClass == null || iClass.isInterface() || iClass.isPrimitive() || iClass.isEnum() || iClass.isAnonymousClass())
return;
OObjectEntitySerializer.registerClass(iClass);
OClass schema = database.getMetadata().getSchema().getClass(iClass);
if (schema == null) {
generateOClass(iClass, database);
}
List<String> fields = OObjectEntitySerializer.getClassFields(iClass);
if (fields != null)
for (String field : fields) {
if (schema.existsProperty(field))
continue;
if (OObjectEntitySerializer.isVersionField(iClass, field) || OObjectEntitySerializer.isIdField(iClass, field))
continue;
Field f = OObjectEntitySerializer.getField(field, iClass);
if (f.getType().equals(Object.class) || f.getType().equals(ODocument.class) || f.getType().equals(ORecordBytes.class)) {
continue;
}
OType t = OObjectEntitySerializer.getTypeByClass(iClass, field, f);
if (t == null) {
if (f.getType().isEnum())
t = OType.STRING;
else {
t = OType.LINK;
}
}
switch (t) {
case LINK:
Class<?> linkedClazz = f.getType();
generateLinkProperty(database, schema, field, t, linkedClazz);
break;
case LINKLIST:
case LINKMAP:
case LINKSET:
linkedClazz = OReflectionHelper.getGenericMultivalueType(f);
if (linkedClazz != null)
generateLinkProperty(database, schema, field, t, linkedClazz);
break;
case EMBEDDED:
linkedClazz = f.getType();
if (linkedClazz == null || linkedClazz.equals(Object.class) || linkedClazz.equals(ODocument.class)
|| f.getType().equals(ORecordBytes.class)) {
continue;
} else {
generateLinkProperty(database, schema, field, t, linkedClazz);
}
break;
case EMBEDDEDLIST:
case EMBEDDEDSET:
case EMBEDDEDMAP:
linkedClazz = OReflectionHelper.getGenericMultivalueType(f);
if (linkedClazz == null || linkedClazz.equals(Object.class) || linkedClazz.equals(ODocument.class)
|| f.getType().equals(ORecordBytes.class)) {
continue;
} else {
if (OReflectionHelper.isJavaType(linkedClazz)) {
schema.createProperty(field, t, OType.getTypeByClass(linkedClazz));
} else if (linkedClazz.isEnum()) {
schema.createProperty(field, t, OType.STRING);
} else {
generateLinkProperty(database, schema, field, t, linkedClazz);
}
}
break;
default:
schema.createProperty(field, t);
break;
}
}
}
/**
* Checks if all registered entities has schema generated, if not it generates it
*/
public synchronized void synchronizeSchema() {
OObjectDatabaseTx database = ((OObjectDatabaseTx) ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner());
Collection<Class<?>> registeredEntities = database.getEntityManager().getRegisteredEntities();
boolean automaticSchemaGeneration = database.isAutomaticSchemaGeneration();
boolean reloadSchema = false;
for (Class<?> iClass : registeredEntities) {
if (Proxy.class.isAssignableFrom(iClass) || iClass.isEnum() || OReflectionHelper.isJavaType(iClass)
|| iClass.isAnonymousClass())
return;
if (!database.getMetadata().getSchema().existsClass(iClass.getSimpleName())) {
database.getMetadata().getSchema().createClass(iClass.getSimpleName());
reloadSchema = true;
}
for (Class<?> currentClass = iClass; currentClass != Object.class;) {
if (automaticSchemaGeneration && !currentClass.equals(Object.class) && !currentClass.equals(ODocument.class)) {
((OSchemaProxyObject) database.getMetadata().getSchema()).generateSchema(currentClass, database.getUnderlying());
}
String iClassName = currentClass.getSimpleName();
currentClass = currentClass.getSuperclass();
if (currentClass == null || currentClass.equals(ODocument.class))
// POJO EXTENDS ODOCUMENT: SPECIAL CASE: AVOID TO CONSIDER
// ODOCUMENT FIELDS
currentClass = Object.class;
if (database != null && !database.isClosed() && !currentClass.equals(Object.class)) {
OClass oSuperClass;
OClass currentOClass = database.getMetadata().getSchema().getClass(iClassName);
if (!database.getMetadata().getSchema().existsClass(currentClass.getSimpleName())) {
oSuperClass = database.getMetadata().getSchema().createClass(currentClass.getSimpleName());
reloadSchema = true;
} else {
oSuperClass = database.getMetadata().getSchema().getClass(currentClass.getSimpleName());
reloadSchema = true;
}
if (currentOClass.getSuperClass() == null || !currentOClass.getSuperClass().equals(oSuperClass)) {
currentOClass.setSuperClass(oSuperClass);
reloadSchema = true;
}
}
}
}
if (database != null && !database.isClosed() && reloadSchema) {
database.getMetadata().getSchema().save();
database.getMetadata().getSchema().reload();
}
}
protected static void generateOClass(Class<?> iClass, ODatabaseRecord database) {
boolean reloadSchema = false;
for (Class<?> currentClass = iClass; currentClass != Object.class;) {
String iClassName = currentClass.getSimpleName();
currentClass = currentClass.getSuperclass();
if (currentClass == null || currentClass.equals(ODocument.class))
// POJO EXTENDS ODOCUMENT: SPECIAL CASE: AVOID TO CONSIDER
// ODOCUMENT FIELDS
currentClass = Object.class;
if (ODatabaseRecordThreadLocal.INSTANCE.get() != null && !ODatabaseRecordThreadLocal.INSTANCE.get().isClosed()
&& !currentClass.equals(Object.class)) {
OClass oSuperClass;
OClass currentOClass = database.getMetadata().getSchema().getClass(iClassName);
if (!database.getMetadata().getSchema().existsClass(currentClass.getSimpleName())) {
oSuperClass = database.getMetadata().getSchema().createClass(currentClass.getSimpleName());
reloadSchema = true;
} else {
oSuperClass = database.getMetadata().getSchema().getClass(currentClass.getSimpleName());
reloadSchema = true;
}
if (currentOClass.getSuperClass() == null || !currentOClass.getSuperClass().equals(oSuperClass)) {
currentOClass.setSuperClass(oSuperClass);
reloadSchema = true;
}
}
}
if (reloadSchema) {
database.getMetadata().getSchema().save();
database.getMetadata().getSchema().reload();
}
}
protected static void generateLinkProperty(ODatabaseRecord database, OClass schema, String field, OType t, Class<?> linkedClazz) {
OClass linkedClass = database.getMetadata().getSchema().getClass(linkedClazz);
if (linkedClass == null) {
OObjectEntitySerializer.registerClass(linkedClazz);
linkedClass = database.getMetadata().getSchema().getClass(linkedClazz);
}
schema.createProperty(field, t, linkedClass);
}
} | 0true
| object_src_main_java_com_orientechnologies_orient_object_metadata_schema_OSchemaProxyObject.java |
3,512 | public static class SmartNameFieldMappers {
private final MapperService mapperService;
private final FieldMappers fieldMappers;
private final DocumentMapper docMapper;
private final boolean explicitTypeInName;
public SmartNameFieldMappers(MapperService mapperService, FieldMappers fieldMappers, @Nullable DocumentMapper docMapper, boolean explicitTypeInName) {
this.mapperService = mapperService;
this.fieldMappers = fieldMappers;
this.docMapper = docMapper;
this.explicitTypeInName = explicitTypeInName;
}
/**
* Has at least one mapper for the field.
*/
public boolean hasMapper() {
return !fieldMappers.isEmpty();
}
/**
* The first mapper for the smart named field.
*/
public FieldMapper mapper() {
return fieldMappers.mapper();
}
/**
* All the field mappers for the smart name field.
*/
public FieldMappers fieldMappers() {
return fieldMappers;
}
/**
* If the smart name was a typed field, with a type that we resolved, will return
* <tt>true</tt>.
*/
public boolean hasDocMapper() {
return docMapper != null;
}
/**
* If the smart name was a typed field, with a type that we resolved, will return
* the document mapper for it.
*/
public DocumentMapper docMapper() {
return docMapper;
}
/**
* Returns <tt>true</tt> if the type is explicitly specified in the name.
*/
public boolean explicitTypeInName() {
return this.explicitTypeInName;
}
public boolean explicitTypeInNameWithDocMapper() {
return explicitTypeInName && docMapper != null;
}
/**
* The best effort search analyzer associated with this field.
*/
public Analyzer searchAnalyzer() {
if (hasMapper()) {
Analyzer analyzer = mapper().searchAnalyzer();
if (analyzer != null) {
return analyzer;
}
}
if (docMapper != null && docMapper.searchAnalyzer() != null) {
return docMapper.searchAnalyzer();
}
return mapperService.searchAnalyzer();
}
public Analyzer searchQuoteAnalyzer() {
if (hasMapper()) {
Analyzer analyzer = mapper().searchQuoteAnalyzer();
if (analyzer != null) {
return analyzer;
}
}
if (docMapper != null && docMapper.searchQuotedAnalyzer() != null) {
return docMapper.searchQuotedAnalyzer();
}
return mapperService.searchQuoteAnalyzer();
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_MapperService.java |
127 | public class OReflectionHelper {
private static final String CLASS_EXTENSION = ".class";
public static List<Class<?>> getClassesFor(final Collection<String> classNames, final ClassLoader classLoader)
throws ClassNotFoundException {
List<Class<?>> classes = new ArrayList<Class<?>>(classNames.size());
for (String className : classNames) {
classes.add(Class.forName(className, true, classLoader));
}
return classes;
}
public static List<Class<?>> getClassesFor(final String iPackageName, final ClassLoader iClassLoader)
throws ClassNotFoundException {
// This will hold a list of directories matching the pckgname.
// There may be more than one if a package is split over multiple jars/paths
final List<Class<?>> classes = new ArrayList<Class<?>>();
final ArrayList<File> directories = new ArrayList<File>();
try {
// Ask for all resources for the path
final String packageUrl = iPackageName.replace('.', '/');
Enumeration<URL> resources = iClassLoader.getResources(packageUrl);
if (!resources.hasMoreElements()) {
resources = iClassLoader.getResources(packageUrl + CLASS_EXTENSION);
if (resources.hasMoreElements()) {
throw new IllegalArgumentException(iPackageName + " does not appear to be a valid package but a class");
}
} else {
while (resources.hasMoreElements()) {
final URL res = resources.nextElement();
if (res.getProtocol().equalsIgnoreCase("jar")) {
final JarURLConnection conn = (JarURLConnection) res.openConnection();
final JarFile jar = conn.getJarFile();
for (JarEntry e : Collections.list(jar.entries())) {
if (e.getName().startsWith(iPackageName.replace('.', '/')) && e.getName().endsWith(CLASS_EXTENSION)
&& !e.getName().contains("$")) {
final String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6);
classes.add(Class.forName(className, true, iClassLoader));
}
}
} else
directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
}
}
} catch (NullPointerException x) {
throw new ClassNotFoundException(iPackageName + " does not appear to be " + "a valid package (Null pointer exception)");
} catch (UnsupportedEncodingException encex) {
throw new ClassNotFoundException(iPackageName + " does not appear to be " + "a valid package (Unsupported encoding)");
} catch (IOException ioex) {
throw new ClassNotFoundException("IOException was thrown when trying " + "to get all resources for " + iPackageName);
}
// For every directory identified capture all the .class files
for (File directory : directories) {
if (directory.exists()) {
// Get the list of the files contained in the package
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
classes.addAll(findClasses(file, iPackageName, iClassLoader));
} else {
String className;
if (file.getName().endsWith(CLASS_EXTENSION)) {
className = file.getName().substring(0, file.getName().length() - CLASS_EXTENSION.length());
classes.add(Class.forName(iPackageName + '.' + className, true, iClassLoader));
}
}
}
} else {
throw new ClassNotFoundException(iPackageName + " (" + directory.getPath() + ") does not appear to be a valid package");
}
}
return classes;
}
/**
* Recursive method used to find all classes in a given directory and subdirs.
*
* @param iDirectory
* The base directory
* @param iPackageName
* The package name for classes found inside the base directory
* @return The classes
* @throws ClassNotFoundException
*/
private static List<Class<?>> findClasses(final File iDirectory, String iPackageName, ClassLoader iClassLoader)
throws ClassNotFoundException {
final List<Class<?>> classes = new ArrayList<Class<?>>();
if (!iDirectory.exists())
return classes;
iPackageName += "." + iDirectory.getName();
String className;
final File[] files = iDirectory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
if (file.getName().contains("."))
continue;
classes.addAll(findClasses(file, iPackageName, iClassLoader));
} else if (file.getName().endsWith(CLASS_EXTENSION)) {
className = file.getName().substring(0, file.getName().length() - CLASS_EXTENSION.length());
classes.add(Class.forName(iPackageName + '.' + className, true, iClassLoader));
}
}
return classes;
}
/**
* Filters discovered classes to see if they implement a given interface.
*
* @param thePackage
* @param theInterface
* @param iClassLoader
* @return The list of classes that implements the requested interface
*/
public static List<Class<?>> getClassessOfInterface(String thePackage, Class<?> theInterface, final ClassLoader iClassLoader) {
List<Class<?>> classList = new ArrayList<Class<?>>();
try {
for (Class<?> discovered : getClassesFor(thePackage, iClassLoader)) {
if (Arrays.asList(discovered.getInterfaces()).contains(theInterface)) {
classList.add(discovered);
}
}
} catch (ClassNotFoundException ex) {
OLogManager.instance().error(null, "Error finding classes", ex);
}
return classList;
}
/**
* Returns the declared generic types of a class.
*
* @param iClass
* Class to examine
* @return The array of Type if any, otherwise null
*/
public static Type[] getGenericTypes(final Class<?> iClass) {
final Type genericType = iClass.getGenericInterfaces()[0];
if (genericType != null && genericType instanceof ParameterizedType) {
final ParameterizedType pt = (ParameterizedType) genericType;
if (pt.getActualTypeArguments() != null && pt.getActualTypeArguments().length > 1)
return pt.getActualTypeArguments();
}
return null;
}
/**
* Returns the generic class of multi-value objects.
*
* @param p
* Field to examine
* @return The Class<?> of generic type if any, otherwise null
*/
public static Class<?> getGenericMultivalueType(final Field p) {
if (p.getType() instanceof Class<?>) {
final Type genericType = p.getGenericType();
if (genericType != null && genericType instanceof ParameterizedType) {
final ParameterizedType pt = (ParameterizedType) genericType;
if (pt.getActualTypeArguments() != null && pt.getActualTypeArguments().length > 0) {
if (((Class<?>) pt.getRawType()).isAssignableFrom(Map.class)) {
if (pt.getActualTypeArguments()[1] instanceof Class<?>) {
return (Class<?>) pt.getActualTypeArguments()[1];
} else if (pt.getActualTypeArguments()[1] instanceof ParameterizedType)
return (Class<?>) ((ParameterizedType) pt.getActualTypeArguments()[1]).getRawType();
} else if (pt.getActualTypeArguments()[0] instanceof Class<?>) {
return (Class<?>) pt.getActualTypeArguments()[0];
} else if (pt.getActualTypeArguments()[0] instanceof ParameterizedType)
return (Class<?>) ((ParameterizedType) pt.getActualTypeArguments()[0]).getRawType();
}
} else if (p.getType().isArray())
return p.getType().getComponentType();
}
return null;
}
/**
* Checks if a class is a Java type: Map, Collection,arrays, Number (extensions and primitives), String, Boolean..
*
* @param clazz
* Class<?> to examine
* @return true if clazz is Java type, false otherwise
*/
public static boolean isJavaType(Class<?> clazz) {
if (clazz.isPrimitive())
return true;
else if (clazz.getName().startsWith("java.lang"))
return true;
else if (clazz.getName().startsWith("java.util"))
return true;
else if (clazz.isArray())
return true;
return false;
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_reflection_OReflectionHelper.java |
218 | }, READ_COMMITTED {
@Override
void configure(TransactionConfig cfg) {
cfg.setReadCommitted(true);
}
}, REPEATABLE_READ { | 0true
| titan-berkeleyje_src_main_java_com_thinkaurelius_titan_diskstorage_berkeleyje_BerkeleyJEStoreManager.java |
3,494 | public static class Aggregator extends FieldMapperListener {
public final List<FieldMapper> mappers = new ArrayList<FieldMapper>();
@Override
public void fieldMapper(FieldMapper fieldMapper) {
mappers.add(fieldMapper);
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_FieldMapperListener.java |
2,907 | return new AttributeFactory() {
@Override
public AttributeImpl createAttributeInstance(Class<? extends Attribute> attClass) {
return (AttributeImpl) source.addAttribute(attClass);
}
}; | 0true
| src_main_java_org_elasticsearch_index_analysis_NumericTokenizer.java |
513 | public class MonthType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, MonthType> TYPES = new LinkedHashMap<String, MonthType>();
public static final MonthType JANUARY = new MonthType("1", "January");
public static final MonthType FEBRUARY = new MonthType("2", "February");
public static final MonthType MARCH = new MonthType("3", "March");
public static final MonthType APRIL = new MonthType("4", "April");
public static final MonthType MAY = new MonthType("5", "May");
public static final MonthType JUNE = new MonthType("6", "June");
public static final MonthType JULY = new MonthType("7", "July");
public static final MonthType AUGUST = new MonthType("8", "August");
public static final MonthType SEPTEMBER = new MonthType("9", "September");
public static final MonthType OCTOBER = new MonthType("10", "October");
public static final MonthType NOVEMBER = new MonthType("11", "November");
public static final MonthType DECEMBER = new MonthType("12", "December");
public static MonthType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public MonthType() {
//do nothing
}
public MonthType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
} else {
throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MonthType other = (MonthType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
} | 1no label
| common_src_main_java_org_broadleafcommerce_common_time_MonthType.java |
2,353 | public class LocalTransportAddress implements TransportAddress {
private String id;
LocalTransportAddress() {
}
public LocalTransportAddress(String id) {
this.id = id;
}
public String id() {
return this.id;
}
@Override
public short uniqueAddressTypeId() {
return 2;
}
@Override
public void readFrom(StreamInput in) throws IOException {
id = in.readString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(id);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LocalTransportAddress that = (LocalTransportAddress) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
@Override
public String toString() {
return "local[" + id + "]";
}
} | 0true
| src_main_java_org_elasticsearch_common_transport_LocalTransportAddress.java |
1,168 | public static enum INDEX_OPERATION_TYPE {
GET, COUNT
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperator.java |
1,495 | class DefaultAddressPicker implements AddressPicker {
private final ILogger logger;
private final Node node;
private ServerSocketChannel serverSocketChannel;
private Address publicAddress;
private Address bindAddress;
public DefaultAddressPicker(Node node) {
this.node = node;
this.logger = node.getLogger(DefaultAddressPicker.class);
}
@Override
public void pickAddress() throws Exception {
if (publicAddress != null || bindAddress != null) {
return;
}
try {
final NetworkConfig networkConfig = node.getConfig().getNetworkConfig();
final AddressDefinition bindAddressDef = pickAddress(networkConfig);
final boolean reuseAddress = networkConfig.isReuseAddress();
final boolean bindAny = node.getGroupProperties().SOCKET_SERVER_BIND_ANY.getBoolean();
final int portCount = networkConfig.getPortCount();
/**
* why setReuseAddress(true)?
* when the member is shutdown,
* the server socket port will be in TIME_WAIT state for the next
* 2 minutes or so. If you start the member right after shutting it down
* you may not be able to bind to the same port because it is in TIME_WAIT
* state. if you set reuseAddress=true then TIME_WAIT will be ignored and
* you will be able to bind to the same port again.
*
* this will cause problem on windows
* see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6421091
* http://www.hsc.fr/ressources/articles/win_net_srv/multiple_bindings.html
*
* By default if the OS is Windows then reuseAddress will be false.
*/
log(Level.FINEST, "inet reuseAddress:" + reuseAddress);
InetSocketAddress inetSocketAddress;
ServerSocket serverSocket = null;
int port = networkConfig.getPort();
Throwable error = null;
for (int i = 0; i < portCount; i++) {
/**
* Instead of reusing the ServerSocket/ServerSocketChannel, we are going to close and replace them on
* every attempt to find a free port. The reason to do this is because in some cases, when concurrent
* threads/processes try to acquire the same port, the ServerSocket gets corrupted and isn't able to
* find any free port at all (no matter if there are more than enough free ports available). We have
* seen this happening on Linux and Windows environments.
*/
serverSocketChannel = ServerSocketChannel.open();
serverSocket = serverSocketChannel.socket();
serverSocket.setReuseAddress(reuseAddress);
serverSocket.setSoTimeout(1000);
try {
if (bindAny) {
inetSocketAddress = new InetSocketAddress(port);
} else {
inetSocketAddress = new InetSocketAddress(bindAddressDef.inetAddress, port);
}
log(Level.FINEST, "Trying to bind inet socket address:" + inetSocketAddress);
serverSocket.bind(inetSocketAddress, 100);
log(Level.FINEST, "Bind successful to inet socket address:" + inetSocketAddress);
break;
} catch (final Exception e) {
serverSocket.close();
serverSocketChannel.close();
if (networkConfig.isPortAutoIncrement()) {
port++;
error = e;
} else {
String msg = "Port [" + port + "] is already in use and auto-increment is "
+ "disabled. Hazelcast cannot start.";
logger.severe(msg, e);
throw new HazelcastException(msg, error);
}
}
}
if (serverSocket == null || !serverSocket.isBound()) {
throw new HazelcastException("ServerSocket bind has failed. Hazelcast cannot start! "
+ "config-port: " + networkConfig.getPort() + ", latest-port: " + port, error);
}
serverSocketChannel.configureBlocking(false);
bindAddress = createAddress(bindAddressDef, port);
log(Level.INFO, "Picked " + bindAddress + ", using socket " + serverSocket + ", bind any local is "
+ bindAny);
AddressDefinition publicAddressDef = getPublicAddress(node.getConfig(), port);
if (publicAddressDef != null) {
publicAddress = createAddress(publicAddressDef, publicAddressDef.port);
log(Level.INFO, "Using public address: " + publicAddress);
} else {
publicAddress = bindAddress;
log(Level.FINEST, "Using public address the same as the bind address. " + publicAddress);
}
} catch (RuntimeException re) {
logger.severe(re);
throw re;
} catch (Exception e) {
logger.severe(e);
throw e;
}
}
private Address createAddress(final AddressDefinition addressDef, final int port) throws UnknownHostException {
return addressDef.host != null ? new Address(addressDef.host, port)
: new Address(addressDef.inetAddress, port);
}
private AddressDefinition pickAddress(final NetworkConfig networkConfig)
throws UnknownHostException, SocketException {
AddressDefinition addressDef = getSystemConfiguredAddress(node.getConfig());
if (addressDef == null) {
final Collection<InterfaceDefinition> interfaces = getInterfaces(networkConfig);
if (interfaces.contains(new InterfaceDefinition("127.0.0.1"))
|| interfaces.contains(new InterfaceDefinition("localhost"))) {
addressDef = pickLoopbackAddress();
} else {
if (preferIPv4Stack()) {
log(Level.INFO, "Prefer IPv4 stack is true.");
}
if (interfaces.size() > 0) {
addressDef = pickMatchingAddress(interfaces);
}
if (addressDef == null) {
if (networkConfig.getInterfaces().isEnabled()) {
String msg = "Hazelcast CANNOT start on this node. No matching network interface found. ";
msg += "\nInterface matching must be either disabled or updated in the hazelcast.xml config file.";
logger.severe(msg);
throw new RuntimeException(msg);
} else {
if (networkConfig.getJoin().getTcpIpConfig().isEnabled()) {
logger.warning("Could not find a matching address to start with! "
+ "Picking one of non-loopback addresses.");
}
addressDef = pickMatchingAddress(null);
}
}
}
}
if (addressDef != null) {
// check if scope id correctly set
addressDef.inetAddress = AddressUtil.fixScopeIdAndGetInetAddress(addressDef.inetAddress);
}
if (addressDef == null) {
addressDef = pickLoopbackAddress();
}
return addressDef;
}
private Collection<InterfaceDefinition> getInterfaces(final NetworkConfig networkConfig)
throws UnknownHostException {
final Map<String, String> addressDomainMap; // address -> domain
final TcpIpConfig tcpIpConfig = networkConfig.getJoin().getTcpIpConfig();
if (tcpIpConfig.isEnabled()) {
addressDomainMap = new LinkedHashMap<String, String>(); // LinkedHashMap is to guarantee order
final Collection<String> possibleAddresses = TcpIpJoiner.getConfigurationMembers(node.config);
for (String possibleAddress : possibleAddresses) {
final String s = AddressUtil.getAddressHolder(possibleAddress).getAddress();
if (AddressUtil.isIpAddress(s)) {
if (!addressDomainMap.containsKey(s)) { // there may be a domain registered for this address
addressDomainMap.put(s, null);
}
} else {
try {
final Collection<String> addresses = resolveDomainNames(s);
for (String address : addresses) {
addressDomainMap.put(address, s);
}
} catch (UnknownHostException e) {
logger.severe("Could not resolve address: " + s);
}
}
}
} else {
addressDomainMap = Collections.emptyMap();
}
final Collection<InterfaceDefinition> interfaces = new HashSet<InterfaceDefinition>();
if (networkConfig.getInterfaces().isEnabled()) {
final Collection<String> configInterfaces = networkConfig.getInterfaces().getInterfaces();
for (String configInterface : configInterfaces) {
if (AddressUtil.isIpAddress(configInterface)) {
String hostname = findHostnameMatchingInterface(addressDomainMap, configInterface);
interfaces.add(new InterfaceDefinition(hostname, configInterface));
} else {
logger.info("'" + configInterface
+ "' is not an IP address! Removing from interface list.");
}
}
log(Level.INFO, "Interfaces is enabled, trying to pick one address matching "
+ "to one of: " + interfaces);
} else if (tcpIpConfig.isEnabled()) {
for (Entry<String, String> entry : addressDomainMap.entrySet()) {
interfaces.add(new InterfaceDefinition(entry.getValue(), entry.getKey()));
}
log(Level.INFO, "Interfaces is disabled, trying to pick one address from TCP-IP config "
+ "addresses: " + interfaces);
}
return interfaces;
}
private String findHostnameMatchingInterface(Map<String, String> addressDomainMap, String configInterface) {
String hostname = addressDomainMap.get(configInterface);
if (hostname != null) {
return hostname;
}
for (Entry<String, String> entry : addressDomainMap.entrySet()) {
String address = entry.getKey();
if (AddressUtil.matchInterface(address, configInterface)) {
return entry.getValue();
}
}
return null;
}
private Collection<String> resolveDomainNames(final String domainName)
throws UnknownHostException {
final InetAddress[] inetAddresses = InetAddress.getAllByName(domainName);
final Collection<String> addresses = new LinkedList<String>();
for (InetAddress inetAddress : inetAddresses) {
addresses.add(inetAddress.getHostAddress());
}
logger.info("Resolving domain name '" + domainName + "' to address(es): " + addresses);
return addresses;
}
private AddressDefinition getSystemConfiguredAddress(Config config) throws UnknownHostException {
String address = config.getProperty("hazelcast.local.localAddress");
if (address != null) {
address = address.trim();
if ("127.0.0.1".equals(address) || "localhost".equals(address)) {
return pickLoopbackAddress();
} else {
log(Level.INFO, "Picking address configured by property 'hazelcast.local.localAddress'");
return new AddressDefinition(address, InetAddress.getByName(address));
}
}
return null;
}
private AddressDefinition getPublicAddress(Config config, int defaultPort) throws UnknownHostException {
String address = config.getProperty("hazelcast.local.publicAddress");
if (address == null) {
address = config.getNetworkConfig().getPublicAddress();
}
if (address != null) {
address = address.trim();
if ("127.0.0.1".equals(address) || "localhost".equals(address)) {
return pickLoopbackAddress();
} else {
// Allow port to be defined in same string in the form of <host>:<port>. i.e. 10.0.0.0:1234
AddressUtil.AddressHolder holder = AddressUtil.getAddressHolder(address, defaultPort);
return new AddressDefinition(holder.getAddress(), holder.getPort(), InetAddress.getByName(holder.getAddress()));
}
}
return null;
}
private AddressDefinition pickLoopbackAddress() throws UnknownHostException {
return new AddressDefinition(InetAddress.getByName("127.0.0.1"));
}
private AddressDefinition pickMatchingAddress(final Collection<InterfaceDefinition> interfaces) throws SocketException {
final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
final boolean preferIPv4Stack = preferIPv4Stack();
while (networkInterfaces.hasMoreElements()) {
final NetworkInterface ni = networkInterfaces.nextElement();
final Enumeration<InetAddress> e = ni.getInetAddresses();
while (e.hasMoreElements()) {
final InetAddress inetAddress = e.nextElement();
if (preferIPv4Stack && inetAddress instanceof Inet6Address) {
continue;
}
if (interfaces != null && !interfaces.isEmpty()) {
final AddressDefinition address;
if ((address = match(inetAddress, interfaces)) != null) {
return address;
}
} else if (!inetAddress.isLoopbackAddress()) {
return new AddressDefinition(inetAddress);
}
}
}
return null;
}
private AddressDefinition match(final InetAddress address, final Collection<InterfaceDefinition> interfaces) {
for (final InterfaceDefinition inf : interfaces) {
if (AddressUtil.matchInterface(address.getHostAddress(), inf.address)) {
return new AddressDefinition(inf.host, address);
}
}
return null;
}
private boolean preferIPv4Stack() {
boolean preferIPv4Stack = Boolean.getBoolean("java.net.preferIPv4Stack")
|| node.groupProperties.PREFER_IPv4_STACK.getBoolean();
// AWS does not support IPv6.
JoinConfig join = node.getConfig().getNetworkConfig().getJoin();
AwsConfig awsConfig = join.getAwsConfig();
boolean awsEnabled = awsConfig != null && awsConfig.isEnabled();
return preferIPv4Stack || awsEnabled;
}
@Deprecated
public Address getAddress() {
return getBindAddress();
}
@Override
public Address getBindAddress() {
return bindAddress;
}
@Override
public Address getPublicAddress() {
return publicAddress;
}
@Override
public ServerSocketChannel getServerSocketChannel() {
return serverSocketChannel;
}
private void log(Level level, String message) {
logger.log(level, message);
node.getSystemLogService().logNode(message);
}
private class InterfaceDefinition {
String host;
String address;
private InterfaceDefinition() {
}
private InterfaceDefinition(final String address) {
this.host = null;
this.address = address;
}
private InterfaceDefinition(final String host, final String address) {
this.host = host;
this.address = address;
}
@Override
public String toString() {
return host != null ? (host + "/" + address) : address;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final InterfaceDefinition that = (InterfaceDefinition) o;
if (address != null ? !address.equals(that.address) : that.address != null) {
return false;
}
if (host != null ? !host.equals(that.host) : that.host != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = host != null ? host.hashCode() : 0;
result = 31 * result + (address != null ? address.hashCode() : 0);
return result;
}
}
private class AddressDefinition extends InterfaceDefinition {
InetAddress inetAddress;
int port;
private AddressDefinition() {
}
private AddressDefinition(final InetAddress inetAddress) {
super(inetAddress.getHostAddress());
this.inetAddress = inetAddress;
}
private AddressDefinition(final String host, final InetAddress inetAddress) {
super(host, inetAddress.getHostAddress());
this.inetAddress = inetAddress;
}
private AddressDefinition(final String host, final int port, final InetAddress inetAddress) {
super(host, inetAddress.getHostAddress());
this.inetAddress = inetAddress;
this.port = port;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)){
return false;
}
AddressDefinition that = (AddressDefinition) o;
if (port != that.port) {
return false;
}
if (inetAddress != null ? !inetAddress.equals(that.inetAddress) : that.inetAddress != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (inetAddress != null ? inetAddress.hashCode() : 0);
result = 31 * result + port;
return result;
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_instance_DefaultAddressPicker.java |
1,930 | public interface ScopedBindingBuilder {
/**
* See the EDSL examples at {@link org.elasticsearch.common.inject.Binder}.
*/
void in(Class<? extends Annotation> scopeAnnotation);
/**
* See the EDSL examples at {@link org.elasticsearch.common.inject.Binder}.
*/
void in(Scope scope);
/**
* Instructs the {@link org.elasticsearch.common.inject.Injector} to eagerly initialize this
* singleton-scoped binding upon creation. Useful for application
* initialization logic. See the EDSL examples at
* {@link org.elasticsearch.common.inject.Binder}.
*/
void asEagerSingleton();
} | 0true
| src_main_java_org_elasticsearch_common_inject_binder_ScopedBindingBuilder.java |
2,365 | TB {
@Override
public long toBytes(long size) {
return x(size, C4 / C0, MAX / (C4 / C0));
}
@Override
public long toKB(long size) {
return x(size, C4 / C1, MAX / (C4 / C1));
}
@Override
public long toMB(long size) {
return x(size, C4 / C2, MAX / (C4 / C2));
}
@Override
public long toGB(long size) {
return x(size, C4 / C3, MAX / (C4 / C3));
}
@Override
public long toTB(long size) {
return size;
}
@Override
public long toPB(long size) {
return size / (C5 / C4);
}
}, | 0true
| src_main_java_org_elasticsearch_common_unit_ByteSizeUnit.java |
1,337 | public class OOperationUnitId {
public static final int SERIALIZED_SIZE = 2 * OLongSerializer.LONG_SIZE;
private UUID uuid;
public static OOperationUnitId generateId() {
OOperationUnitId operationUnitId = new OOperationUnitId();
operationUnitId.uuid = UUID.randomUUID();
return operationUnitId;
}
public OOperationUnitId() {
}
public OOperationUnitId(UUID uuid) {
this.uuid = uuid;
}
public int toStream(byte[] content, int offset) {
OLongSerializer.INSTANCE.serializeNative(uuid.getMostSignificantBits(), content, offset);
offset += OLongSerializer.LONG_SIZE;
OLongSerializer.INSTANCE.serializeNative(uuid.getLeastSignificantBits(), content, offset);
offset += OLongSerializer.LONG_SIZE;
return offset;
}
public int fromStream(byte[] content, int offset) {
long most = OLongSerializer.INSTANCE.deserializeNative(content, offset);
offset += OLongSerializer.LONG_SIZE;
long least = OLongSerializer.INSTANCE.deserializeNative(content, offset);
offset += OLongSerializer.LONG_SIZE;
uuid = new UUID(most, least);
return offset;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
OOperationUnitId that = (OOperationUnitId) o;
if (!uuid.equals(that.uuid))
return false;
return true;
}
@Override
public int hashCode() {
return uuid.hashCode();
}
@Override
public String toString() {
return "OOperationUnitId{" + "uuid=" + uuid + "} ";
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_OOperationUnitId.java |
803 | multiGetAction.execute(multiGetRequest, new ActionListener<MultiGetResponse>() {
@Override
public void onResponse(MultiGetResponse multiGetItemResponses) {
for (int i = 0; i < multiGetItemResponses.getResponses().length; i++) {
MultiGetItemResponse itemResponse = multiGetItemResponses.getResponses()[i];
int slot = getRequestSlots.get(i);
if (!itemResponse.isFailed()) {
GetResponse getResponse = itemResponse.getResponse();
if (getResponse.isExists()) {
PercolateRequest originalRequest = (PercolateRequest) percolateRequests.get(slot);
percolateRequests.set(slot, new PercolateRequest(originalRequest, getResponse.getSourceAsBytesRef()));
} else {
logger.trace("mpercolate existing doc, item[{}] doesn't exist", slot);
percolateRequests.set(slot, new DocumentMissingException(null, getResponse.getType(), getResponse.getId()));
}
} else {
logger.trace("mpercolate existing doc, item[{}] failure {}", slot, itemResponse.getFailure());
percolateRequests.set(slot, itemResponse.getFailure());
}
}
new ASyncAction(percolateRequests, listener, clusterState).run();
}
@Override
public void onFailure(Throwable e) {
listener.onFailure(e);
}
}); | 0true
| src_main_java_org_elasticsearch_action_percolate_TransportMultiPercolateAction.java |
973 | public class BeforeAwaitBackupOperation extends BaseLockOperation implements BackupOperation {
private String conditionId;
private String originalCaller;
public BeforeAwaitBackupOperation() {
}
public BeforeAwaitBackupOperation(ObjectNamespace namespace, Data key, long threadId,
String conditionId, String originalCaller) {
super(namespace, key, threadId);
this.conditionId = conditionId;
this.originalCaller = originalCaller;
}
@Override
public void run() throws Exception {
LockStoreImpl lockStore = getLockStore();
lockStore.addAwait(key, conditionId, originalCaller, threadId);
lockStore.unlock(key, originalCaller, threadId);
response = true;
}
@Override
public int getId() {
return LockDataSerializerHook.BEFORE_AWAIT_BACKUP;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeUTF(originalCaller);
out.writeUTF(conditionId);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
originalCaller = in.readUTF();
conditionId = in.readUTF();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_operations_BeforeAwaitBackupOperation.java |
20 | public class DeleteCommand extends AbstractTextCommand {
ByteBuffer response;
private final String key;
private final int expiration;
private final boolean noreply;
public DeleteCommand(String key, int expiration, boolean noreply) {
super(TextCommandType.DELETE);
this.key = key;
this.expiration = expiration;
this.noreply = noreply;
}
public boolean readFrom(ByteBuffer cb) {
return true;
}
public void setResponse(byte[] value) {
this.response = ByteBuffer.wrap(value);
}
public boolean writeTo(ByteBuffer bb) {
if (response == null) {
response = ByteBuffer.wrap(STORED);
}
while (bb.hasRemaining() && response.hasRemaining()) {
bb.put(response.get());
}
return !response.hasRemaining();
}
public boolean shouldReply() {
return !noreply;
}
public int getExpiration() {
return expiration;
}
public String getKey() {
return key;
}
@Override
public String toString() {
return "DeleteCommand [" + type + "]{"
+ "key='" + key + '\''
+ ", expiration=" + expiration
+ ", noreply=" + noreply + '}'
+ super.toString();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_ascii_memcache_DeleteCommand.java |
133 | public enum SchemaStatus {
/**
* The index is installed in the system but not yet registered with all instances in the cluster
*/
INSTALLED,
/**
* The index is registered with all instances in the cluster but not (yet) enabled
*/
REGISTERED,
/**
* The index is enabled and in use
*/
ENABLED,
/**
* The index is disabled and no longer in use
*/
DISABLED;
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_schema_SchemaStatus.java |
275 | public class SimpleClientInterceptor implements MapInterceptor, Portable {
public static final int ID = 345;
@Override
public Object interceptGet(Object value) {
if (value == null)
return null;
return value + ":";
}
@Override
public void afterGet(Object value) {
}
@Override
public Object interceptPut(Object oldValue, Object newValue) {
return newValue.toString().toUpperCase();
}
@Override
public void afterPut(Object value) {
}
@Override
public Object interceptRemove(Object removedValue) {
if (removedValue.equals("ISTANBUL"))
throw new RuntimeException("you can not remove this");
return removedValue;
}
@Override
public void afterRemove(Object value) {
}
@Override
public int getFactoryId() {
return PortableHelpersFactory.ID; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public int getClassId() {
return ID; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void writePortable(PortableWriter writer) throws IOException {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void readPortable(PortableReader reader) throws IOException {
//To change body of implemented methods use File | Settings | File Templates.
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_helpers_SimpleClientInterceptor.java |
1,116 | public class PercolatorStressBenchmark {
public static void main(String[] args) throws Exception {
Settings settings = settingsBuilder()
.put("cluster.routing.schedule", 200, TimeUnit.MILLISECONDS)
.put("gateway.type", "none")
.put(SETTING_NUMBER_OF_SHARDS, 4)
.put(SETTING_NUMBER_OF_REPLICAS, 0)
.build();
Node[] nodes = new Node[1];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = nodeBuilder().settings(settingsBuilder().put(settings).put("name", "node" + i)).node();
}
Node clientNode = nodeBuilder().settings(settingsBuilder().put(settings).put("name", "client")).client(true).node();
Client client = clientNode.client();
client.admin().indices().create(createIndexRequest("test")).actionGet();
ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth("test")
.setWaitForGreenStatus()
.execute().actionGet();
if (healthResponse.isTimedOut()) {
System.err.println("Quiting, because cluster health requested timed out...");
return;
} else if (healthResponse.getStatus() != ClusterHealthStatus.GREEN) {
System.err.println("Quiting, because cluster state isn't green...");
return;
}
int COUNT = 200000;
int QUERIES = 100;
int TERM_QUERIES = QUERIES / 2;
int RANGE_QUERIES = QUERIES - TERM_QUERIES;
client.prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject().field("numeric1", 1).endObject()).execute().actionGet();
// register queries
int i = 0;
for (; i < TERM_QUERIES; i++) {
client.prepareIndex("test", PercolatorService.TYPE_NAME, Integer.toString(i))
.setSource(jsonBuilder().startObject()
.field("query", termQuery("name", "value"))
.endObject())
.execute().actionGet();
}
int[] numbers = new int[RANGE_QUERIES];
for (; i < QUERIES; i++) {
client.prepareIndex("test", PercolatorService.TYPE_NAME, Integer.toString(i))
.setSource(jsonBuilder().startObject()
.field("query", rangeQuery("numeric1").from(i).to(i))
.endObject())
.execute().actionGet();
numbers[i - TERM_QUERIES] = i;
}
StopWatch stopWatch = new StopWatch().start();
System.out.println("Percolating [" + COUNT + "] ...");
for (i = 1; i <= COUNT; i++) {
XContentBuilder source;
int expectedMatches;
if (i % 2 == 0) {
source = source(Integer.toString(i), "value");
expectedMatches = TERM_QUERIES;
} else {
int number = numbers[i % RANGE_QUERIES];
source = source(Integer.toString(i), number);
expectedMatches = 1;
}
PercolateResponse percolate = client.preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(source)
.execute().actionGet();
if (percolate.getMatches().length != expectedMatches) {
System.err.println("No matching number of queries");
}
if ((i % 10000) == 0) {
System.out.println("Percolated " + i + " took " + stopWatch.stop().lastTaskTime());
stopWatch.start();
}
}
System.out.println("Percolation took " + stopWatch.totalTime() + ", TPS " + (((double) COUNT) / stopWatch.totalTime().secondsFrac()));
clientNode.close();
for (Node node : nodes) {
node.close();
}
}
private static XContentBuilder source(String id, String nameValue) throws IOException {
return jsonBuilder().startObject().startObject("doc")
.field("id", id)
.field("name", nameValue)
.endObject().endObject();
}
private static XContentBuilder source(String id, int number) throws IOException {
return jsonBuilder().startObject().startObject("doc")
.field("id", id)
.field("numeric1", number)
.field("numeric2", number)
.field("numeric3", number)
.field("numeric4", number)
.field("numeric5", number)
.field("numeric6", number)
.field("numeric7", number)
.field("numeric8", number)
.field("numeric9", number)
.field("numeric10", number)
.endObject().endObject();
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_percolator_PercolatorStressBenchmark.java |
1,262 | class SniffNodesSampler extends NodeSampler {
@Override
protected void doSample() {
// the nodes we are going to ping include the core listed nodes that were added
// and the last round of discovered nodes
Set<DiscoveryNode> nodesToPing = Sets.newHashSet();
for (DiscoveryNode node : listedNodes) {
nodesToPing.add(node);
}
for (DiscoveryNode node : nodes) {
nodesToPing.add(node);
}
final CountDownLatch latch = new CountDownLatch(nodesToPing.size());
final ConcurrentMap<DiscoveryNode, ClusterStateResponse> clusterStateResponses = ConcurrentCollections.newConcurrentMap();
for (final DiscoveryNode listedNode : nodesToPing) {
threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new Runnable() {
@Override
public void run() {
try {
if (!transportService.nodeConnected(listedNode)) {
try {
// if its one of hte actual nodes we will talk to, not to listed nodes, fully connect
if (nodes.contains(listedNode)) {
logger.trace("connecting to cluster node [{}]", listedNode);
transportService.connectToNode(listedNode);
} else {
// its a listed node, light connect to it...
logger.trace("connecting to listed node (light) [{}]", listedNode);
transportService.connectToNodeLight(listedNode);
}
} catch (Exception e) {
logger.debug("failed to connect to node [{}], ignoring...", e, listedNode);
latch.countDown();
return;
}
}
transportService.sendRequest(listedNode, ClusterStateAction.NAME,
Requests.clusterStateRequest()
.clear().nodes(true).local(true),
TransportRequestOptions.options().withType(TransportRequestOptions.Type.STATE).withTimeout(pingTimeout),
new BaseTransportResponseHandler<ClusterStateResponse>() {
@Override
public ClusterStateResponse newInstance() {
return new ClusterStateResponse();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(ClusterStateResponse response) {
clusterStateResponses.put(listedNode, response);
latch.countDown();
}
@Override
public void handleException(TransportException e) {
logger.info("failed to get local cluster state for {}, disconnecting...", e, listedNode);
transportService.disconnectFromNode(listedNode);
latch.countDown();
}
});
} catch (Throwable e) {
logger.info("failed to get local cluster state info for {}, disconnecting...", e, listedNode);
transportService.disconnectFromNode(listedNode);
latch.countDown();
}
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
return;
}
HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>(listedNodes);
HashSet<DiscoveryNode> newFilteredNodes = new HashSet<DiscoveryNode>();
for (Map.Entry<DiscoveryNode, ClusterStateResponse> entry : clusterStateResponses.entrySet()) {
if (!ignoreClusterName && !clusterName.equals(entry.getValue().getClusterName())) {
logger.warn("node {} not part of the cluster {}, ignoring...", entry.getValue().getState().nodes().localNode(), clusterName);
newFilteredNodes.add(entry.getKey());
continue;
}
for (ObjectCursor<DiscoveryNode> cursor : entry.getValue().getState().nodes().dataNodes().values()) {
newNodes.add(cursor.value);
}
}
nodes = validateNewNodes(newNodes);
filteredNodes = ImmutableList.copyOf(newFilteredNodes);
}
} | 1no label
| src_main_java_org_elasticsearch_client_transport_TransportClientNodesService.java |
2,162 | protected static final DocIdSet EMPTY_DOCIDSET = new DocIdSet() {
@Override
public DocIdSetIterator iterator() {
return DocIdSetIterator.empty();
}
@Override
public boolean isCacheable() {
return true;
}
// we explicitly provide no random access, as this filter is 100% sparse and iterator exits faster
@Override
public Bits bits() {
return null;
}
}; | 0true
| src_main_java_org_elasticsearch_common_lucene_docset_DocIdSets.java |
443 | public class KCVSProxy implements KeyColumnValueStore {
protected final KeyColumnValueStore store;
public KCVSProxy(KeyColumnValueStore store) {
Preconditions.checkArgument(store!=null);
this.store = store;
}
protected StoreTransaction unwrapTx(StoreTransaction txh) {
return txh;
}
@Override
public void close() throws BackendException {
store.close();
}
@Override
public void acquireLock(StaticBuffer key, StaticBuffer column, StaticBuffer expectedValue,
StoreTransaction txh) throws BackendException {
store.acquireLock(key,column,expectedValue,unwrapTx(txh));
}
@Override
public KeyIterator getKeys(KeyRangeQuery keyQuery, StoreTransaction txh) throws BackendException {
return store.getKeys(keyQuery, unwrapTx(txh));
}
@Override
public KeyIterator getKeys(SliceQuery columnQuery, StoreTransaction txh) throws BackendException {
return store.getKeys(columnQuery, unwrapTx(txh));
}
@Override
public String getName() {
return store.getName();
}
@Override
public void mutate(StaticBuffer key, List<Entry> additions, List<StaticBuffer> deletions, StoreTransaction txh) throws BackendException {
store.mutate(key, additions, deletions, unwrapTx(txh));
}
@Override
public EntryList getSlice(KeySliceQuery query, StoreTransaction txh) throws BackendException {
return store.getSlice(query, unwrapTx(txh));
}
@Override
public Map<StaticBuffer,EntryList> getSlice(List<StaticBuffer> keys, SliceQuery query, StoreTransaction txh) throws BackendException {
return store.getSlice(keys, query, unwrapTx(txh));
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_KCVSProxy.java |
3,048 | public class DirectPostingsFormatProvider extends AbstractPostingsFormatProvider {
private final int minSkipCount;
private final int lowFreqCutoff;
private final DirectPostingsFormat postingsFormat;
@Inject
public DirectPostingsFormatProvider(@Assisted String name, @Assisted Settings postingsFormatSettings) {
super(name);
this.minSkipCount = postingsFormatSettings.getAsInt("min_skip_count", 8); // See DirectPostingsFormat#DEFAULT_MIN_SKIP_COUNT
this.lowFreqCutoff = postingsFormatSettings.getAsInt("low_freq_cutoff", 32); // See DirectPostingsFormat#DEFAULT_LOW_FREQ_CUTOFF
this.postingsFormat = new DirectPostingsFormat(minSkipCount, lowFreqCutoff);
}
public int minSkipCount() {
return minSkipCount;
}
public int lowFreqCutoff() {
return lowFreqCutoff;
}
@Override
public PostingsFormat get() {
return postingsFormat;
}
} | 0true
| src_main_java_org_elasticsearch_index_codec_postingsformat_DirectPostingsFormatProvider.java |
1,424 | public class OChannelBinaryOutputStream extends OutputStream {
private OChannelBinaryAsynchClient channel;
private final byte[] buffer;
private int pos = 0;
public OChannelBinaryOutputStream(final OChannelBinaryAsynchClient channel) {
this.channel = channel;
buffer = channel.getBuffer();
}
@Override
public void write(final int iByte) throws IOException {
if (pos >= buffer.length)
flush(true);
buffer[pos++] = (byte) iByte;
}
@Override
public void close() throws IOException {
flush(false);
channel = null;
}
@Override
public void flush() throws IOException {
// flush(true);
}
private void flush(final boolean iContinue) throws IOException {
channel.beginRequest();
try {
channel.out.writeInt(pos);
if (pos > 0) {
channel.out.write(buffer, 0, pos);
pos = 0;
}
channel.out.writeByte(iContinue ? 1 : 0);
} finally {
channel.endRequest();
}
}
} | 0true
| enterprise_src_main_java_com_orientechnologies_orient_enterprise_channel_binary_OChannelBinaryOutputStream.java |
500 | private static class SetRewriter implements FieldRewriter<Set<?>> {
@Override
public Set<?> rewriteValue(Set<?> setValue) {
boolean wasRewritten = false;
Set<Object> result = new HashSet<Object>();
for (Object item : setValue) {
FieldRewriter<Object> fieldRewriter = RewritersFactory.INSTANCE.findRewriter(null, null, item);
Object newItem = fieldRewriter.rewriteValue(item);
if (newItem != null) {
wasRewritten = true;
result.add(newItem);
} else
result.add(item);
}
if (wasRewritten)
return result;
return null;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseImport.java |
1,512 | public class IndexBalanceTests extends ElasticsearchAllocationTestCase {
private final ESLogger logger = Loggers.getLogger(IndexBalanceTests.class);
@Test
public void testBalanceAllNodesStarted() {
AllocationService strategy = createAllocationService(settingsBuilder()
.put("cluster.routing.allocation.node_concurrent_recoveries", 10)
.put("cluster.routing.allocation.node_initial_primaries_recoveries", 10)
.put("cluster.routing.allocation.allow_rebalance", "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1).build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder().put(IndexMetaData.builder("test").numberOfShards(3).numberOfReplicas(1))
.put(IndexMetaData.builder("test1").numberOfShards(3).numberOfReplicas(1)).build();
RoutingTable routingTable = RoutingTable.builder().addAsNew(metaData.index("test")).addAsNew(metaData.index("test1")).build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).shards().get(1).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).shards().get(0).currentNodeId(), nullValue());
assertThat(routingTable.index("test").shard(i).shards().get(1).currentNodeId(), nullValue());
}
assertThat(routingTable.index("test1").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test1").shards().size(); i++) {
assertThat(routingTable.index("test1").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).shards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test1").shard(i).shards().get(1).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test1").shard(i).shards().get(0).currentNodeId(), nullValue());
assertThat(routingTable.index("test1").shard(i).shards().get(1).currentNodeId(), nullValue());
}
logger.info("Adding three node and performing rerouting");
clusterState = ClusterState.builder(clusterState)
.nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3"))).build();
RoutingTable prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), nullValue());
}
logger.info("Another round of rebalancing");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable == routingTable, equalTo(true));
RoutingNodes routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
// backup shards are initializing as well, we make sure that they
// recover from primary *started* shards in the
// IndicesClusterStateService
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING));
}
logger.info("Reroute, nothing should change");
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Start the more shards");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(STARTED));
}
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test1").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test1").shards().size(); i++) {
assertThat(routingTable.index("test1").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test1").shard(i).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).state(), equalTo(STARTED));
}
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node1").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node2").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node3").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node1").shardsWithState("test1", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node2").shardsWithState("test1", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node3").shardsWithState("test1", STARTED).size(), equalTo(2));
}
@Test
public void testBalanceIncrementallyStartNodes() {
AllocationService strategy = createAllocationService(settingsBuilder()
.put("cluster.routing.allocation.node_concurrent_recoveries", 10)
.put("cluster.routing.allocation.node_initial_primaries_recoveries", 10)
.put("cluster.routing.allocation.allow_rebalance", "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1).build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder().put(IndexMetaData.builder("test").numberOfShards(3).numberOfReplicas(1))
.put(IndexMetaData.builder("test1").numberOfShards(3).numberOfReplicas(1)).build();
RoutingTable routingTable = RoutingTable.builder().addAsNew(metaData.index("test")).addAsNew(metaData.index("test1")).build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).shards().get(1).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).shards().get(0).currentNodeId(), nullValue());
assertThat(routingTable.index("test").shard(i).shards().get(1).currentNodeId(), nullValue());
}
assertThat(routingTable.index("test1").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test1").shards().size(); i++) {
assertThat(routingTable.index("test1").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).shards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test1").shard(i).shards().get(1).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test1").shard(i).shards().get(0).currentNodeId(), nullValue());
assertThat(routingTable.index("test1").shard(i).shards().get(1).currentNodeId(), nullValue());
}
logger.info("Adding one node and performing rerouting");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1"))).build();
RoutingTable prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), nullValue());
}
logger.info("Add another node and perform rerouting, nothing will happen since primary not started");
clusterState = ClusterState.builder(clusterState)
.nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node2"))).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Start the primary shard");
RoutingNodes routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
// backup shards are initializing as well, we make sure that they
// recover from primary *started* shards in the
// IndicesClusterStateService
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING));
}
logger.info("Reroute, nothing should change");
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Start the backup shard");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(STARTED));
}
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test1").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test1").shards().size(); i++) {
assertThat(routingTable.index("test1").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test1").shard(i).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).state(), equalTo(STARTED));
}
logger.info("Add another node and perform rerouting, nothing will happen since primary not started");
clusterState = ClusterState.builder(clusterState)
.nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node3"))).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
logger.info("Reroute, nothing should change");
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Start the backup shard");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(3));
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test1").shards().size(), equalTo(3));
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node1").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node2").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node3").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node1").shardsWithState("test1", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node2").shardsWithState("test1", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node3").shardsWithState("test1", STARTED).size(), equalTo(2));
}
@Test
public void testBalanceAllNodesStartedAddIndex() {
AllocationService strategy = createAllocationService(settingsBuilder()
.put("cluster.routing.allocation.node_concurrent_recoveries", 10)
.put("cluster.routing.allocation.node_initial_primaries_recoveries", 10)
.put("cluster.routing.allocation.allow_rebalance", "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1).build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder().put(IndexMetaData.builder("test").numberOfShards(3).numberOfReplicas(1)).build();
RoutingTable routingTable = RoutingTable.builder().addAsNew(metaData.index("test")).build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).shards().get(1).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).shards().get(0).currentNodeId(), nullValue());
assertThat(routingTable.index("test").shard(i).shards().get(1).currentNodeId(), nullValue());
}
logger.info("Adding three node and performing rerouting");
clusterState = ClusterState.builder(clusterState)
.nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3"))).build();
RoutingTable prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), nullValue());
}
logger.info("Another round of rebalancing");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable == routingTable, equalTo(true));
RoutingNodes routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
// backup shards are initializing as well, we make sure that they
// recover from primary *started* shards in the
// IndicesClusterStateService
assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING));
}
logger.info("Reroute, nothing should change");
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Start the more shards");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test").shards().size(); i++) {
assertThat(routingTable.index("test").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1));
}
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(2));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(2));
assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(2));
assertThat(routingNodes.node("node1").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node2").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node3").shardsWithState("test", STARTED).size(), equalTo(2));
logger.info("Add new index 3 shards 1 replica");
prevRoutingTable = routingTable;
metaData = MetaData.builder(metaData)
.put(IndexMetaData.builder("test1").settings(ImmutableSettings.settingsBuilder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 3)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
))
.build();
routingTable = RoutingTable.builder(routingTable)
.addAsNew(metaData.index("test1"))
.build();
clusterState = ClusterState.builder(clusterState).metaData(metaData).routingTable(routingTable).build();
assertThat(routingTable.index("test1").shards().size(), equalTo(3));
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test1").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test1").shards().size(); i++) {
assertThat(routingTable.index("test1").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test1").shard(i).replicaShards().size(), equalTo(1));
assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).currentNodeId(), nullValue());
}
logger.info("Another round of rebalancing");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable == routingTable, equalTo(true));
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test1").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test1").shards().size(); i++) {
assertThat(routingTable.index("test1").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test1").shard(i).replicaShards().size(), equalTo(1));
// backup shards are initializing as well, we make sure that they
// recover from primary *started* shards in the
// IndicesClusterStateService
assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING));
}
logger.info("Reroute, nothing should change");
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Start the more shards");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test1").shards().size(), equalTo(3));
for (int i = 0; i < routingTable.index("test1").shards().size(); i++) {
assertThat(routingTable.index("test1").shard(i).size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test1").shard(i).replicaShards().size(), equalTo(1));
}
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node1").shardsWithState("test1", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node2").shardsWithState("test1", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node3").shardsWithState("test1", STARTED).size(), equalTo(2));
}
} | 0true
| src_test_java_org_elasticsearch_cluster_routing_allocation_IndexBalanceTests.java |
2,720 | public static class AllocateDangledResponse extends TransportResponse {
private boolean ack;
AllocateDangledResponse() {
}
AllocateDangledResponse(boolean ack) {
this.ack = ack;
}
public boolean ack() {
return ack;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
ack = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(ack);
}
} | 0true
| src_main_java_org_elasticsearch_gateway_local_state_meta_LocalAllocateDangledIndices.java |
3,118 | public class SegmentsStats implements Streamable, ToXContent {
private long count;
private long memoryInBytes;
public SegmentsStats() {
}
public void add(long count, long memoryInBytes) {
this.count += count;
this.memoryInBytes += memoryInBytes;
}
public void add(SegmentsStats mergeStats) {
if (mergeStats == null) {
return;
}
this.count += mergeStats.count;
this.memoryInBytes += mergeStats.memoryInBytes;
}
/**
* The the segments count.
*/
public long getCount() {
return this.count;
}
/**
* Estimation of the memory usage used by a segment.
*/
public long getMemoryInBytes() {
return this.memoryInBytes;
}
public ByteSizeValue getMemory() {
return new ByteSizeValue(memoryInBytes);
}
public static SegmentsStats readSegmentsStats(StreamInput in) throws IOException {
SegmentsStats stats = new SegmentsStats();
stats.readFrom(in);
return stats;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.SEGMENTS);
builder.field(Fields.COUNT, count);
builder.byteSizeField(Fields.MEMORY_IN_BYTES, Fields.MEMORY, memoryInBytes);
builder.endObject();
return builder;
}
static final class Fields {
static final XContentBuilderString SEGMENTS = new XContentBuilderString("segments");
static final XContentBuilderString COUNT = new XContentBuilderString("count");
static final XContentBuilderString MEMORY = new XContentBuilderString("memory");
static final XContentBuilderString MEMORY_IN_BYTES = new XContentBuilderString("memory_in_bytes");
}
@Override
public void readFrom(StreamInput in) throws IOException {
count = in.readVLong();
memoryInBytes = in.readLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(count);
out.writeLong(memoryInBytes);
}
} | 1no label
| src_main_java_org_elasticsearch_index_engine_SegmentsStats.java |
18 | public class CompletionUtil {
public static List<Declaration> overloads(Declaration dec) {
if (dec instanceof Functional && ((Functional) dec).isAbstraction()) {
return ((Functional) dec).getOverloads();
}
else {
return Collections.singletonList(dec);
}
}
static List<Parameter> getParameters(ParameterList pl,
boolean includeDefaults, boolean namedInvocation) {
List<Parameter> ps = pl.getParameters();
if (includeDefaults) {
return ps;
}
else {
List<Parameter> list = new ArrayList<Parameter>();
for (Parameter p: ps) {
if (!p.isDefaulted() ||
(namedInvocation &&
p==ps.get(ps.size()-1) &&
p.getModel() instanceof Value &&
p.getType()!=null &&
p.getDeclaration().getUnit()
.isIterableParameterType(p.getType()))) {
list.add(p);
}
}
return list;
}
}
static String fullPath(int offset, String prefix,
Tree.ImportPath path) {
StringBuilder fullPath = new StringBuilder();
if (path!=null) {
fullPath.append(Util.formatPath(path.getIdentifiers()));
fullPath.append('.');
fullPath.setLength(offset-path.getStartIndex()-prefix.length());
}
return fullPath.toString();
}
static boolean isPackageDescriptor(CeylonParseController cpc) {
return cpc.getRootNode() != null &&
cpc.getRootNode().getUnit() != null &&
cpc.getRootNode().getUnit().getFilename().equals("package.ceylon");
}
static boolean isModuleDescriptor(CeylonParseController cpc) {
return cpc.getRootNode() != null &&
cpc.getRootNode().getUnit() != null &&
cpc.getRootNode().getUnit().getFilename().equals("module.ceylon");
}
static boolean isEmptyModuleDescriptor(CeylonParseController cpc) {
return isModuleDescriptor(cpc) &&
cpc.getRootNode() != null &&
cpc.getRootNode().getModuleDescriptors().isEmpty();
}
static boolean isEmptyPackageDescriptor(CeylonParseController cpc) {
return cpc.getRootNode() != null &&
cpc.getRootNode().getUnit() != null &&
cpc.getRootNode().getUnit().getFilename().equals("package.ceylon") &&
cpc.getRootNode().getPackageDescriptors().isEmpty();
}
public static OccurrenceLocation getOccurrenceLocation(Tree.CompilationUnit cu,
Node node, int offset) {
FindOccurrenceLocationVisitor visitor =
new FindOccurrenceLocationVisitor(offset, node);
cu.visit(visitor);
return visitor.getOccurrenceLocation();
}
static int nextTokenType(final CeylonParseController cpc,
final CommonToken token) {
for (int i=token.getTokenIndex()+1; i<cpc.getTokens().size(); i++) {
CommonToken tok = cpc.getTokens().get(i);
if (tok.getChannel()!=CommonToken.HIDDEN_CHANNEL) {
return tok.getType();
}
}
return -1;
}
/**
* BaseMemberExpressions in Annotations have funny lying
* scopes, but we can extract the real scope out of the
* identifier! (Yick)
*/
static Scope getRealScope(final Node node, CompilationUnit cu) {
class FindScopeVisitor extends Visitor {
Scope scope;
public void visit(Tree.Declaration that) {
super.visit(that);
AnnotationList al = that.getAnnotationList();
if (al!=null) {
for (Tree.Annotation a: al.getAnnotations()) {
Integer i = a.getPrimary().getStartIndex();
Integer j = node.getStartIndex();
if (i.intValue()==j.intValue()) {
scope = that.getDeclarationModel().getScope();
}
}
}
}
public void visit(Tree.DocLink that) {
super.visit(that);
scope = ((Tree.DocLink)node).getPkg();
}
};
FindScopeVisitor fsv = new FindScopeVisitor();
fsv.visit(cu);
return fsv.scope==null ? node.getScope() : fsv.scope;
}
static int getLine(final int offset, ITextViewer viewer) {
int line=-1;
try {
line = viewer.getDocument().getLineOfOffset(offset);
}
catch (BadLocationException e) {
e.printStackTrace();
}
return line;
}
public static boolean isInBounds(List<ProducedType> upperBounds, ProducedType t) {
boolean ok = true;
for (ProducedType ub: upperBounds) {
if (!t.isSubtypeOf(ub) &&
!(ub.containsTypeParameters() &&
t.getDeclaration().inherits(ub.getDeclaration()))) {
ok = false;
break;
}
}
return ok;
}
public static List<DeclarationWithProximity> getSortedProposedValues(Scope scope, Unit unit) {
List<DeclarationWithProximity> results = new ArrayList<DeclarationWithProximity>(
scope.getMatchingDeclarations(unit, "", 0).values());
Collections.sort(results, new Comparator<DeclarationWithProximity>() {
public int compare(DeclarationWithProximity x, DeclarationWithProximity y) {
if (x.getProximity()<y.getProximity()) return -1;
if (x.getProximity()>y.getProximity()) return 1;
int c = x.getDeclaration().getName().compareTo(y.getDeclaration().getName());
if (c!=0) return c;
return x.getDeclaration().getQualifiedNameString()
.compareTo(y.getDeclaration().getQualifiedNameString());
}
});
return results;
}
public static boolean isIgnoredLanguageModuleClass(Class clazz) {
String name = clazz.getName();
return name.equals("String") ||
name.equals("Integer") ||
name.equals("Float") ||
name.equals("Character") ||
clazz.isAnnotation();
}
public static boolean isIgnoredLanguageModuleValue(Value value) {
String name = value.getName();
return name.equals("process") ||
name.equals("runtime") ||
name.equals("system") ||
name.equals("operatingSystem") ||
name.equals("language") ||
name.equals("emptyIterator") ||
name.equals("infinity") ||
name.endsWith("IntegerValue") ||
name.equals("finished");
}
public static boolean isIgnoredLanguageModuleMethod(Method method) {
String name = method.getName();
return name.equals("className") ||
name.equals("flatten") ||
name.equals("unflatten")||
name.equals("curry") ||
name.equals("uncurry") ||
name.equals("compose") ||
method.isAnnotation();
}
static boolean isIgnoredLanguageModuleType(TypeDeclaration td) {
String name = td.getName();
return !name.equals("Object") &&
!name.equals("Anything") &&
!name.equals("String") &&
!name.equals("Integer") &&
!name.equals("Character") &&
!name.equals("Float") &&
!name.equals("Boolean");
}
public static String getInitialValueDescription(final Declaration dec, CeylonParseController cpc) {
Node refnode = Nodes.getReferencedNode(dec, cpc);
Tree.SpecifierOrInitializerExpression sie = null;
String arrow = null;
if (refnode instanceof Tree.AttributeDeclaration) {
sie = ((Tree.AttributeDeclaration) refnode).getSpecifierOrInitializerExpression();
arrow = " = ";
}
else if (refnode instanceof Tree.MethodDeclaration) {
sie = ((Tree.MethodDeclaration) refnode).getSpecifierExpression();
arrow = " => ";
}
if (sie==null) {
class FindInitializerVisitor extends Visitor {
Tree.SpecifierOrInitializerExpression result;
@Override
public void visit(Tree.InitializerParameter that) {
super.visit(that);
Declaration d = that.getParameterModel().getModel();
if (d!=null && d.equals(dec)) {
result = that.getSpecifierExpression();
}
}
}
FindInitializerVisitor fiv = new FindInitializerVisitor();
fiv.visit(cpc.getRootNode());
sie = fiv.result;
}
if (sie!=null) {
if (sie.getExpression()!=null) {
Tree.Term term = sie.getExpression().getTerm();
if (term.getUnit().equals(cpc.getRootNode().getUnit())) {
return arrow + Nodes.toString(term, cpc.getTokens());
}
else if (term instanceof Tree.Literal) {
return arrow + term.getToken().getText();
}
else if (term instanceof Tree.BaseMemberOrTypeExpression) {
Tree.BaseMemberOrTypeExpression bme =
(Tree.BaseMemberOrTypeExpression) term;
if (bme.getIdentifier()!=null && bme.getTypeArguments()==null) {
return arrow + bme.getIdentifier().getText();
}
}
//don't have the token stream :-/
//TODO: figure out where to get it from!
return arrow + "...";
}
}
return "";
}
public static String getDefaultValueDescription(Parameter p,
CeylonParseController cpc) {
if (p.isDefaulted()) {
if (p.getModel() instanceof Functional) {
return " => ...";
}
else {
return getInitialValueDescription(p.getModel(), cpc);
}
}
else {
return "";
}
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CompletionUtil.java |
193 | public class TruncateTokenFilter extends TokenFilter {
private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);
private final int size;
public TruncateTokenFilter(TokenStream in, int size) {
super(in);
this.size = size;
}
@Override
public final boolean incrementToken() throws IOException {
if (input.incrementToken()) {
final int length = termAttribute.length();
if (length > size) {
termAttribute.setLength(size);
}
return true;
} else {
return false;
}
}
} | 0true
| src_main_java_org_apache_lucene_analysis_miscellaneous_TruncateTokenFilter.java |
834 | EMBEDDED("Embedded", 9, new Class<?>[] { Object.class }, new Class<?>[] { OSerializableStream.class }) {
}, | 0true
| core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OType.java |
1,440 | public class LocalRegionCache implements RegionCache {
protected final ITopic<Object> topic;
protected final MessageListener<Object> messageListener;
protected final ConcurrentMap<Object, Value> cache;
protected final Comparator versionComparator;
protected MapConfig config;
public LocalRegionCache(final String name, final HazelcastInstance hazelcastInstance,
final CacheDataDescription metadata) {
try {
config = hazelcastInstance != null ? hazelcastInstance.getConfig().findMapConfig(name) : null;
} catch (UnsupportedOperationException ignored) {
}
versionComparator = metadata != null && metadata.isVersioned() ? metadata.getVersionComparator() : null;
cache = new ConcurrentHashMap<Object, Value>();
messageListener = createMessageListener();
if (hazelcastInstance != null) {
topic = hazelcastInstance.getTopic(name);
topic.addMessageListener(messageListener);
} else {
topic = null;
}
}
public Object get(final Object key) {
final Value value = cache.get(key);
return value != null ? value.getValue() : null;
}
public boolean put(final Object key, final Object value, final Object currentVersion) {
final Value newValue = new Value(currentVersion, value, null, Clock.currentTimeMillis());
cache.put(key, newValue);
return true;
}
public boolean update(final Object key, final Object value, final Object currentVersion,
final Object previousVersion, final SoftLock lock) {
if (lock == LOCK_FAILURE) {
return false;
}
final Value currentValue = cache.get(key);
if (lock == LOCK_SUCCESS) {
if (currentValue != null && currentVersion != null
&& versionComparator.compare(currentVersion, currentValue.getVersion()) < 0) {
return false;
}
}
if (topic != null) {
topic.publish(createMessage(key, value, currentVersion));
}
cache.put(key, new Value(currentVersion, value, lock, Clock.currentTimeMillis()));
return true;
}
protected Object createMessage(final Object key, Object value, final Object currentVersion) {
return new Invalidation(key, currentVersion);
}
protected MessageListener<Object> createMessageListener() {
return new MessageListener<Object>() {
public void onMessage(final Message<Object> message) {
final Invalidation invalidation = (Invalidation) message.getMessageObject();
if (versionComparator != null) {
final Value value = cache.get(invalidation.getKey());
if (value != null) {
Object currentVersion = value.getVersion();
Object newVersion = invalidation.getVersion();
if (versionComparator.compare(newVersion, currentVersion) > 0) {
cache.remove(invalidation.getKey(), value);
}
}
} else {
cache.remove(invalidation.getKey());
}
}
};
}
public boolean remove(final Object key) {
final Value value = cache.remove(key);
if (value != null) {
if (topic != null) {
topic.publish(createMessage(key, null, value.getVersion()));
}
return true;
}
return false;
}
public SoftLock tryLock(final Object key, final Object version) {
final Value value = cache.get(key);
if (value == null) {
if (cache.putIfAbsent(key, new Value(version, null, LOCK_SUCCESS, Clock.currentTimeMillis())) == null) {
return LOCK_SUCCESS;
} else {
return LOCK_FAILURE;
}
} else {
if (version == null || versionComparator.compare(version, value.getVersion()) >= 0) {
if (cache.replace(key, value, value.createLockedValue(LOCK_SUCCESS))) {
return LOCK_SUCCESS;
} else {
return LOCK_FAILURE;
}
} else {
return LOCK_FAILURE;
}
}
}
public void unlock(final Object key, SoftLock lock) {
final Value value = cache.get(key);
if (value != null) {
final SoftLock currentLock = value.getLock();
if (currentLock == lock) {
cache.replace(key, value, value.createUnlockedValue());
}
}
}
public boolean contains(final Object key) {
return cache.containsKey(key);
}
public void clear() {
cache.clear();
}
public long size() {
return cache.size();
}
public long getSizeInMemory() {
return 0;
}
public Map asMap() {
return cache;
}
void cleanup() {
final int maxSize;
final long timeToLive;
if (config != null) {
maxSize = config.getMaxSizeConfig().getSize();
timeToLive = config.getTimeToLiveSeconds() * 1000L;
} else {
maxSize = 100000;
timeToLive = CacheEnvironment.getDefaultCacheTimeoutInMillis();
}
if ((maxSize > 0 && maxSize != Integer.MAX_VALUE) || timeToLive > 0) {
final Iterator<Entry<Object, Value>> iter = cache.entrySet().iterator();
SortedSet<EvictionEntry> entries = null;
final long now = Clock.currentTimeMillis();
while (iter.hasNext()) {
final Entry<Object, Value> e = iter.next();
final Object k = e.getKey();
final Value v = e.getValue();
if (v.getLock() == LOCK_SUCCESS) {
continue;
}
if (v.getCreationTime() + timeToLive < now) {
iter.remove();
} else if (maxSize > 0 && maxSize != Integer.MAX_VALUE) {
if (entries == null) {
entries = new TreeSet<EvictionEntry>();
}
entries.add(new EvictionEntry(k, v));
}
}
final int diff = cache.size() - maxSize;
final int k = diff >= 0 ? (diff + maxSize * 20 / 100) : 0;
if (k > 0 && entries != null) {
int i = 0;
for (EvictionEntry entry : entries) {
if (cache.remove(entry.key, entry.value)) {
if (++i == k) {
break;
}
}
}
}
}
}
static private class EvictionEntry implements Comparable<EvictionEntry> {
final Object key;
final Value value;
private EvictionEntry(final Object key, final Value value) {
this.key = key;
this.value = value;
}
public int compareTo(final EvictionEntry o) {
final long thisVal = this.value.getCreationTime();
final long anotherVal = o.value.getCreationTime();
return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EvictionEntry that = (EvictionEntry) o;
if (key != null ? !key.equals(that.key) : that.key != null) return false;
if (value != null ? !value.equals(that.value) : that.value != null) return false;
return true;
}
@Override
public int hashCode() {
return key != null ? key.hashCode() : 0;
}
}
private static final SoftLock LOCK_SUCCESS = new SoftLock() {
@Override
public String toString() {
return "Lock::Success";
}
};
private static final SoftLock LOCK_FAILURE = new SoftLock() {
@Override
public String toString() {
return "Lock::Failure";
}
};
} | 0true
| hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_local_LocalRegionCache.java |
1,074 | @Service("blFulfillmentGroupService")
public class FulfillmentGroupServiceImpl implements FulfillmentGroupService {
@Resource(name="blFulfillmentGroupDao")
protected FulfillmentGroupDao fulfillmentGroupDao;
@Resource(name = "blFulfillmentGroupItemDao")
protected FulfillmentGroupItemDao fulfillmentGroupItemDao;
@Resource(name = "blOrderService")
protected OrderService orderService;
@Resource(name = "blOrderMultishipOptionService")
protected OrderMultishipOptionService orderMultishipOptionService;
@Override
@Transactional("blTransactionManager")
public FulfillmentGroup save(FulfillmentGroup fulfillmentGroup) {
if (fulfillmentGroup.getSequence() == null) {
fulfillmentGroup.setSequence(
fulfillmentGroupDao.readNextFulfillmentGroupSequnceForOrder(
fulfillmentGroup.getOrder()));
}
return fulfillmentGroupDao.save(fulfillmentGroup);
}
@Override
public FulfillmentGroup createEmptyFulfillmentGroup() {
return fulfillmentGroupDao.create();
}
@Override
public FulfillmentGroup findFulfillmentGroupById(Long fulfillmentGroupId) {
return fulfillmentGroupDao.readFulfillmentGroupById(fulfillmentGroupId);
}
@Override
@Transactional("blTransactionManager")
public void delete(FulfillmentGroup fulfillmentGroup) {
fulfillmentGroupDao.delete(fulfillmentGroup);
}
@Override
@Transactional("blTransactionManager")
public FulfillmentGroup addFulfillmentGroupToOrder(FulfillmentGroupRequest fulfillmentGroupRequest, boolean priceOrder) throws PricingException {
FulfillmentGroup fg = fulfillmentGroupDao.create();
fg.setAddress(fulfillmentGroupRequest.getAddress());
fg.setOrder(fulfillmentGroupRequest.getOrder());
fg.setPhone(fulfillmentGroupRequest.getPhone());
fg.setFulfillmentOption(fulfillmentGroupRequest.getOption());
for (int i = 0; i < fulfillmentGroupRequest.getFulfillmentGroupItemRequests().size(); i++) {
FulfillmentGroupItemRequest request = fulfillmentGroupRequest.getFulfillmentGroupItemRequests().get(i);
request.setFulfillmentGroup(fg);
request.setOrder(fulfillmentGroupRequest.getOrder());
boolean shouldPriceOrder = (priceOrder && (i == (fulfillmentGroupRequest.getFulfillmentGroupItemRequests().size() - 1)));
fg = addItemToFulfillmentGroup(request, shouldPriceOrder);
}
return fg;
}
@Override
@Transactional("blTransactionManager")
public FulfillmentGroup addItemToFulfillmentGroup(FulfillmentGroupItemRequest fulfillmentGroupItemRequest, boolean priceOrder) throws PricingException {
Order order = fulfillmentGroupItemRequest.getOrder();
OrderItem item = fulfillmentGroupItemRequest.getOrderItem();
FulfillmentGroup fulfillmentGroup = fulfillmentGroupItemRequest.getFulfillmentGroup();
if (order == null) {
if (item.getOrder() != null) {
order = item.getOrder();
} else {
throw new IllegalArgumentException("Order must not be null");
}
}
// 1) Find the order item's existing fulfillment group, if any
for (FulfillmentGroup fg : order.getFulfillmentGroups()) {
Iterator<FulfillmentGroupItem> itr = fg.getFulfillmentGroupItems().iterator();
while (itr.hasNext()) {
FulfillmentGroupItem fgItem = itr.next();
if (fgItem.getOrderItem().equals(item)) {
// 2) remove item from it's existing fulfillment group
itr.remove();
fulfillmentGroupItemDao.delete(fgItem);
}
}
}
if (fulfillmentGroup == null || fulfillmentGroup.getId() == null) {
// API user is trying to add an item to a fulfillment group not created
fulfillmentGroup = fulfillmentGroupDao.create();
FulfillmentGroupRequest fgRequest = new FulfillmentGroupRequest();
fgRequest.setOrder(order);
fulfillmentGroup = addFulfillmentGroupToOrder(fgRequest, false);
fulfillmentGroup = save(fulfillmentGroup);
order.getFulfillmentGroups().add(fulfillmentGroup);
}
FulfillmentGroupItem fgi = createFulfillmentGroupItemFromOrderItem(item, fulfillmentGroup, fulfillmentGroupItemRequest.getQuantity());
fgi = fulfillmentGroupItemDao.save(fgi);
// 3) add the item to the new fulfillment group
fulfillmentGroup.addFulfillmentGroupItem(fgi);
order = orderService.save(order, priceOrder);
return fulfillmentGroup;
}
@Override
@Transactional("blTransactionManager")
public void removeOrderItemFromFullfillmentGroups(Order order, OrderItem orderItem) {
List<FulfillmentGroup> fulfillmentGroups = order.getFulfillmentGroups();
for (FulfillmentGroup fulfillmentGroup : fulfillmentGroups) {
Iterator<FulfillmentGroupItem> itr = fulfillmentGroup.getFulfillmentGroupItems().iterator();
while (itr.hasNext()) {
FulfillmentGroupItem fulfillmentGroupItem = itr.next();
if (fulfillmentGroupItem.getOrderItem().equals(orderItem)) {
itr.remove();
fulfillmentGroupItemDao.delete(fulfillmentGroupItem);
} else if (orderItem instanceof BundleOrderItem) {
BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItem;
for (DiscreteOrderItem discreteOrderItem : bundleOrderItem.getDiscreteOrderItems()) {
if (fulfillmentGroupItem.getOrderItem().equals(discreteOrderItem)){
itr.remove();
fulfillmentGroupItemDao.delete(fulfillmentGroupItem);
break;
}
}
}
}
}
}
@Override
@Transactional("blTransactionManager")
public Order collapseToOneFulfillmentGroup(Order order, boolean priceOrder) throws PricingException {
if (order.getFulfillmentGroups() == null || order.getFulfillmentGroups().size() < 2) {
return order;
}
// Get the default (first) fulfillment group to collapse the others into
ListIterator<FulfillmentGroup> fgIter = order.getFulfillmentGroups().listIterator();
FulfillmentGroup collapsedFg = fgIter.next();
// Build out a map representing the default fgs items keyed by OrderItem id
Map<Long, FulfillmentGroupItem> fgOrderItemMap = new HashMap<Long, FulfillmentGroupItem>();
for (FulfillmentGroupItem fgi : collapsedFg.getFulfillmentGroupItems()) {
fgOrderItemMap.put(fgi.getOrderItem().getId(), fgi);
}
// For all non default fgs, collapse the items into the default fg
while (fgIter.hasNext()) {
FulfillmentGroup fg = fgIter.next();
ListIterator<FulfillmentGroupItem> fgItemIter = fg.getFulfillmentGroupItems().listIterator();
while (fgItemIter.hasNext()) {
FulfillmentGroupItem fgi = fgItemIter.next();
Long orderItemId = fgi.getOrderItem().getId();
FulfillmentGroupItem matchingFgi = fgOrderItemMap.get(orderItemId);
if (matchingFgi == null) {
matchingFgi = fulfillmentGroupItemDao.create();
matchingFgi.setFulfillmentGroup(collapsedFg);
matchingFgi.setOrderItem(fgi.getOrderItem());
matchingFgi.setQuantity(fgi.getQuantity());
matchingFgi = fulfillmentGroupItemDao.save(matchingFgi);
collapsedFg.getFulfillmentGroupItems().add(matchingFgi);
fgOrderItemMap.put(orderItemId, matchingFgi);
} else {
matchingFgi.setQuantity(matchingFgi.getQuantity() + fgi.getQuantity());
}
fulfillmentGroupItemDao.delete(fgi);
fgItemIter.remove();
}
fulfillmentGroupDao.delete(fg);
fgIter.remove();
}
return orderService.save(order, priceOrder);
}
@Override
@Transactional("blTransactionManager")
public Order matchFulfillmentGroupsToMultishipOptions(Order order, boolean priceOrder) throws PricingException {
List<OrderMultishipOption> multishipOptions = orderMultishipOptionService.findOrderMultishipOptions(order.getId());
// Build map of fulfillmentGroupItemId --> FulfillmentGroupItem.quantity
// Also build map of addressId:fulfillmentOptionId --> FulfillmentGroup
Map<Long, Integer> fgItemQuantityMap = new HashMap<Long, Integer>();
Map<String, FulfillmentGroup> multishipGroups = new HashMap<String, FulfillmentGroup>();
for (FulfillmentGroup fg : order.getFulfillmentGroups()) {
String key = getKey(fg.getAddress(), fg.getFulfillmentOption());
multishipGroups.put(key, fg);
for (FulfillmentGroupItem fgi : fg.getFulfillmentGroupItems()) {
fgItemQuantityMap.put(fgi.getId(), fgi.getQuantity());
}
}
for (OrderMultishipOption option : multishipOptions) {
String key = getKey(option.getAddress(), option.getFulfillmentOption());
FulfillmentGroup fg = multishipGroups.get(key);
// Get or create a fulfillment group that matches this OrderMultishipOption destination
if (fg == null) {
FulfillmentGroupRequest fgr = new FulfillmentGroupRequest();
fgr.setOrder(order);
if (option.getAddress() != null) {
fgr.setAddress(option.getAddress());
}
if (option.getFulfillmentOption() != null) {
fgr.setOption(option.getFulfillmentOption());
}
fg = addFulfillmentGroupToOrder(fgr, false);
fg = save(fg);
order.getFulfillmentGroups().add(fg);
}
// See if there is a fulfillment group item that matches this OrderMultishipOption
// OrderItem request
FulfillmentGroupItem fulfillmentGroupItem = null;
for (FulfillmentGroupItem fgi : fg.getFulfillmentGroupItems()) {
if (fgi.getOrderItem().getId() == option.getOrderItem().getId()) {
fulfillmentGroupItem = fgi;
}
}
// If there is no matching fulfillment group item, create a new one with quantity 1
if (fulfillmentGroupItem == null) {
fulfillmentGroupItem = fulfillmentGroupItemDao.create();
fulfillmentGroupItem.setFulfillmentGroup(fg);
fulfillmentGroupItem.setOrderItem(option.getOrderItem());
fulfillmentGroupItem.setQuantity(1);
fulfillmentGroupItem = fulfillmentGroupItemDao.save(fulfillmentGroupItem);
fg.getFulfillmentGroupItems().add(fulfillmentGroupItem);
} else {
// There are three potential scenarios where a fulfillment group item exists:
// 1: It has been previously created and exists in the database and
// has an id. This means it's in the fgItemQuantityMap. If there is
// remaining quantity in that map, we will decrement it for future
// usage. If the quantity is 0 in the map, that means that we have more
// items than we did before, and we must simply increment the quantity.
// (qty == 0 or qty is not null)
// 2: It was created in this request but has been saved to the database because
// it is a brand new fulfillment group and so it has an id.
// However, it does not have an entry in the fgItemQuantityMap,
// so we can simply increment the quantity.
// (qty == null)
// 3: It was created in this request and has not yet been saved to the database.
// This is because it was a previously existing fulfillment group that has new
// items. Therefore, we simply increment the quantity.
// (fulfillmentGroupItem.getId() == null)
if (fulfillmentGroupItem.getId() != null) {
Integer qty = fgItemQuantityMap.get(fulfillmentGroupItem.getId());
if (qty == null || qty == 0) {
fulfillmentGroupItem.setQuantity(fulfillmentGroupItem.getQuantity() + 1);
} else {
qty -= 1;
fgItemQuantityMap.put(fulfillmentGroupItem.getId(), qty);
}
} else {
fulfillmentGroupItem.setQuantity(fulfillmentGroupItem.getQuantity() + 1);
}
}
multishipGroups.put(key, fg);
}
// Go through all of the items in the fgItemQuantityMap. For all items that have a
// zero quantity, we don't need to do anything because we've already matched them
// to the newly requested OrderMultishipOption. For items that have a non-zero quantity,
// there are two possible scenarios:
// 1: The quantity remaining matches exactly the quantity of a fulfillmentGroupItem.
// In this case, we can simply remove the fulfillmentGroupItem.
// 2: The quantity in the map is greater than what we've found. This means that we
// need to subtract the remaining old quantity from the new quantity.
// Furthermore, delete the empty fulfillment groups.
for (Entry<Long, Integer> entry : fgItemQuantityMap.entrySet()) {
if (entry.getValue() > 0) {
FulfillmentGroupItem fgi = fulfillmentGroupItemDao.readFulfillmentGroupItemById(entry.getKey());
if (fgi.getQuantity() == entry.getValue()) {
FulfillmentGroup fg = fgi.getFulfillmentGroup();
fg.getFulfillmentGroupItems().remove(fgi);
fulfillmentGroupItemDao.delete(fgi);
if (fg.getFulfillmentGroupItems().size() == 0) {
order.getFulfillmentGroups().remove(fg);
fulfillmentGroupDao.delete(fg);
}
} else {
fgi.setQuantity(fgi.getQuantity() - entry.getValue());
fulfillmentGroupItemDao.save(fgi);
}
}
}
return orderService.save(order, priceOrder);
}
protected String getKey(Address address, FulfillmentOption option) {
Long addressKey = (address == null) ? -1 : address.getId();
Long fulfillmentOptionKey = (option == null) ? -1 : option.getId();
return addressKey + ":" + fulfillmentOptionKey;
}
protected FulfillmentGroupItem createFulfillmentGroupItemFromOrderItem(OrderItem orderItem, FulfillmentGroup fulfillmentGroup, int quantity) {
FulfillmentGroupItem fgi = fulfillmentGroupItemDao.create();
fgi.setFulfillmentGroup(fulfillmentGroup);
fgi.setOrderItem(orderItem);
fgi.setQuantity(quantity);
return fgi;
}
@Override
@Transactional("blTransactionManager")
public Order removeAllFulfillmentGroupsFromOrder(Order order, boolean priceOrder) throws PricingException {
if (order.getFulfillmentGroups() != null) {
for (Iterator<FulfillmentGroup> iterator = order.getFulfillmentGroups().iterator(); iterator.hasNext();) {
FulfillmentGroup fulfillmentGroup = iterator.next();
iterator.remove();
fulfillmentGroupDao.delete(fulfillmentGroup);
}
order = orderService.save(order, priceOrder);
}
return order;
}
@Override
public FulfillmentGroupFee createFulfillmentGroupFee() {
return fulfillmentGroupDao.createFulfillmentGroupFee();
}
@Override
public List<FulfillmentGroup> findUnfulfilledFulfillmentGroups(int start,
int maxResults) {
return fulfillmentGroupDao.readUnfulfilledFulfillmentGroups(start, maxResults);
}
@Override
public List<FulfillmentGroup> findPartiallyFulfilledFulfillmentGroups(
int start, int maxResults) {
return fulfillmentGroupDao.readPartiallyFulfilledFulfillmentGroups(start, maxResults);
}
@Override
public List<FulfillmentGroup> findUnprocessedFulfillmentGroups(int start,
int maxResults) {
return fulfillmentGroupDao.readUnprocessedFulfillmentGroups(start, maxResults);
}
@Override
public List<FulfillmentGroup> findFulfillmentGroupsByStatus(
FulfillmentGroupStatusType status, int start, int maxResults,
boolean ascending) {
return fulfillmentGroupDao.readFulfillmentGroupsByStatus(status, start, maxResults, ascending);
}
@Override
public List<FulfillmentGroup> findFulfillmentGroupsByStatus(
FulfillmentGroupStatusType status, int start, int maxResults) {
return fulfillmentGroupDao.readFulfillmentGroupsByStatus(status, start, maxResults);
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_FulfillmentGroupServiceImpl.java |
440 | static final class Fields {
static final XContentBuilderString COUNT = new XContentBuilderString("count");
static final XContentBuilderString VERSIONS = new XContentBuilderString("versions");
static final XContentBuilderString OS = new XContentBuilderString("os");
static final XContentBuilderString PROCESS = new XContentBuilderString("process");
static final XContentBuilderString JVM = new XContentBuilderString("jvm");
static final XContentBuilderString FS = new XContentBuilderString("fs");
static final XContentBuilderString PLUGINS = new XContentBuilderString("plugins");
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsNodes.java |
338 | StaticBuffer result = BackendOperation.execute(new BackendOperation.Transactional<StaticBuffer>() {
@Override
public StaticBuffer call(StoreTransaction txh) throws BackendException {
List<Entry> entries = store.getSlice(query,txh);
if (entries.isEmpty()) return null;
return entries.get(0).getValueAs(StaticBuffer.STATIC_FACTORY);
}
@Override
public String toString() {
return "getConfiguration";
}
}, txProvider, times, maxOperationWaitTime); | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_backend_KCVSConfiguration.java |
393 | public class MediaDto implements Media {
private static final long serialVersionUID = 1L;
protected long id;
protected String url = "";
protected String title = "";
protected String altText = "";
protected String tags = "";
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getUrl() {
return url;
}
@Override
public void setUrl(String url) {
this.url = url;
}
@Override
public String getTitle() {
return title;
}
@Override
public void setTitle(String title) {
this.title = title;
}
@Override
public String getAltText() {
return altText;
}
@Override
public void setAltText(String altText) {
this.altText = altText;
}
@Override
public String getTags() {
return tags;
}
@Override
public void setTags(String tags) {
this.tags = tags;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_media_domain_MediaDto.java |
917 | public class IndicesOptions {
private static final IndicesOptions[] VALUES;
static {
byte max = 1 << 4;
VALUES = new IndicesOptions[max];
for (byte id = 0; id < max; id++) {
VALUES[id] = new IndicesOptions(id);
}
}
private final byte id;
private IndicesOptions(byte id) {
this.id = id;
}
/**
* @return Whether specified concrete indices should be ignored when unavailable (missing or closed)
*/
public boolean ignoreUnavailable() {
return (id & 1) != 0;
}
/**
* @return Whether to ignore if a wildcard indices expression resolves into no concrete indices.
* The `_all` string or when no indices have been specified also count as wildcard expressions.
*/
public boolean allowNoIndices() {
return (id & 2) != 0;
}
/**
* @return Whether wildcard indices expressions should expanded into open indices should be
*/
public boolean expandWildcardsOpen() {
return (id & 4) != 0;
}
/**
* @return Whether wildcard indices expressions should expanded into closed indices should be
*/
public boolean expandWildcardsClosed() {
return (id & 8) != 0;
}
public void writeIndicesOptions(StreamOutput out) throws IOException {
out.write(id);
}
public static IndicesOptions readIndicesOptions(StreamInput in) throws IOException {
byte id = in.readByte();
if (id >= VALUES.length) {
throw new ElasticsearchIllegalArgumentException("No valid missing index type id: " + id);
}
return VALUES[id];
}
public static IndicesOptions fromOptions(boolean ignoreUnavailable, boolean allowNoIndices, boolean expandToOpenIndices, boolean expandToClosedIndices) {
byte id = toByte(ignoreUnavailable, allowNoIndices, expandToOpenIndices, expandToClosedIndices);
return VALUES[id];
}
public static IndicesOptions fromRequest(RestRequest request, IndicesOptions defaultSettings) {
String sWildcards = request.param("expand_wildcards");
String sIgnoreUnavailable = request.param("ignore_unavailable");
String sAllowNoIndices = request.param("allow_no_indices");
if (sWildcards == null && sIgnoreUnavailable == null && sAllowNoIndices == null) {
return defaultSettings;
}
boolean expandWildcardsOpen = defaultSettings.expandWildcardsOpen();
boolean expandWildcardsClosed = defaultSettings.expandWildcardsClosed();
if (sWildcards != null) {
String[] wildcards = Strings.splitStringByCommaToArray(sWildcards);
for (String wildcard : wildcards) {
if ("open".equals(wildcard)) {
expandWildcardsOpen = true;
} else if ("closed".equals(wildcard)) {
expandWildcardsClosed = true;
} else {
throw new ElasticsearchIllegalArgumentException("No valid expand wildcard value [" + wildcard + "]");
}
}
}
return fromOptions(
toBool(sIgnoreUnavailable, defaultSettings.ignoreUnavailable()),
toBool(sAllowNoIndices, defaultSettings.allowNoIndices()),
expandWildcardsOpen,
expandWildcardsClosed
);
}
/**
* @return indices options that requires any specified index to exists, expands wildcards only to open indices and
* allow that no indices are resolved from wildcard expressions (not returning an error).
*/
public static IndicesOptions strict() {
return VALUES[6];
}
/**
* @return indices options that ignore unavailable indices, expand wildcards only to open indices and
* allow that no indices are resolved from wildcard expressions (not returning an error).
*/
public static IndicesOptions lenient() {
return VALUES[7];
}
private static byte toByte(boolean ignoreUnavailable, boolean allowNoIndices, boolean wildcardExpandToOpen, boolean wildcardExpandToClosed) {
byte id = 0;
if (ignoreUnavailable) {
id |= 1;
}
if (allowNoIndices) {
id |= 2;
}
if (wildcardExpandToOpen) {
id |= 4;
}
if (wildcardExpandToClosed) {
id |= 8;
}
return id;
}
private static boolean toBool(String sValue, boolean defaultValue) {
if (sValue == null) {
return defaultValue;
}
return !(sValue.equals("false") || sValue.equals("0") || sValue.equals("off"));
}
} | 1no label
| src_main_java_org_elasticsearch_action_support_IndicesOptions.java |
2,361 | BYTES {
@Override
public long toBytes(long size) {
return size;
}
@Override
public long toKB(long size) {
return size / (C1 / C0);
}
@Override
public long toMB(long size) {
return size / (C2 / C0);
}
@Override
public long toGB(long size) {
return size / (C3 / C0);
}
@Override
public long toTB(long size) {
return size / (C4 / C0);
}
@Override
public long toPB(long size) {
return size / (C5 / C0);
}
}, | 0true
| src_main_java_org_elasticsearch_common_unit_ByteSizeUnit.java |
400 | public class CreateSnapshotRequestBuilder extends MasterNodeOperationRequestBuilder<CreateSnapshotRequest, CreateSnapshotResponse, CreateSnapshotRequestBuilder> {
/**
* Constructs a new create snapshot request builder
*
* @param clusterAdminClient cluster admin client
*/
public CreateSnapshotRequestBuilder(ClusterAdminClient clusterAdminClient) {
super((InternalClusterAdminClient) clusterAdminClient, new CreateSnapshotRequest());
}
/**
* Constructs a new create snapshot request builder with specified repository and snapshot names
*
* @param clusterAdminClient cluster admin client
* @param repository repository name
* @param snapshot snapshot name
*/
public CreateSnapshotRequestBuilder(ClusterAdminClient clusterAdminClient, String repository, String snapshot) {
super((InternalClusterAdminClient) clusterAdminClient, new CreateSnapshotRequest(repository, snapshot));
}
/**
* Sets the snapshot name
*
* @param snapshot snapshot name
* @return this builder
*/
public CreateSnapshotRequestBuilder setSnapshot(String snapshot) {
request.snapshot(snapshot);
return this;
}
/**
* Sets the repository name
*
* @param repository repository name
* @return this builder
*/
public CreateSnapshotRequestBuilder setRepository(String repository) {
request.repository(repository);
return this;
}
/**
* Sets a list of indices that should be included into the snapshot
* <p/>
* The list of indices supports multi-index syntax. For example: "+test*" ,"-test42" will index all indices with
* prefix "test" except index "test42". Aliases are supported. An empty list or {"_all"} will snapshot all open
* indices in the cluster.
*
* @param indices
* @return this builder
*/
public CreateSnapshotRequestBuilder setIndices(String... indices) {
request.indices(indices);
return this;
}
/**
* Specifies the indices options. Like what type of requested indices to ignore. For example indices that don't exist.
*
* @param indicesOptions the desired behaviour regarding indices options
* @return this request
*/
public CreateSnapshotRequestBuilder setIndicesOptions(IndicesOptions indicesOptions) {
request.indicesOptions(indicesOptions);
return this;
}
/**
* If set to true the request should wait for the snapshot completion before returning.
*
* @param waitForCompletion true if
* @return this builder
*/
public CreateSnapshotRequestBuilder setWaitForCompletion(boolean waitForCompletion) {
request.waitForCompletion(waitForCompletion);
return this;
}
/**
* If set to true the request should snapshot indices with unavailable shards
*
* @param partial true if request should snapshot indices with unavailable shards
* @return this builder
*/
public CreateSnapshotRequestBuilder setPartial(boolean partial) {
request.partial(partial);
return this;
}
/**
* Sets repository-specific snapshot settings.
* <p/>
* See repository documentation for more information.
*
* @param settings repository-specific snapshot settings
* @return this builder
*/
public CreateSnapshotRequestBuilder setSettings(Settings settings) {
request.settings(settings);
return this;
}
/**
* Sets repository-specific snapshot settings.
* <p/>
* See repository documentation for more information.
*
* @param settings repository-specific snapshot settings
* @return this builder
*/
public CreateSnapshotRequestBuilder setSettings(Settings.Builder settings) {
request.settings(settings);
return this;
}
/**
* Sets repository-specific snapshot settings in YAML, JSON or properties format
* <p/>
* See repository documentation for more information.
*
* @param source repository-specific snapshot settings
* @return this builder
*/
public CreateSnapshotRequestBuilder setSettings(String source) {
request.settings(source);
return this;
}
/**
* Sets repository-specific snapshot settings.
* <p/>
* See repository documentation for more information.
*
* @param settings repository-specific snapshot settings
* @return this builder
*/
public CreateSnapshotRequestBuilder setSettings(Map<String, Object> settings) {
request.settings(settings);
return this;
}
/**
* Set to true if snapshot should include global cluster state
*
* @param includeGlobalState true if snapshot should include global cluster state
* @return this builder
*/
public CreateSnapshotRequestBuilder setIncludeGlobalState(boolean includeGlobalState) {
request.includeGlobalState(includeGlobalState);
return this;
}
@Override
protected void doExecute(ActionListener<CreateSnapshotResponse> listener) {
((ClusterAdminClient) client).createSnapshot(request, listener);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_snapshots_create_CreateSnapshotRequestBuilder.java |
578 | public interface ClusterService extends CoreService {
MemberImpl getMember(Address address);
MemberImpl getMember(String uuid);
Collection<MemberImpl> getMemberList();
Collection<Member> getMembers();
Address getMasterAddress();
boolean isMaster();
Address getThisAddress();
int getSize();
long getClusterTime();
} | 0true
| hazelcast_src_main_java_com_hazelcast_cluster_ClusterService.java |
1,023 | public abstract class OCommandExecutorSQLAbstract extends OCommandExecutorAbstract {
public static final String KEYWORD_FROM = "FROM";
public static final String KEYWORD_LET = "LET";
public static final String KEYWORD_WHERE = "WHERE";
public static final String KEYWORD_LIMIT = "LIMIT";
public static final String KEYWORD_SKIP = "SKIP";
public static final String KEYWORD_TIMEOUT = "TIMEOUT";
public static final String KEYWORD_KEY = "key";
public static final String KEYWORD_RID = "rid";
public static final String CLUSTER_PREFIX = "CLUSTER:";
public static final String CLASS_PREFIX = "CLASS:";
public static final String INDEX_PREFIX = "INDEX:";
public static final String DICTIONARY_PREFIX = "DICTIONARY:";
public static final String METADATA_PREFIX = "METADATA:";
public static final String METADATA_SCHEMA = "SCHEMA";
public static final String METADATA_INDEXMGR = "INDEXMANAGER";
protected long timeoutMs = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong();
protected TIMEOUT_STRATEGY timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION;
protected void throwSyntaxErrorException(final String iText) {
throw new OCommandSQLParsingException(iText + ". Use " + getSyntax(), parserText, parserGetPreviousPosition());
}
protected void throwParsingException(final String iText) {
throw new OCommandSQLParsingException(iText, parserText, parserGetPreviousPosition());
}
/**
* The command is replicated
*
* @return
*/
public boolean isReplicated() {
return true;
}
public boolean isIdempotent() {
return false;
}
/**
* Parses the timeout keyword if found.
*/
protected boolean parseTimeout(final String w) throws OCommandSQLParsingException {
if (!w.equals(KEYWORD_TIMEOUT))
return false;
parserNextWord(true);
String word = parserGetLastWord();
try {
timeoutMs = Long.parseLong(word);
} catch (Exception e) {
throwParsingException("Invalid " + KEYWORD_TIMEOUT + " value setted to '" + word
+ "' but it should be a valid long. Example: " + KEYWORD_TIMEOUT + " 3000");
}
if (timeoutMs < 0)
throwParsingException("Invalid " + KEYWORD_TIMEOUT + ": value setted to less than ZERO. Example: " + timeoutMs + " 10");
parserNextWord(true);
word = parserGetLastWord();
if (word.equals(TIMEOUT_STRATEGY.EXCEPTION.toString()))
timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION;
else if (word.equals(TIMEOUT_STRATEGY.RETURN.toString()))
timeoutStrategy = TIMEOUT_STRATEGY.RETURN;
else
parserGoBack();
return true;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLAbstract.java |
1,373 | public abstract class BaseEndpoint implements ApplicationContextAware, MessageSourceAware {
protected ApplicationContext context;
protected MessageSource messageSource;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_endpoint_BaseEndpoint.java |
340 | List<Entry> result = BackendOperation.execute(new BackendOperation.Transactional<List<Entry>>() {
@Override
public List<Entry> call(StoreTransaction txh) throws BackendException {
return store.getSlice(new KeySliceQuery(rowKey, BufferUtil.zeroBuffer(128), BufferUtil.oneBuffer(128)),txh);
}
@Override
public String toString() {
return "setConfiguration";
}
},txProvider, times, maxOperationWaitTime); | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_backend_KCVSConfiguration.java |
323 | public class OStorageMemoryClusterConfiguration extends OAbstractStorageClusterConfiguration {
public OStorageMemoryClusterConfiguration(final String name, final int id, final int iDataSegmentId) {
super(name, id, iDataSegmentId);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_config_OStorageMemoryClusterConfiguration.java |
832 | public static class DummyObject implements Serializable {
} | 0true
| hazelcast_src_test_java_com_hazelcast_concurrent_atomicreference_AtomicReferenceInstanceSharingTest.java |
3,933 | public class RangeQueryParser implements QueryParser {
public static final String NAME = "range";
@Inject
public RangeQueryParser() {
}
@Override
public String[] names() {
return new String[]{NAME};
}
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new QueryParsingException(parseContext.index(), "[range] query malformed, no field to indicate field name");
}
String fieldName = parser.currentName();
token = parser.nextToken();
if (token != XContentParser.Token.START_OBJECT) {
throw new QueryParsingException(parseContext.index(), "[range] query malformed, after field missing start object");
}
Object from = null;
Object to = null;
boolean includeLower = true;
boolean includeUpper = true;
float boost = 1.0f;
String queryName = null;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
if ("from".equals(currentFieldName)) {
from = parser.objectBytes();
} else if ("to".equals(currentFieldName)) {
to = parser.objectBytes();
} else if ("include_lower".equals(currentFieldName) || "includeLower".equals(currentFieldName)) {
includeLower = parser.booleanValue();
} else if ("include_upper".equals(currentFieldName) || "includeUpper".equals(currentFieldName)) {
includeUpper = parser.booleanValue();
} else if ("boost".equals(currentFieldName)) {
boost = parser.floatValue();
} else if ("gt".equals(currentFieldName)) {
from = parser.objectBytes();
includeLower = false;
} else if ("gte".equals(currentFieldName) || "ge".equals(currentFieldName)) {
from = parser.objectBytes();
includeLower = true;
} else if ("lt".equals(currentFieldName)) {
to = parser.objectBytes();
includeUpper = false;
} else if ("lte".equals(currentFieldName) || "le".equals(currentFieldName)) {
to = parser.objectBytes();
includeUpper = true;
} else if ("_name".equals(currentFieldName)) {
queryName = parser.text();
} else {
throw new QueryParsingException(parseContext.index(), "[range] query does not support [" + currentFieldName + "]");
}
}
}
// move to the next end object, to close the field name
token = parser.nextToken();
if (token != XContentParser.Token.END_OBJECT) {
throw new QueryParsingException(parseContext.index(), "[range] query malformed, does not end with an object");
}
Query query = null;
MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName);
if (smartNameFieldMappers != null) {
if (smartNameFieldMappers.hasMapper()) {
//LUCENE 4 UPGRADE Mapper#rangeQuery should use bytesref as well?
query = smartNameFieldMappers.mapper().rangeQuery(from, to, includeLower, includeUpper, parseContext);
}
}
if (query == null) {
query = new TermRangeQuery(fieldName, BytesRefs.toBytesRef(from), BytesRefs.toBytesRef(to), includeLower, includeUpper);
}
query.setBoost(boost);
query = wrapSmartNameQuery(query, smartNameFieldMappers, parseContext);
if (queryName != null) {
parseContext.addNamedQuery(queryName, query);
}
return query;
}
} | 1no label
| src_main_java_org_elasticsearch_index_query_RangeQueryParser.java |
576 | public interface IndexEntriesResultListener {
boolean addResult(ODocument entry);
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_OIndex.java |
177 | private static class AddOneFunction implements IFunction<Long, Long> {
@Override
public Long apply(Long input) {
return input+1;
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_atomiclong_ClientAtomicLongTest.java |
38 | public class TransactionalTitanGraphTestSuite extends TransactionalGraphTestSuite {
public TransactionalTitanGraphTestSuite(final GraphTest graphTest) {
super(graphTest);
}
@Override
public void testCompetingThreads() {
TitanBlueprintsGraph graph = (TitanBlueprintsGraph) graphTest.generateGraph();
//Need to define types before hand to avoid deadlock in transactions
TitanManagement mgmt = graph.getManagementSystem();
mgmt.makeEdgeLabel("friend").make();
mgmt.makePropertyKey("test").dataType(Long.class).make();
mgmt.makePropertyKey("blah").dataType(Float.class).make();
mgmt.makePropertyKey("bloop").dataType(Integer.class).make();
mgmt.commit();
graph.shutdown();
super.testCompetingThreads();
}
} | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_blueprints_TransactionalTitanGraphTestSuite.java |
3,502 | public static class ParserContext {
private final PostingsFormatService postingsFormatService;
private final DocValuesFormatService docValuesFormatService;
private final AnalysisService analysisService;
private final SimilarityLookupService similarityLookupService;
private final ImmutableMap<String, TypeParser> typeParsers;
private final Version indexVersionCreated;
public ParserContext(PostingsFormatService postingsFormatService, DocValuesFormatService docValuesFormatService,
AnalysisService analysisService, SimilarityLookupService similarityLookupService,
ImmutableMap<String, TypeParser> typeParsers, Version indexVersionCreated) {
this.postingsFormatService = postingsFormatService;
this.docValuesFormatService = docValuesFormatService;
this.analysisService = analysisService;
this.similarityLookupService = similarityLookupService;
this.typeParsers = typeParsers;
this.indexVersionCreated = indexVersionCreated;
}
public AnalysisService analysisService() {
return analysisService;
}
public PostingsFormatService postingFormatService() {
return postingsFormatService;
}
public DocValuesFormatService docValuesFormatService() {
return docValuesFormatService;
}
public SimilarityLookupService similarityLookupService() {
return similarityLookupService;
}
public TypeParser typeParser(String type) {
return typeParsers.get(Strings.toUnderscoreCase(type));
}
public Version indexVersionCreated() {
return indexVersionCreated;
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_Mapper.java |
3,216 | MULTI_VALUED_ENUM {
public int numValues(Random r) {
return r.nextInt(3);
}
@Override
public long nextValue(Random r) {
return 3 + r.nextInt(8);
}
}, | 0true
| src_test_java_org_elasticsearch_index_fielddata_LongFieldDataTests.java |
1,913 | public class TypeLiteral<T> {
final Class<? super T> rawType;
final Type type;
final int hashCode;
/**
* Constructs a new type literal. Derives represented class from type
* parameter.
* <p/>
* <p>Clients create an empty anonymous subclass. Doing so embeds the type
* parameter in the anonymous class's type hierarchy so we can reconstitute it
* at runtime despite erasure.
*/
@SuppressWarnings("unchecked")
protected TypeLiteral() {
this.type = getSuperclassTypeParameter(getClass());
this.rawType = (Class<? super T>) MoreTypes.getRawType(type);
this.hashCode = MoreTypes.hashCode(type);
}
/**
* Unsafe. Constructs a type literal manually.
*/
@SuppressWarnings("unchecked")
TypeLiteral(Type type) {
this.type = canonicalize(checkNotNull(type, "type"));
this.rawType = (Class<? super T>) MoreTypes.getRawType(this.type);
this.hashCode = MoreTypes.hashCode(this.type);
}
/**
* Returns the type from super class's type parameter in {@link MoreTypes#canonicalize(Type)
* canonical form}.
*/
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return canonicalize(parameterized.getActualTypeArguments()[0]);
}
/**
* Gets type literal from super class's type parameter.
*/
static TypeLiteral<?> fromSuperclassTypeParameter(Class<?> subclass) {
return new TypeLiteral<Object>(getSuperclassTypeParameter(subclass));
}
/**
* Returns the raw (non-generic) type for this type.
*
* @since 2.0
*/
public final Class<? super T> getRawType() {
return rawType;
}
/**
* Gets underlying {@code Type} instance.
*/
public final Type getType() {
return type;
}
/**
* Gets the type of this type's provider.
*/
@SuppressWarnings("unchecked")
final TypeLiteral<Provider<T>> providerType() {
// This cast is safe and wouldn't generate a warning if Type had a type
// parameter.
return (TypeLiteral<Provider<T>>) get(Types.providerOf(getType()));
}
@Override
public final int hashCode() {
return this.hashCode;
}
@Override
public final boolean equals(Object o) {
return o instanceof TypeLiteral<?>
&& MoreTypes.equals(type, ((TypeLiteral) o).type);
}
@Override
public final String toString() {
return MoreTypes.toString(type);
}
/**
* Gets type literal for the given {@code Type} instance.
*/
public static TypeLiteral<?> get(Type type) {
return new TypeLiteral<Object>(type);
}
/**
* Gets type literal for the given {@code Class} instance.
*/
public static <T> TypeLiteral<T> get(Class<T> type) {
return new TypeLiteral<T>(type);
}
/**
* Returns an immutable list of the resolved types.
*/
private List<TypeLiteral<?>> resolveAll(Type[] types) {
TypeLiteral<?>[] result = new TypeLiteral<?>[types.length];
for (int t = 0; t < types.length; t++) {
result[t] = resolve(types[t]);
}
return ImmutableList.copyOf(result);
}
/**
* Resolves known type parameters in {@code toResolve} and returns the result.
*/
TypeLiteral<?> resolve(Type toResolve) {
return TypeLiteral.get(resolveType(toResolve));
}
Type resolveType(Type toResolve) {
// this implementation is made a little more complicated in an attempt to avoid object-creation
while (true) {
if (toResolve instanceof TypeVariable) {
TypeVariable original = (TypeVariable) toResolve;
toResolve = MoreTypes.resolveTypeVariable(type, rawType, original);
if (toResolve == original) {
return toResolve;
}
} else if (toResolve instanceof GenericArrayType) {
GenericArrayType original = (GenericArrayType) toResolve;
Type componentType = original.getGenericComponentType();
Type newComponentType = resolveType(componentType);
return componentType == newComponentType
? original
: Types.arrayOf(newComponentType);
} else if (toResolve instanceof ParameterizedType) {
ParameterizedType original = (ParameterizedType) toResolve;
Type ownerType = original.getOwnerType();
Type newOwnerType = resolveType(ownerType);
boolean changed = newOwnerType != ownerType;
Type[] args = original.getActualTypeArguments();
for (int t = 0, length = args.length; t < length; t++) {
Type resolvedTypeArgument = resolveType(args[t]);
if (resolvedTypeArgument != args[t]) {
if (!changed) {
args = args.clone();
changed = true;
}
args[t] = resolvedTypeArgument;
}
}
return changed
? Types.newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args)
: original;
} else if (toResolve instanceof WildcardType) {
WildcardType original = (WildcardType) toResolve;
Type[] originalLowerBound = original.getLowerBounds();
Type[] originalUpperBound = original.getUpperBounds();
if (originalLowerBound.length == 1) {
Type lowerBound = resolveType(originalLowerBound[0]);
if (lowerBound != originalLowerBound[0]) {
return Types.supertypeOf(lowerBound);
}
} else if (originalUpperBound.length == 1) {
Type upperBound = resolveType(originalUpperBound[0]);
if (upperBound != originalUpperBound[0]) {
return Types.subtypeOf(upperBound);
}
}
return original;
} else {
return toResolve;
}
}
}
/**
* Returns the generic form of {@code supertype}. For example, if this is {@code
* ArrayList<String>}, this returns {@code Iterable<String>} given the input {@code
* Iterable.class}.
*
* @param supertype a superclass of, or interface implemented by, this.
* @since 2.0
*/
public TypeLiteral<?> getSupertype(Class<?> supertype) {
checkArgument(supertype.isAssignableFrom(rawType),
"%s is not a supertype of %s", supertype, this.type);
return resolve(MoreTypes.getGenericSupertype(type, rawType, supertype));
}
/**
* Returns the resolved generic type of {@code field}.
*
* @param field a field defined by this or any superclass.
* @since 2.0
*/
public TypeLiteral<?> getFieldType(Field field) {
checkArgument(field.getDeclaringClass().isAssignableFrom(rawType),
"%s is not defined by a supertype of %s", field, type);
return resolve(field.getGenericType());
}
/**
* Returns the resolved generic parameter types of {@code methodOrConstructor}.
*
* @param methodOrConstructor a method or constructor defined by this or any supertype.
* @since 2.0
*/
public List<TypeLiteral<?>> getParameterTypes(Member methodOrConstructor) {
Type[] genericParameterTypes;
if (methodOrConstructor instanceof Method) {
Method method = (Method) methodOrConstructor;
checkArgument(method.getDeclaringClass().isAssignableFrom(rawType),
"%s is not defined by a supertype of %s", method, type);
genericParameterTypes = method.getGenericParameterTypes();
} else if (methodOrConstructor instanceof Constructor) {
Constructor constructor = (Constructor) methodOrConstructor;
checkArgument(constructor.getDeclaringClass().isAssignableFrom(rawType),
"%s does not construct a supertype of %s", constructor, type);
genericParameterTypes = constructor.getGenericParameterTypes();
} else {
throw new IllegalArgumentException("Not a method or a constructor: " + methodOrConstructor);
}
return resolveAll(genericParameterTypes);
}
/**
* Returns the resolved generic exception types thrown by {@code constructor}.
*
* @param methodOrConstructor a method or constructor defined by this or any supertype.
* @since 2.0
*/
public List<TypeLiteral<?>> getExceptionTypes(Member methodOrConstructor) {
Type[] genericExceptionTypes;
if (methodOrConstructor instanceof Method) {
Method method = (Method) methodOrConstructor;
checkArgument(method.getDeclaringClass().isAssignableFrom(rawType),
"%s is not defined by a supertype of %s", method, type);
genericExceptionTypes = method.getGenericExceptionTypes();
} else if (methodOrConstructor instanceof Constructor) {
Constructor<?> constructor = (Constructor<?>) methodOrConstructor;
checkArgument(constructor.getDeclaringClass().isAssignableFrom(rawType),
"%s does not construct a supertype of %s", constructor, type);
genericExceptionTypes = constructor.getGenericExceptionTypes();
} else {
throw new IllegalArgumentException("Not a method or a constructor: " + methodOrConstructor);
}
return resolveAll(genericExceptionTypes);
}
/**
* Returns the resolved generic return type of {@code method}.
*
* @param method a method defined by this or any supertype.
* @since 2.0
*/
public TypeLiteral<?> getReturnType(Method method) {
checkArgument(method.getDeclaringClass().isAssignableFrom(rawType),
"%s is not defined by a supertype of %s", method, type);
return resolve(method.getGenericReturnType());
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_TypeLiteral.java |
145 | public interface StructuredContentItemCriteria extends QuantityBasedRule {
/**
* Returns the parent <code>StructuredContent</code> item to which this
* field belongs.
*
* @return
*/
@Nonnull
public StructuredContent getStructuredContent();
/**
* Sets the parent <code>StructuredContent</code> item.
* @param structuredContent
*/
public void setStructuredContent(@Nonnull StructuredContent structuredContent);
/**
* Builds a copy of this item. Used by the content management system when an
* item is edited.
*
* @return a copy of this item
*/
@Nonnull
public StructuredContentItemCriteria cloneEntity();
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentItemCriteria.java |
3,640 | public class GeoShapeFieldMapper extends AbstractFieldMapper<String> {
public static final String CONTENT_TYPE = "geo_shape";
public static class Names {
public static final String TREE = "tree";
public static final String TREE_GEOHASH = "geohash";
public static final String TREE_QUADTREE = "quadtree";
public static final String TREE_LEVELS = "tree_levels";
public static final String TREE_PRESISION = "precision";
public static final String DISTANCE_ERROR_PCT = "distance_error_pct";
public static final String STRATEGY = "strategy";
}
public static class Defaults {
public static final String TREE = Names.TREE_GEOHASH;
public static final String STRATEGY = SpatialStrategy.RECURSIVE.getStrategyName();
public static final int GEOHASH_LEVELS = GeoUtils.geoHashLevelsForPrecision("50m");
public static final int QUADTREE_LEVELS = GeoUtils.quadTreeLevelsForPrecision("50m");
public static final double DISTANCE_ERROR_PCT = 0.025d;
public static final FieldType FIELD_TYPE = new FieldType();
static {
FIELD_TYPE.setIndexed(true);
FIELD_TYPE.setTokenized(false);
FIELD_TYPE.setStored(false);
FIELD_TYPE.setStoreTermVectors(false);
FIELD_TYPE.setOmitNorms(true);
FIELD_TYPE.setIndexOptions(FieldInfo.IndexOptions.DOCS_ONLY);
FIELD_TYPE.freeze();
}
}
public static class Builder extends AbstractFieldMapper.Builder<Builder, GeoShapeFieldMapper> {
private String tree = Defaults.TREE;
private String strategyName = Defaults.STRATEGY;
private int treeLevels = 0;
private double precisionInMeters = -1;
private double distanceErrorPct = Defaults.DISTANCE_ERROR_PCT;
private SpatialPrefixTree prefixTree;
public Builder(String name) {
super(name, new FieldType(Defaults.FIELD_TYPE));
}
public Builder tree(String tree) {
this.tree = tree;
return this;
}
public Builder strategy(String strategy) {
this.strategyName = strategy;
return this;
}
public Builder treeLevelsByDistance(double meters) {
this.precisionInMeters = meters;
return this;
}
public Builder treeLevels(int treeLevels) {
this.treeLevels = treeLevels;
return this;
}
public Builder distanceErrorPct(double distanceErrorPct) {
this.distanceErrorPct = distanceErrorPct;
return this;
}
@Override
public GeoShapeFieldMapper build(BuilderContext context) {
final FieldMapper.Names names = buildNames(context);
if (Names.TREE_GEOHASH.equals(tree)) {
prefixTree = new GeohashPrefixTree(ShapeBuilder.SPATIAL_CONTEXT, getLevels(treeLevels, precisionInMeters, Defaults.GEOHASH_LEVELS, true));
} else if (Names.TREE_QUADTREE.equals(tree)) {
prefixTree = new QuadPrefixTree(ShapeBuilder.SPATIAL_CONTEXT, getLevels(treeLevels, precisionInMeters, Defaults.QUADTREE_LEVELS, false));
} else {
throw new ElasticsearchIllegalArgumentException("Unknown prefix tree type [" + tree + "]");
}
return new GeoShapeFieldMapper(names, prefixTree, strategyName, distanceErrorPct, fieldType, postingsProvider,
docValuesProvider, multiFieldsBuilder.build(this, context), copyTo);
}
}
private static final int getLevels(int treeLevels, double precisionInMeters, int defaultLevels, boolean geoHash) {
if (treeLevels > 0 || precisionInMeters >= 0) {
return Math.max(treeLevels, precisionInMeters >= 0 ? (geoHash ? GeoUtils.geoHashLevelsForPrecision(precisionInMeters)
: GeoUtils.quadTreeLevelsForPrecision(precisionInMeters)) : 0);
}
return defaultLevels;
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Builder builder = geoShapeField(name);
for (Map.Entry<String, Object> entry : node.entrySet()) {
String fieldName = Strings.toUnderscoreCase(entry.getKey());
Object fieldNode = entry.getValue();
if (Names.TREE.equals(fieldName)) {
builder.tree(fieldNode.toString());
} else if (Names.TREE_LEVELS.equals(fieldName)) {
builder.treeLevels(Integer.parseInt(fieldNode.toString()));
} else if (Names.TREE_PRESISION.equals(fieldName)) {
builder.treeLevelsByDistance(DistanceUnit.parse(fieldNode.toString(), DistanceUnit.DEFAULT, DistanceUnit.DEFAULT));
} else if (Names.DISTANCE_ERROR_PCT.equals(fieldName)) {
builder.distanceErrorPct(Double.parseDouble(fieldNode.toString()));
} else if (Names.STRATEGY.equals(fieldName)) {
builder.strategy(fieldNode.toString());
}
}
return builder;
}
}
private final PrefixTreeStrategy defaultStrategy;
private final RecursivePrefixTreeStrategy recursiveStrategy;
private final TermQueryPrefixTreeStrategy termStrategy;
public GeoShapeFieldMapper(FieldMapper.Names names, SpatialPrefixTree tree, String defaultStrategyName, double distanceErrorPct,
FieldType fieldType, PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider,
MultiFields multiFields, CopyTo copyTo) {
super(names, 1, fieldType, null, null, null, postingsProvider, docValuesProvider, null, null, null, null, multiFields, copyTo);
this.recursiveStrategy = new RecursivePrefixTreeStrategy(tree, names.indexName());
this.recursiveStrategy.setDistErrPct(distanceErrorPct);
this.termStrategy = new TermQueryPrefixTreeStrategy(tree, names.indexName());
this.termStrategy.setDistErrPct(distanceErrorPct);
this.defaultStrategy = resolveStrategy(defaultStrategyName);
}
@Override
public FieldType defaultFieldType() {
return Defaults.FIELD_TYPE;
}
@Override
public FieldDataType defaultFieldDataType() {
return null;
}
@Override
public boolean hasDocValues() {
return false;
}
@Override
public void parse(ParseContext context) throws IOException {
try {
ShapeBuilder shape = ShapeBuilder.parse(context.parser());
if (shape == null) {
return;
}
Field[] fields = defaultStrategy.createIndexableFields(shape.build());
if (fields == null || fields.length == 0) {
return;
}
for (Field field : fields) {
if (!customBoost()) {
field.setBoost(boost);
}
if (context.listener().beforeFieldAdded(this, field, context)) {
context.doc().add(field);
}
}
} catch (Exception e) {
throw new MapperParsingException("failed to parse [" + names.fullName() + "]", e);
}
}
@Override
protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException {
}
@Override
protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
builder.field("type", contentType());
// TODO: Come up with a better way to get the name, maybe pass it from builder
if (defaultStrategy.getGrid() instanceof GeohashPrefixTree) {
// Don't emit the tree name since GeohashPrefixTree is the default
// Only emit the tree levels if it isn't the default value
if (includeDefaults || defaultStrategy.getGrid().getMaxLevels() != Defaults.GEOHASH_LEVELS) {
builder.field(Names.TREE_LEVELS, defaultStrategy.getGrid().getMaxLevels());
}
} else {
builder.field(Names.TREE, Names.TREE_QUADTREE);
if (includeDefaults || defaultStrategy.getGrid().getMaxLevels() != Defaults.QUADTREE_LEVELS) {
builder.field(Names.TREE_LEVELS, defaultStrategy.getGrid().getMaxLevels());
}
}
if (includeDefaults || defaultStrategy.getDistErrPct() != Defaults.DISTANCE_ERROR_PCT) {
builder.field(Names.DISTANCE_ERROR_PCT, defaultStrategy.getDistErrPct());
}
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
public String value(Object value) {
throw new UnsupportedOperationException("GeoShape fields cannot be converted to String values");
}
public PrefixTreeStrategy defaultStrategy() {
return this.defaultStrategy;
}
public PrefixTreeStrategy recursiveStrategy() {
return this.recursiveStrategy;
}
public PrefixTreeStrategy termStrategy() {
return this.termStrategy;
}
public PrefixTreeStrategy resolveStrategy(String strategyName) {
if (SpatialStrategy.RECURSIVE.getStrategyName().equals(strategyName)) {
return recursiveStrategy;
}
if (SpatialStrategy.TERM.getStrategyName().equals(strategyName)) {
return termStrategy;
}
throw new ElasticsearchIllegalArgumentException("Unknown prefix tree strategy [" + strategyName + "]");
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_geo_GeoShapeFieldMapper.java |
1,878 | public class ListGridRecord {
protected ListGrid listGrid;
protected String id;
protected List<Field> fields = new ArrayList<Field>();
protected List<Field> hiddenFields = new ArrayList<Field>();
/**
* Convenience map keyed by the field name. Used to guarantee field ordering with header fields within a ListGrid
*/
protected Map<String, Field> fieldMap;
public String getPath() {
return listGrid.getPath() + "/" + id;
}
public boolean getCanLinkToExternalEntity() {
return StringUtils.isNotBlank(listGrid.getExternalEntitySectionKey());
}
public String getExternalEntityPath() {
return listGrid.getExternalEntitySectionKey() + "/" + id;
}
public ListGrid getListGrid() {
return listGrid;
}
public void setListGrid(ListGrid listGrid) {
this.listGrid = listGrid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getIndex() {
return listGrid.getStartIndex() + listGrid.getRecords().indexOf(this);
}
/**
* Normally you should not be looping through these fields. In order to preserve proper field ordering, instead you
* should loop through {@link ListGrid#getHeaderFields()} and then invoke the {@link #getField(String)} method
* with that header field name.
*
* @return
*/
public List<Field> getFields() {
return fields;
}
public void setFields(List<Field> fields) {
this.fields = fields;
}
public List<Field> getHiddenFields() {
return hiddenFields;
}
public void setHiddenFields(List<Field> hiddenFields) {
this.hiddenFields = hiddenFields;
}
/**
* Returns a {@link Field} in this record for a particular field name. Used when displaying a {@link ListGrid} in order
* to guarantee proper field ordering
*
* @param fieldName
* @return
*/
public Field getField(String fieldName) {
if (fieldMap == null) {
fieldMap = new LinkedHashMap<String, Field>();
for (Field field : fields) {
fieldMap.put(field.getName(), field);
}
for (Field hiddenField : hiddenFields) {
fieldMap.put(hiddenField.getName(), hiddenField);
}
}
Field field = fieldMap.get(fieldName);
// We'll return a null field is this particular record doesn't have this polymorphic property.
// This prevents NPEs in list grids
if (field == null) {
field = new Field();
}
return field;
}
public void clearFieldMap() {
fieldMap = null;
}
public String getHiddenFieldsJson() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\"hiddenFields\":[");
for (int j=0;j<hiddenFields.size();j++) {
sb.append("{\"name\":\"");
sb.append(hiddenFields.get(j).getName());
sb.append("\",\"val\":\"");
sb.append(hiddenFields.get(j).getValue());
sb.append("\"}");
if (j < hiddenFields.size()-1) {
sb.append(",");
}
}
sb.append("]}");
return sb.toString();
}
} | 1no label
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_web_form_component_ListGridRecord.java |
1,447 | public class TitanHadoopGraph {
private final TitanHadoopSetup setup;
private final TypeInspector typeManager;
private final SystemTypeInspector systemTypes;
private final VertexReader vertexReader;
private final boolean verifyVertexExistence = false;
private static final Logger log =
LoggerFactory.getLogger(TitanHadoopGraph.class);
public TitanHadoopGraph(final TitanHadoopSetup setup) {
this.setup = setup;
this.typeManager = setup.getTypeInspector();
this.systemTypes = setup.getSystemTypeInspector();
this.vertexReader = setup.getVertexReader();
}
protected FaunusVertex readHadoopVertex(final Configuration configuration, final StaticBuffer key, Iterable<Entry> entries) {
final long vertexId = this.vertexReader.getVertexId(key);
Preconditions.checkArgument(vertexId > 0);
FaunusVertex vertex = new FaunusVertex(configuration, vertexId);
boolean foundVertexState = !verifyVertexExistence;
for (final Entry data : entries) {
try {
RelationReader relationReader = setup.getRelationReader(vertex.getLongId());
final RelationCache relation = relationReader.parseRelation(data, false, typeManager);
if (this.systemTypes.isVertexExistsSystemType(relation.typeId)) {
foundVertexState = true;
} else if (this.systemTypes.isVertexLabelSystemType(relation.typeId)) {
//Vertex Label
long vertexLabelId = relation.getOtherVertexId();
VertexLabel vl = typeManager.getExistingVertexLabel(vertexLabelId);
vertex.setVertexLabel(vertex.getTypeManager().getVertexLabel(vl.getName()));
}
if (systemTypes.isSystemType(relation.typeId)) continue; //Ignore system types
final RelationType type = typeManager.getExistingRelationType(relation.typeId);
if (((InternalRelationType)type).isHiddenType()) continue; //Ignore hidden types
StandardFaunusRelation frel;
if (type.isPropertyKey()) {
Object value = relation.getValue();
Preconditions.checkNotNull(value);
final StandardFaunusProperty fprop = new StandardFaunusProperty(relation.relationId, vertex, type.getName(), value);
vertex.addProperty(fprop);
frel = fprop;
} else {
assert type.isEdgeLabel();
StandardFaunusEdge fedge;
if (relation.direction.equals(Direction.IN))
fedge = new StandardFaunusEdge(configuration, relation.relationId, relation.getOtherVertexId(), vertexId, type.getName());
else if (relation.direction.equals(Direction.OUT))
fedge = new StandardFaunusEdge(configuration, relation.relationId, vertexId, relation.getOtherVertexId(), type.getName());
else
throw ExceptionFactory.bothIsNotSupported();
vertex.addEdge(fedge);
frel = fedge;
}
if (relation.hasProperties()) {
// load relation properties
for (final LongObjectCursor<Object> next : relation) {
assert next.value != null;
RelationType rt = typeManager.getExistingRelationType(next.key);
if (rt.isPropertyKey()) {
PropertyKey pkey = (PropertyKey)vertex.getTypeManager().getPropertyKey(rt.getName());
log.debug("Retrieved key {} for name \"{}\"", pkey, rt.getName());
frel.setProperty(pkey, next.value);
} else {
assert next.value instanceof Long;
EdgeLabel el = (EdgeLabel)vertex.getTypeManager().getEdgeLabel(rt.getName());
log.debug("Retrieved ege label {} for name \"{}\"", el, rt.getName());
frel.setProperty(el, new FaunusVertex(configuration,(Long)next.value));
}
}
for (TitanRelation rel : frel.query().queryAll().relations())
((FaunusRelation)rel).setLifeCycle(ElementLifeCycle.Loaded);
}
frel.setLifeCycle(ElementLifeCycle.Loaded);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
vertex.setLifeCycle(ElementLifeCycle.Loaded);
/*Since we are filtering out system relation types, we might end up with vertices that have no incident relations.
This is especially true for schema vertices. Those are filtered out. */
if (!foundVertexState || !vertex.query().relations().iterator().hasNext()) return null;
return vertex;
}
public void close() {
setup.close();
}
} | 1no label
| titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_formats_util_TitanHadoopGraph.java |
813 | public static class Response extends ActionResponse {
private List<Item> items;
public List<Item> items() {
return items;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(items.size());
for (Item item : items) {
out.writeVInt(item.slot);
if (item.response != null) {
out.writeBoolean(true);
item.response.writeTo(out);
} else {
out.writeBoolean(false);
out.writeText(item.error);
}
}
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
int size = in.readVInt();
items = new ArrayList<Item>(size);
for (int i = 0; i < size; i++) {
int slot = in.readVInt();
if (in.readBoolean()) {
PercolateShardResponse shardResponse = new PercolateShardResponse();
shardResponse.readFrom(in);
items.add(new Item(slot, shardResponse));
} else {
items.add(new Item(slot, in.readText()));
}
}
}
public static class Item {
private final int slot;
private final PercolateShardResponse response;
private final Text error;
public Item(Integer slot, PercolateShardResponse response) {
this.slot = slot;
this.response = response;
this.error = null;
}
public Item(Integer slot, Text error) {
this.slot = slot;
this.error = error;
this.response = null;
}
public int slot() {
return slot;
}
public PercolateShardResponse response() {
return response;
}
public Text error() {
return error;
}
public boolean failed() {
return error != null;
}
}
} | 0true
| src_main_java_org_elasticsearch_action_percolate_TransportShardMultiPercolateAction.java |
782 | class TransactionLogKey {
private final String name;
private final long itemId;
private final String serviceName;
TransactionLogKey(String name, long itemId, String serviceName) {
this.name = name;
this.itemId = itemId;
this.serviceName = serviceName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TransactionLogKey)) {
return false;
}
TransactionLogKey that = (TransactionLogKey) o;
if (itemId != that.itemId) {
return false;
}
if (!name.equals(that.name)) {
return false;
}
if (!serviceName.equals(that.serviceName)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + (int) (itemId ^ (itemId >>> 32));
result = 31 * result + serviceName.hashCode();
return result;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_txn_TransactionLogKey.java |
1,356 | final ExecutionCallback callback = new ExecutionCallback() {
public void onResponse(Object response) {
if ((Boolean) response)
count.incrementAndGet();
latch.countDown();
}
public void onFailure(Throwable t) {
}
}; | 0true
| hazelcast_src_test_java_com_hazelcast_executor_ExecutorServiceTest.java |
1,182 | public interface ManagedContext {
/**
* Initialize the given object instance.
* This is intended for repopulating select fields and methods for deserialized instances.
* It is also possible to proxy the object, e.g. with AOP proxies.
*
* @param obj Object to initialize
* @return the initialized object to use
*/
Object initialize(Object obj);
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_ManagedContext.java |
1,452 | public class DiscoveryNode implements Streamable, Serializable {
public static boolean localNode(Settings settings) {
if (settings.get("node.local") != null) {
return settings.getAsBoolean("node.local", false);
}
if (settings.get("node.mode") != null) {
String nodeMode = settings.get("node.mode");
if ("local".equals(nodeMode)) {
return true;
} else if ("network".equals(nodeMode)) {
return false;
} else {
throw new ElasticsearchIllegalArgumentException("unsupported node.mode [" + nodeMode + "]");
}
}
return false;
}
public static boolean nodeRequiresLocalStorage(Settings settings) {
return !(settings.getAsBoolean("node.client", false) || (!settings.getAsBoolean("node.data", true) && !settings.getAsBoolean("node.master", true)));
}
public static boolean clientNode(Settings settings) {
String client = settings.get("node.client");
return client != null && client.equals("true");
}
public static boolean masterNode(Settings settings) {
String master = settings.get("node.master");
if (master == null) {
return !clientNode(settings);
}
return master.equals("true");
}
public static boolean dataNode(Settings settings) {
String data = settings.get("node.data");
if (data == null) {
return !clientNode(settings);
}
return data.equals("true");
}
public static final ImmutableList<DiscoveryNode> EMPTY_LIST = ImmutableList.of();
private String nodeName = "";
private String nodeId;
private String hostName;
private String hostAddress;
private TransportAddress address;
private ImmutableMap<String, String> attributes;
private Version version = Version.CURRENT;
DiscoveryNode() {
}
public DiscoveryNode(String nodeId, TransportAddress address, Version version) {
this("", nodeId, address, ImmutableMap.<String, String>of(), version);
}
public DiscoveryNode(String nodeName, String nodeId, TransportAddress address, Map<String, String> attributes, Version version) {
this(nodeName, nodeId, NetworkUtils.getLocalHostName(""), NetworkUtils.getLocalHostAddress(""), address, attributes, version);
}
public DiscoveryNode(String nodeName, String nodeId, String hostName, String hostAddress, TransportAddress address, Map<String, String> attributes, Version version) {
if (nodeName != null) {
this.nodeName = nodeName.intern();
}
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (Map.Entry<String, String> entry : attributes.entrySet()) {
builder.put(entry.getKey().intern(), entry.getValue().intern());
}
this.attributes = builder.build();
this.nodeId = nodeId.intern();
this.hostName = hostName.intern();
this.hostAddress = hostAddress.intern();
this.address = address;
this.version = version;
}
/**
* Should this node form a connection to the provided node.
*/
public boolean shouldConnectTo(DiscoveryNode otherNode) {
if (clientNode() && otherNode.clientNode()) {
return false;
}
return true;
}
/**
* The address that the node can be communicated with.
*/
public TransportAddress address() {
return address;
}
/**
* The address that the node can be communicated with.
*/
public TransportAddress getAddress() {
return address();
}
/**
* The unique id of the node.
*/
public String id() {
return nodeId;
}
/**
* The unique id of the node.
*/
public String getId() {
return id();
}
/**
* The name of the node.
*/
public String name() {
return this.nodeName;
}
/**
* The name of the node.
*/
public String getName() {
return name();
}
/**
* The node attributes.
*/
public ImmutableMap<String, String> attributes() {
return this.attributes;
}
/**
* The node attributes.
*/
public ImmutableMap<String, String> getAttributes() {
return attributes();
}
/**
* Should this node hold data (shards) or not.
*/
public boolean dataNode() {
String data = attributes.get("data");
if (data == null) {
return !clientNode();
}
return data.equals("true");
}
/**
* Should this node hold data (shards) or not.
*/
public boolean isDataNode() {
return dataNode();
}
/**
* Is the node a client node or not.
*/
public boolean clientNode() {
String client = attributes.get("client");
return client != null && client.equals("true");
}
public boolean isClientNode() {
return clientNode();
}
/**
* Can this node become master or not.
*/
public boolean masterNode() {
String master = attributes.get("master");
if (master == null) {
return !clientNode();
}
return master.equals("true");
}
/**
* Can this node become master or not.
*/
public boolean isMasterNode() {
return masterNode();
}
public Version version() {
return this.version;
}
public String getHostName() {
return this.hostName;
}
public String getHostAddress() {
return this.hostAddress;
}
public Version getVersion() {
return this.version;
}
public static DiscoveryNode readNode(StreamInput in) throws IOException {
DiscoveryNode node = new DiscoveryNode();
node.readFrom(in);
return node;
}
@Override
public void readFrom(StreamInput in) throws IOException {
nodeName = in.readString().intern();
nodeId = in.readString().intern();
hostName = in.readString().intern();
hostAddress = in.readString().intern();
address = TransportAddressSerializers.addressFromStream(in);
int size = in.readVInt();
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (int i = 0; i < size; i++) {
builder.put(in.readString().intern(), in.readString().intern());
}
attributes = builder.build();
version = Version.readVersion(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(nodeName);
out.writeString(nodeId);
out.writeString(hostName);
out.writeString(hostAddress);
addressToStream(out, address);
out.writeVInt(attributes.size());
for (Map.Entry<String, String> entry : attributes.entrySet()) {
out.writeString(entry.getKey());
out.writeString(entry.getValue());
}
Version.writeVersion(version, out);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof DiscoveryNode))
return false;
DiscoveryNode other = (DiscoveryNode) obj;
return this.nodeId.equals(other.nodeId);
}
@Override
public int hashCode() {
return nodeId.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (nodeName.length() > 0) {
sb.append('[').append(nodeName).append(']');
}
if (nodeId != null) {
sb.append('[').append(nodeId).append(']');
}
if (Strings.hasLength(hostName)) {
sb.append('[').append(hostName).append(']');
}
if (address != null) {
sb.append('[').append(address).append(']');
}
if (!attributes.isEmpty()) {
sb.append(attributes);
}
return sb.toString();
}
} | 0true
| src_main_java_org_elasticsearch_cluster_node_DiscoveryNode.java |
1,858 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class MapTransactionTest extends HazelcastTestSupport {
private final TransactionOptions options = new TransactionOptions().setTransactionType(TransactionOptions.TransactionType.TWO_PHASE);
//unfortunately the bug can't be detected by a unit test since the exception is thrown in a background thread (and logged)
@Test
public void issue_1056s() throws InterruptedException {
HazelcastInstance instance = Hazelcast.newHazelcastInstance();
final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
final CountDownLatch latch = new CountDownLatch(1);
final Thread t = new Thread() {
@Override
public void run() {
TransactionContext ctx = instance2.newTransactionContext();
ctx.beginTransaction();
TransactionalMap<Integer, Integer> txnMap = ctx.getMap("test");
latch.countDown();
txnMap.delete(1);
ctx.commitTransaction();
}
};
t.start();
TransactionContext ctx = instance2.newTransactionContext();
ctx.beginTransaction();
TransactionalMap<Integer, Integer> txnMap = ctx.getMap("test");
txnMap.delete(1);
latch.await();
ctx.commitTransaction();
t.join();
}
@Test
public void testCommitOrder() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(4);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final HazelcastInstance h3 = factory.newHazelcastInstance(config);
final HazelcastInstance h4 = factory.newHazelcastInstance(config);
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
txMap.put("1", "value1");
assertEquals("value1", txMap.put("1", "value2"));
assertEquals("value2", txMap.put("1", "value3"));
assertEquals("value3", txMap.put("1", "value4"));
assertEquals("value4", txMap.put("1", "value5"));
assertEquals("value5", txMap.put("1", "value6"));
assertEquals(1, txMap.size());
return true;
}
});
assertEquals("value6", h4.getMap("default").get("1"));
}
@Test
public void testTxnCommit() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final String map1 = "map1";
final String map2 = "map2";
final String key = "1";
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap1 = context.getMap(map1);
final TransactionalMap<Object, Object> txMap2 = context.getMap(map2);
txMap1.put(key, "value");
assertEquals("value", txMap1.put(key, "value1"));
assertEquals("value1", txMap1.get(key));
txMap2.put(key, "value");
assertEquals("value", txMap2.put(key, "value2"));
assertEquals("value2", txMap2.get(key));
assertEquals(true, txMap1.containsKey(key));
assertEquals(true, txMap2.containsKey(key));
assertNull(h2.getMap(map1).get(key));
assertNull(h2.getMap(map2).get(key));
return true;
}
});
assertTrue(b);
assertEquals("value1", h1.getMap(map1).get(key));
assertEquals("value1", h2.getMap(map1).get(key));
assertEquals("value2", h1.getMap(map2).get(key));
assertEquals("value2", h2.getMap(map2).get(key));
assertFalse(h1.getMap(map1).isLocked(key));
assertFalse(h1.getMap(map2).isLocked(key));
}
@Test
public void testTxnBackupDies() throws TransactionException, InterruptedException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map1 = h1.getMap("default");
final int size = 100;
final CountDownLatch latch = new CountDownLatch(size + 1);
final CountDownLatch latch2 = new CountDownLatch(1);
Runnable runnable = new Runnable() {
public void run() {
try {
final int oneThird = size / 3;
final int threshold = new Random().nextInt(oneThird) + oneThird;
h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
for (int i = 0; i < size; i++) {
if (i == threshold) {
latch2.countDown();
}
txMap.put(i, i);
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
latch.countDown();
}
return true;
}
});
fail();
} catch (Exception ignored) {
}
latch.countDown();
}
};
new Thread(runnable).start();
assertTrue(latch2.await(20, TimeUnit.SECONDS));
h2.shutdown();
assertTrue(latch.await(60, TimeUnit.SECONDS));
for (int i = 0; i < size; i++) {
assertNull(map1.get(i));
}
}
@Test
public void testTxnOwnerDies() throws TransactionException, InterruptedException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(3);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final HazelcastInstance h3 = factory.newHazelcastInstance(config);
final IMap map1 = h1.getMap("default");
final int size = 50;
final AtomicBoolean result = new AtomicBoolean(false);
Runnable runnable = new Runnable() {
public void run() {
try {
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
for (int i = 0; i < size; i++) {
txMap.put(i, i);
sleepSeconds(1);
}
return true;
}
});
result.set(b);
} catch (HazelcastInstanceNotActiveException ignored) {
} catch (TransactionException ignored) {
}
}
};
Thread thread = new Thread(runnable);
thread.start();
sleepSeconds(1);
h1.shutdown();
// wait till thread finishes.
thread.join(30 * 1000);
assertFalse(result.get());
final IMap map2 = h2.getMap("default");
for (int i = 0; i < size; i++) {
assertNull(map2.get(i));
}
}
@Test
public void testTxnSet() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map2 = h2.getMap("default");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
txMap.set("1", "value");
txMap.set("1", "value2");
assertEquals("value2", txMap.get("1"));
assertNull(map2.get("1"));
assertNull(map2.get("2"));
assertEquals(1, txMap.size());
return true;
}
});
assertTrue(b);
IMap map1 = h1.getMap("default");
assertEquals("value2", map1.get("1"));
assertEquals("value2", map2.get("1"));
}
@Test
public void testTxnPutTTL() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map2 = h2.getMap("putWithTTL");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("putWithTTL");
txMap.put("1", "value", 5, TimeUnit.SECONDS);
assertEquals("value", txMap.get("1"));
assertEquals(1, txMap.size());
return true;
}
});
assertTrue(b);
IMap map1 = h2.getMap("putWithTTL");
assertEquals("value", map1.get("1"));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
assertNull(map1.get("1"));
}
@Test
public void testTxnGetForUpdate() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap<String, String> map = h2.getMap("default");
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicBoolean pass = new AtomicBoolean(true);
map.put("var", "value0");
Runnable updater = new Runnable() {
public void run() {
try {
latch1.await(100, TimeUnit.SECONDS);
pass.set(map.tryPut("var", "value1", 0, TimeUnit.SECONDS) == false);
latch2.countDown();
} catch (Exception e) {
}
}
};
new Thread(updater).start();
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
try {
final TransactionalMap<String, Integer> txMap = context.getMap("default");
assertEquals("value0", txMap.getForUpdate("var"));
latch1.countDown();
latch2.await(100, TimeUnit.SECONDS);
} catch (Exception e) {
}
return true;
}
});
assertTrue(b);
assertTrue(pass.get());
assertTrue(map.tryPut("var", "value2", 0, TimeUnit.SECONDS));
}
@Test
public void testTxnGetForUpdateTimeout() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap<String, String> map = h2.getMap("default");
map.put("var", "value0");
map.lock("var");
TransactionOptions opts = new TransactionOptions();
opts.setTimeout(1, TimeUnit.SECONDS);
try {
boolean b = h1.executeTransaction(opts, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<String, String> txMap = context.getMap("default");
txMap.getForUpdate("var");
fail();
return true;
}
});
} catch (TransactionException e) {
}
assertTrue(map.isLocked("var"));
}
@Test
@Category(ProblematicTest.class)
public void testTxnGetForUpdateTxnFails() throws TransactionException {
Config config = new Config();
config.setProperty(GroupProperties.PROP_OPERATION_CALL_TIMEOUT_MILLIS, "5000");
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap<String, String> map = h2.getMap("default");
map.put("var", "value");
map.lock("varLocked");
TransactionOptions opts = new TransactionOptions();
opts.setTimeout(1, TimeUnit.SECONDS);
try {
boolean b = h1.executeTransaction(opts, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<String, String> txMap = context.getMap("default");
txMap.getForUpdate("var");
throw new TransactionException();
}
});
} catch (TransactionException e) {
}
assertFalse(map.isLocked("var"));
assertTrue(map.isLocked("varLocked"));
}
@Test
public void testTxnGetForUpdateMultipleTimes() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap<String, String> map = h2.getMap("default");
map.put("var", "value0");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
try {
final TransactionalMap<String, String> txMap = context.getMap("default");
assertEquals("value0", txMap.getForUpdate("var"));
assertEquals("value0", txMap.getForUpdate("var"));
assertEquals("value0", txMap.getForUpdate("var"));
} catch (Exception e) {
}
return true;
}
});
}
@Test
public void testTxnUpdateThenGetForUpdate() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap<String, String> map = h2.getMap("default");
map.put("var", "value0");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
try {
final TransactionalMap<String, String> txMap = context.getMap("default");
assertEquals("value0", txMap.put("var", "value1"));
assertEquals("value1", txMap.getForUpdate("var"));
} catch (Exception e) {
}
return true;
}
});
}
@Test
public void testTxnGetForUpdateThenUpdate() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap<String, String> map = h2.getMap("default");
map.put("var", "value0");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
try {
final TransactionalMap<String, String> txMap = context.getMap("default");
assertEquals("value0", txMap.getForUpdate("var"));
assertEquals("value0", txMap.put("var", "value1"));
assertEquals("value1", txMap.getForUpdate("var"));
assertEquals("value1", txMap.get("var"));
} catch (Exception e) {
}
return true;
}
});
}
@Test
public void testTxnRemove() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map2 = h2.getMap("default");
map2.put("1", "1");
map2.put("2", "2");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
txMap.put("3", "3");
map2.put("4", "4");
assertEquals("1", txMap.remove("1"));
assertEquals("2", map2.remove("2"));
assertEquals("1", map2.get("1"));
assertEquals(null, txMap.get("1"));
assertEquals(null, txMap.remove("2"));
assertEquals(2, txMap.size());
return true;
}
});
assertTrue(b);
IMap map1 = h1.getMap("default");
assertEquals(null, map1.get("1"));
assertEquals(null, map2.get("1"));
assertEquals(null, map1.get("2"));
assertEquals(null, map2.get("2"));
assertEquals("3", map1.get("3"));
assertEquals("3", map2.get("3"));
assertEquals("4", map1.get("4"));
assertEquals("4", map2.get("4"));
}
@Test
public void testTxnRemoveIfSame() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map2 = h2.getMap("default");
map2.put("1", "1");
map2.put("2", "2");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
txMap.put("3", "3");
map2.put("4", "4");
assertEquals(true, txMap.remove("1", "1"));
assertEquals(false, txMap.remove("2", "1"));
assertEquals("1", map2.get("1"));
assertEquals(null, txMap.get("1"));
assertEquals(true, txMap.remove("2", "2"));
assertEquals(false, txMap.remove("3", null));
assertEquals(false, txMap.remove("5", "2"));
assertEquals(2, txMap.size());
return true;
}
});
assertTrue(b);
IMap map1 = h1.getMap("default");
assertEquals(null, map1.get("1"));
assertEquals(null, map2.get("1"));
assertEquals(null, map1.get("2"));
assertEquals(null, map2.get("2"));
assertEquals("3", map1.get("3"));
assertEquals("3", map2.get("3"));
assertEquals("4", map1.get("4"));
assertEquals("4", map2.get("4"));
}
@Test
public void testTxnDelete() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map2 = h2.getMap("default");
map2.put("1", "1");
map2.put("2", "2");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
txMap.put("3", "3");
map2.put("4", "4");
txMap.delete("1");
map2.delete("2");
assertEquals("1", map2.get("1"));
assertEquals(null, txMap.get("1"));
txMap.delete("2");
assertEquals(2, txMap.size());
return true;
}
});
assertTrue(b);
IMap map1 = h1.getMap("default");
assertEquals(null, map1.get("1"));
assertEquals(null, map2.get("1"));
assertEquals(null, map1.get("2"));
assertEquals(null, map2.get("2"));
assertEquals("3", map1.get("3"));
assertEquals("3", map2.get("3"));
assertEquals("4", map1.get("4"));
assertEquals("4", map2.get("4"));
}
@Test
public void testTxnPutIfAbsent() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map2 = h2.getMap("default");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
txMap.putIfAbsent("1", "value");
assertEquals("value", txMap.putIfAbsent("1", "value2"));
assertEquals("value", txMap.get("1"));
assertNull(map2.get("1"));
assertNull(map2.get("2"));
return true;
}
});
assertTrue(b);
IMap map1 = h1.getMap("default");
assertEquals("value", map1.get("1"));
assertEquals("value", map2.get("1"));
}
@Test
public void testTxnReplace() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map2 = h2.getMap("default");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
assertNull(txMap.replace("1", "value"));
txMap.put("1", "value2");
assertEquals("value2", txMap.replace("1", "value3"));
assertEquals("value3", txMap.get("1"));
assertNull(map2.get("1"));
assertNull(map2.get("2"));
return true;
}
});
assertTrue(b);
IMap map1 = h1.getMap("default");
assertEquals("value3", map1.get("1"));
assertEquals("value3", map2.get("1"));
}
@Test
public void testTxnReplaceIfSame() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map2 = h2.getMap("default");
map2.put("1", "1");
map2.put("2", "2");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
assertEquals(true, txMap.replace("1", "1", "11"));
assertEquals(false, txMap.replace("5", "5", "55"));
assertEquals(false, txMap.replace("2", "1", "22"));
assertEquals("1", map2.get("1"));
assertEquals("11", txMap.get("1"));
assertEquals("2", map2.get("2"));
assertEquals("2", txMap.get("2"));
return true;
}
});
assertTrue(b);
IMap map1 = h1.getMap("default");
assertEquals("11", map1.get("1"));
assertEquals("11", map2.get("1"));
assertEquals("2", map1.get("2"));
assertEquals("2", map2.get("2"));
}
@Test
public void testTxnReplace2() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map2 = h2.getMap("default");
map2.put("1", "value2");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
assertEquals("value2", txMap.replace("1", "value3"));
assertEquals("value3", txMap.get("1"));
assertNull(map2.get("2"));
return true;
}
});
assertTrue(b);
IMap map1 = h1.getMap("default");
assertEquals("value3", map1.get("1"));
assertEquals("value3", map2.get("1"));
}
@Test
public void testIssue1076() {
final HazelcastInstance inst = createHazelcastInstance();
IMap map = inst.getMap("default");
EntryListener<String, Integer> l = new EntryAdapter<String, Integer>() {
};
EntryObject e = new PredicateBuilder().getEntryObject();
Predicate<String, Integer> p = e.equal(1);
map.addEntryListener(l, p, null, false);
for (Integer i = 0; i < 100; i++) {
TransactionContext context = inst.newTransactionContext();
context.beginTransaction();
TransactionalMap<String, Integer> txnMap = context.getMap("default");
txnMap.remove(i.toString());
context.commitTransaction();
}
assertEquals(0, map.size());
inst.shutdown();
}
@Test
@Category(ProblematicTest.class)
// TODO: @mm - Review following case...
public void testFailingMapStore() throws TransactionException {
final String map = "map";
final String anotherMap = "anotherMap";
Config config = new Config();
config.getMapConfig(map).setMapStoreConfig(new MapStoreConfig()
.setEnabled(true).setImplementation(new MapStoreAdapter() {
public void store(Object key, Object value) {
throw new IllegalStateException("Map store intentionally failed :) ");
}
}));
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
assertNull(context.getMap(map).put("1", "value1"));
assertNull(context.getMap(anotherMap).put("1", "value1"));
return true;
}
});
assertTrue(b);
assertNull(h2.getMap(map).get("1"));
assertEquals("value1", h2.getMap(anotherMap).get("1"));
}
@Test
public void testRollbackMap() throws Throwable {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(4);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final TransactionContext transactionContext = h1.newTransactionContext();
transactionContext.beginTransaction();
TransactionalMap<Integer, String> m = transactionContext.getMap("testRollbackMap");
Integer key1 = 1;
String value1 = "value1";
Integer key2 = 2;
String value2 = "value2";
m.put(key1, value1);
m.put(key2, value2);
transactionContext.rollbackTransaction();
assertNull(h1.getMap("testRollbackMap").get(key1));
assertNull(h1.getMap("testRollbackMap").get(key2));
}
@Test(expected = TransactionNotActiveException.class)
public void testTxnMapOuterTransaction() throws Throwable {
final HazelcastInstance h1 = createHazelcastInstance();
final TransactionContext transactionContext = h1.newTransactionContext();
transactionContext.beginTransaction();
TransactionalMap<Integer, Integer> m = transactionContext.getMap("testTxnMapOuterTransaction");
m.put(1, 1);
transactionContext.commitTransaction();
m.put(1, 1);
}
@Test
public void testIssue615keySet() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map = h2.getMap("default");
map.put("1", "1");
map.put("2", "2");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
txMap.put("3", "3");
assertEquals(3, txMap.keySet().size());
map.put("4", "4");
assertEquals(4, txMap.keySet().size());
txMap.remove("1");
assertEquals(3, txMap.keySet().size());
map.remove("2");
assertEquals(2, txMap.keySet().size());
assertEquals(2, txMap.size());
return true;
}
});
assertEquals(2, map.keySet().size());
// raise an exception and rollback changes.
try {
boolean b2 = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
txMap.put("5", "5");
assertEquals(3, txMap.keySet().size());
assertEquals(2, map.keySet().size());
throw new DummyUncheckedHazelcastTestException();
}
});
} catch (Exception e) {
if (!(e instanceof DummyUncheckedHazelcastTestException)) {
throw new RuntimeException(e);
}
}
assertEquals(2, map.keySet().size());
h1.shutdown();
h2.shutdown();
}
@Test
public void testIssue615KeysetWithPredicate() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map = h2.getMap("default");
final SampleObjects.Employee employee1 = new SampleObjects.Employee("abc-123-xvz", 34, true, 10D);
final SampleObjects.Employee employee2 = new SampleObjects.Employee("abc-1xvz", 4, true, 7D);
final SampleObjects.Employee employee3 = new SampleObjects.Employee("abc-1xasda...vz", 7, true, 1D);
final SampleObjects.Employee employee4 = new SampleObjects.Employee("abc-1asdsaxvz", 2, true, 2D);
map.put(1, employee1);
try {
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
assertEquals(0, txMap.keySet(new SqlPredicate("age <= 10")).size());
//put
txMap.put(2, employee2);
Set keys = txMap.keySet(new SqlPredicate("age <= 10"));
Iterator iterator = keys.iterator();
assertEquals(1, keys.size());
while (iterator.hasNext()) {
assertEquals(2, ((Integer) iterator.next()).intValue());
}
txMap.put(3, employee3);
txMap.put(4, employee4);
keys = txMap.keySet(new SqlPredicate("age <= 10"));
assertEquals(3, keys.size());
// force rollback.
throw new DummyUncheckedHazelcastTestException();
}
});
} catch (Exception e) {
if (!(e instanceof DummyUncheckedHazelcastTestException)) {
throw new RuntimeException(e);
}
}
assertEquals(1, map.size());
assertEquals(1, map.keySet().size());
assertEquals(0, map.keySet(new SqlPredicate("age <= 10")).size());
h1.shutdown();
h2.shutdown();
}
@Test
public void testIssue615KeysetPredicates() throws TransactionException {
final String MAP_NAME = "defaultMap";
final Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map = h2.getMap(MAP_NAME);
final SampleObjects.Employee employee1 = new SampleObjects.Employee("abc-123-xvz", 34, true, 10D);
final SampleObjects.Employee employee2 = new SampleObjects.Employee("abc-1xvz", 4, true, 7D);
final SampleObjects.Employee employee3 = new SampleObjects.Employee("abc-1xasda...vz", 7, true, 1D);
final SampleObjects.Employee employee4 = new SampleObjects.Employee("abc-1asdsaxvz", 2, true, 2D);
map.put(employee1, employee1);
final TransactionContext context = h1.newTransactionContext();
context.beginTransaction();
final TransactionalMap<Object, Object> txMap = context.getMap(MAP_NAME);
assertNull(txMap.put(employee2, employee2));
assertEquals(2, txMap.size());
assertEquals(2, txMap.keySet().size());
assertEquals(1, txMap.keySet(new SqlPredicate("age = 34")).size());
context.commitTransaction();
assertEquals(2, map.size());
h1.shutdown();
h2.shutdown();
}
@Test
public void testIssue615values() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map2 = h2.getMap("default");
map2.put("1", "1");
map2.put("2", "2");
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
txMap.put("3", "3");
assertEquals(3, txMap.values().size());
map2.put("4", "4");
assertEquals(4, txMap.values().size());
txMap.remove("1");
assertEquals(3, txMap.values().size());
map2.remove("2");
assertEquals(2, txMap.values().size());
assertEquals(2, txMap.size());
txMap.put("12", "32");
assertEquals(2, map2.values().size());
return true;
}
});
assertEquals(3, map2.values().size());
h1.shutdown();
h2.shutdown();
}
@Test
public void testIssue615ValuesWithPredicate() throws TransactionException {
Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map2 = h2.getMap("default");
final SampleObjects.Employee emp1 = new SampleObjects.Employee("abc-123-xvz", 34, true, 10D);
map2.put(1, emp1);
final SampleObjects.Employee emp2 = new SampleObjects.Employee("xvz", 4, true, 10D);
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
assertEquals(0, txMap.values(new SqlPredicate("age <= 10")).size());
txMap.put(2, emp2);
Collection coll = txMap.values(new SqlPredicate("age <= 10"));
Iterator<Object> iterator = coll.iterator();
while (iterator.hasNext()) {
final SampleObjects.Employee e = (SampleObjects.Employee) iterator.next();
assertEquals(emp2, e);
}
coll = txMap.values(new SqlPredicate("age > 30 "));
iterator = coll.iterator();
while (iterator.hasNext()) {
final SampleObjects.Employee e = (SampleObjects.Employee) iterator.next();
assertEquals(emp1, e);
}
txMap.remove(2);
coll = txMap.values(new SqlPredicate("age <= 10 "));
assertEquals(0, coll.size());
return true;
}
});
assertEquals(0, map2.values(new SqlPredicate("age <= 10")).size());
assertEquals(1, map2.values(new SqlPredicate("age = 34")).size());
h1.shutdown();
h2.shutdown();
}
@Test
public void testValuesWithPredicates_notContains_oldValues() throws TransactionException {
Config config = new Config();
final String mapName = "testValuesWithPredicate_notContains_oldValues";
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
final HazelcastInstance h1 = factory.newHazelcastInstance(config);
final HazelcastInstance h2 = factory.newHazelcastInstance(config);
final IMap map = h1.getMap(mapName);
final SampleObjects.Employee employeeAtAge22 = new SampleObjects.Employee("emin", 22, true, 10D);
final SampleObjects.Employee employeeAtAge23 = new SampleObjects.Employee("emin", 23, true, 10D);
map.put(1, employeeAtAge22);
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap(mapName);
assertEquals(1, txMap.values(new SqlPredicate("age > 21")).size());
txMap.put(1, employeeAtAge23);
Collection coll = txMap.values(new SqlPredicate("age > 21"));
assertEquals(1, coll.size());
return true;
}
});
h1.shutdown();
h2.shutdown();
}
@Test( expected = IllegalArgumentException.class)
public void testValuesWithPagingPredicate() throws TransactionException {
final int nodeCount = 1;
final String mapName = randomMapName("testValuesWithPagingPredicate");
final Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(nodeCount);
final HazelcastInstance node = factory.newHazelcastInstance(config);
final IMap map = node.getMap(mapName);
final SampleObjects.Employee emp = new SampleObjects.Employee("name", 77, true, 10D);
map.put(1, emp);
node.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap(mapName);
PagingPredicate predicate = new PagingPredicate(5);
txMap.values(predicate);
return true;
}
});
}
@Test
public void testValuesWithPredicate_removingExistentEntry() throws TransactionException {
final int nodeCount = 1;
final String mapName = randomMapName("_testValuesWithPredicate_removingExistentEntry_");
final Config config = new Config();
final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(nodeCount);
final HazelcastInstance node = factory.newHazelcastInstance(config);
final IMap map = node.getMap(mapName);
final SampleObjects.Employee emp = new SampleObjects.Employee("name", 77, true, 10D);
map.put(1, emp);
node.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap(mapName);
txMap.remove(1);
Collection<Object> coll = txMap.values(new SqlPredicate("age > 70 "));
assertEquals(0, coll.size());
return true;
}
});
node.shutdown();
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_map_MapTransactionTest.java |
1,951 | public abstract class FailableCache<K, V> {
private final LoadingCache<K, Object> delegate = CacheBuilder.newBuilder().build(new CacheLoader<K, Object>() {
@Override
public Object load(K key) throws Exception {
Errors errors = new Errors();
V result = null;
try {
result = FailableCache.this.create(key, errors);
} catch (ErrorsException e) {
errors.merge(e.getErrors());
}
return errors.hasErrors() ? errors : result;
}
});
protected abstract V create(K key, Errors errors) throws ErrorsException;
public V get(K key, Errors errors) throws ErrorsException {
try {
Object resultOrError = delegate.get(key);
if (resultOrError instanceof Errors) {
errors.merge((Errors) resultOrError);
throw errors.toException();
} else {
@SuppressWarnings("unchecked") // create returned a non-error result, so this is safe
V result = (V) resultOrError;
return result;
}
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_internal_FailableCache.java |
2,061 | @Component("blCustomerStateRequestProcessor")
public class CustomerStateRequestProcessor extends AbstractBroadleafWebRequestProcessor implements ApplicationEventPublisherAware {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public static final String BLC_RULE_MAP_PARAM = "blRuleMap";
@Resource(name="blCustomerService")
protected CustomerService customerService;
protected ApplicationEventPublisher eventPublisher;
protected static String customerRequestAttributeName = "customer";
public static final String ANONYMOUS_CUSTOMER_SESSION_ATTRIBUTE_NAME = "_blc_anonymousCustomer";
public static final String ANONYMOUS_CUSTOMER_ID_SESSION_ATTRIBUTE_NAME = "_blc_anonymousCustomerId";
private static final String LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME = "_blc_lastPublishedEvent";
@Override
public void process(WebRequest request) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Customer customer = null;
if ((authentication != null) && !(authentication instanceof AnonymousAuthenticationToken)) {
String userName = authentication.getName();
customer = (Customer) request.getAttribute(customerRequestAttributeName, WebRequest.SCOPE_REQUEST);
if (userName != null && (customer == null || !userName.equals(customer.getUsername()))) {
// can only get here if the authenticated user does not match the user in session
customer = customerService.readCustomerByUsername(userName);
if (logger.isDebugEnabled() && customer != null) {
logger.debug("Customer found by username " + userName);
}
}
if (customer != null) {
ApplicationEvent lastPublishedEvent = (ApplicationEvent) request.getAttribute(LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME, WebRequest.SCOPE_REQUEST);
if (authentication instanceof RememberMeAuthenticationToken) {
// set transient property of customer
customer.setCookied(true);
boolean publishRememberMeEvent = true;
if (lastPublishedEvent != null && lastPublishedEvent instanceof CustomerAuthenticatedFromCookieEvent) {
CustomerAuthenticatedFromCookieEvent cookieEvent = (CustomerAuthenticatedFromCookieEvent) lastPublishedEvent;
if (userName.equals(cookieEvent.getCustomer().getUsername())) {
publishRememberMeEvent = false;
}
}
if (publishRememberMeEvent) {
CustomerAuthenticatedFromCookieEvent cookieEvent = new CustomerAuthenticatedFromCookieEvent(customer, this.getClass().getName());
eventPublisher.publishEvent(cookieEvent);
request.setAttribute(LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME, cookieEvent, WebRequest.SCOPE_REQUEST);
}
} else if (authentication instanceof UsernamePasswordAuthenticationToken) {
customer.setLoggedIn(true);
boolean publishLoggedInEvent = true;
if (lastPublishedEvent != null && lastPublishedEvent instanceof CustomerLoggedInEvent) {
CustomerLoggedInEvent loggedInEvent = (CustomerLoggedInEvent) lastPublishedEvent;
if (userName.equals(loggedInEvent.getCustomer().getUsername())) {
publishLoggedInEvent= false;
}
}
if (publishLoggedInEvent) {
CustomerLoggedInEvent loggedInEvent = new CustomerLoggedInEvent(customer, this.getClass().getName());
eventPublisher.publishEvent(loggedInEvent);
request.setAttribute(LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME, loggedInEvent, WebRequest.SCOPE_REQUEST);
}
} else {
customer = resolveAuthenticatedCustomer(authentication);
}
}
}
if (customer == null) {
// This is an anonymous customer.
// TODO: Handle a custom cookie (different than remember me) that is just for anonymous users.
// This can be used to remember their cart from a previous visit.
// Cookie logic probably needs to be configurable - with TCS as the exception.
customer = resolveAnonymousCustomer(request);
}
CustomerState.setCustomer(customer);
// Setup customer for content rule processing
Map<String,Object> ruleMap = (Map<String, Object>) request.getAttribute(BLC_RULE_MAP_PARAM, WebRequest.SCOPE_REQUEST);
if (ruleMap == null) {
ruleMap = new HashMap<String,Object>();
}
ruleMap.put("customer", customer);
request.setAttribute(BLC_RULE_MAP_PARAM, ruleMap, WebRequest.SCOPE_REQUEST);
}
/**
* Subclasses can extend to resolve other types of Authentication tokens
* @param authentication
* @return
*/
public Customer resolveAuthenticatedCustomer(Authentication authentication) {
return null;
}
/**
* <p>Implementors can subclass to change how anonymous customers are created. Note that this method is intended to actually create the anonymous
* customer if one does not exist. If you are looking to just get the current anonymous customer (if it exists) then instead use the
* {@link #getAnonymousCustomer(WebRequest)} method.<p>
*
* <p>The intended behavior of this method is as follows:</p>
*
* <ul>
* <li>Look for a {@link Customer} on the session</li>
* <ul>
* <li>If a customer is found in session, keep using the session-based customer</li>
* <li>If a customer is not found in session</li>
* <ul>
* <li>Look for a customer ID in session</li>
* <li>If a customer ID is found in session:</li>
* <ul><li>Look up the customer in the database</ul></li>
* </ul>
* <li>If no there is no customer ID in session (and thus no {@link Customer})</li>
* <ol>
* <li>Create a new customer</li>
* <li>Put the newly-created {@link Customer} in session</li>
* </ol>
* </ul>
* </ul>
*
* @param request
* @return
* @see {@link #getAnonymousCustomer(WebRequest)}
* @see {@link #getAnonymousCustomerAttributeName()}
* @see {@link #getAnonymousCustomerIdAttributeName()}
*/
public Customer resolveAnonymousCustomer(WebRequest request) {
Customer customer;
customer = getAnonymousCustomer(request);
//If there is no Customer object in session, AND no customer id in session, create a new customer
//and store the entire customer in session (don't persist to DB just yet)
if (customer == null) {
customer = customerService.createNewCustomer();
request.setAttribute(getAnonymousCustomerSessionAttributeName(), customer, WebRequest.SCOPE_GLOBAL_SESSION);
}
customer.setAnonymous(true);
return customer;
}
/**
* Returns the anonymous customer that was saved in session. This first checks for a full customer in session (meaning
* that the customer has not already been persisted) and returns that. If there is no full customer in session (and
* there is instead just an anonymous customer ID) then this will look up the customer from the database using that and
* return it.
*
* @param request the current request
* @return the anonymous customer in session or null if there is no anonymous customer represented in session
* @see {@link #getAnonymousCustomerSessionAttributeName()}
* @see {@link #getAnonymousCustomerIdSessionAttributeName()}
*/
public Customer getAnonymousCustomer(WebRequest request) {
Customer anonymousCustomer = (Customer) request.getAttribute(getAnonymousCustomerSessionAttributeName(),
WebRequest.SCOPE_GLOBAL_SESSION);
if (anonymousCustomer == null) {
//Customer is not in session, see if we have just a customer ID in session (the anonymous customer might have
//already been persisted)
Long customerId = (Long) request.getAttribute(getAnonymousCustomerIdSessionAttributeName(), WebRequest.SCOPE_GLOBAL_SESSION);
if (customerId != null) {
//we have a customer ID in session, look up the customer from the database to ensure we have an up-to-date
//customer to store in CustomerState
anonymousCustomer = customerService.readCustomerById(customerId);
}
}
return anonymousCustomer;
}
/**
* Returns the session attribute to store the anonymous customer.
* Some implementations may wish to have a different anonymous customer instance (and as a result a different cart).
*
* The entire Customer should be stored in session ONLY if that Customer has not already been persisted to the database.
* Once it has been persisted (like once the user has added something to the cart) then {@link #getAnonymousCustomerIdAttributeName()}
* should be used instead.
*
* @return the session attribute for an anonymous {@link Customer} that has not been persisted to the database yet
*/
public static String getAnonymousCustomerSessionAttributeName() {
return ANONYMOUS_CUSTOMER_SESSION_ATTRIBUTE_NAME;
}
/**
* <p>Returns the session attribute to store the anonymous customer ID. This session attribute should be used to track
* anonymous customers that have not registered but have state in the database. When users first visit the Broadleaf
* site, a new {@link Customer} is instantiated but is <b>only saved in session</b> and not persisted to the database. However,
* once that user adds something to the cart, that {@link Customer} is now saved in the database and it no longer makes
* sense to pull back a full {@link Customer} object from session, as any session-based {@link Customer} will be out of
* date in regards to Hibernate (specifically with lists).</p>
*
* <p>So, once Broadleaf detects that the session-based {@link Customer} has been persisted, it should remove the session-based
* {@link Customer} and then utilize just the customer ID from session.</p>
*
* @see {@link CustomerStateRefresher}
*/
public static String getAnonymousCustomerIdSessionAttributeName() {
return ANONYMOUS_CUSTOMER_ID_SESSION_ATTRIBUTE_NAME;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
/**
* The request-scoped attribute that should store the {@link Customer}.
*
* <pre>
* Customer customer = (Customer) request.getAttribute(CustomerStateRequestProcessor.getCustomerRequestAttributeName());
* //this is equivalent to the above invocation
* Customer customer = CustomerState.getCustomer();
* </pre>
* @return
* @see {@link CustomerState}
*/
public static String getCustomerRequestAttributeName() {
return customerRequestAttributeName;
}
public static void setCustomerRequestAttributeName(String customerRequestAttributeName) {
CustomerStateRequestProcessor.customerRequestAttributeName = customerRequestAttributeName;
}
} | 1no label
| core_broadleaf-profile-web_src_main_java_org_broadleafcommerce_profile_web_core_security_CustomerStateRequestProcessor.java |
573 | config.addListenerConfig(new ListenerConfig().setImplementation(new MembershipListener() {
final AtomicBoolean flag = new AtomicBoolean(false);
public void memberAdded(MembershipEvent membershipEvent) {
if (flag.compareAndSet(false, true)) {
try {
Thread.sleep((long) (Math.random() * 500) + 50);
eventLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
flag.set(false);
}
}
}
public void memberRemoved(MembershipEvent membershipEvent) {
}
public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) {
}
})); | 0true
| hazelcast_src_test_java_com_hazelcast_cluster_ClusterMembershipTest.java |
974 | public class BeforeAwaitOperation extends BaseLockOperation implements Notifier, BackupAwareOperation {
private String conditionId;
public BeforeAwaitOperation() {
}
public BeforeAwaitOperation(ObjectNamespace namespace, Data key, long threadId, String conditionId) {
super(namespace, key, threadId);
this.conditionId = conditionId;
}
@Override
public void beforeRun() throws Exception {
LockStoreImpl lockStore = getLockStore();
boolean isLockOwner = lockStore.isLockedBy(key, getCallerUuid(), threadId);
ensureOwner(lockStore, isLockOwner);
}
private void ensureOwner(LockStoreImpl lockStore, boolean isLockOwner) {
if (!isLockOwner) {
throw new IllegalMonitorStateException("Current thread is not owner of the lock! -> "
+ lockStore.getOwnerInfo(key));
}
}
@Override
public void run() throws Exception {
LockStoreImpl lockStore = getLockStore();
lockStore.addAwait(key, conditionId, getCallerUuid(), threadId);
lockStore.unlock(key, getCallerUuid(), threadId);
}
@Override
public boolean shouldNotify() {
return true;
}
@Override
public boolean shouldBackup() {
return true;
}
@Override
public Operation getBackupOperation() {
return new BeforeAwaitBackupOperation(namespace, key, threadId, conditionId, getCallerUuid());
}
@Override
public WaitNotifyKey getNotifiedKey() {
return new LockWaitNotifyKey(namespace, key);
}
@Override
public int getId() {
return LockDataSerializerHook.BEFORE_AWAIT;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeUTF(conditionId);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
conditionId = in.readUTF();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_operations_BeforeAwaitOperation.java |
2,159 | public static class FilteredIterator extends FilteredDocIdSetIterator {
private final Bits bits;
FilteredIterator(DocIdSetIterator innerIter, Bits bits) {
super(innerIter);
this.bits = bits;
}
@Override
protected boolean match(int doc) {
return bits.get(doc);
}
} | 0true
| src_main_java_org_elasticsearch_common_lucene_docset_BitsDocIdSetIterator.java |
1,127 | public static class Factory implements NativeScriptFactory {
@Override
public ExecutableScript newScript(@Nullable Map<String, Object> params) {
return new NativeConstantScoreScript();
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_scripts_score_script_NativeConstantScoreScript.java |
3,256 | public abstract class InstancePermission extends ClusterPermission {
protected static final int NONE = 0x0;
protected static final int CREATE = 0x1;
protected static final int DESTROY = 0x2;
protected final int mask;
protected final String actions;
public InstancePermission(String name, String... actions) {
super(name);
if (name == null || "".equals(name)) {
throw new IllegalArgumentException("Permission name is mamdatory!");
}
mask = initMask(actions);
final StringBuilder s = new StringBuilder();
for (String action : actions) {
s.append(action).append(" ");
}
this.actions = s.toString();
}
/**
* init mask
*/
protected abstract int initMask(String[] actions);
@Override
public boolean implies(Permission permission) {
if (this.getClass() != permission.getClass()) {
return false;
}
InstancePermission that = (InstancePermission) permission;
boolean maskTest = ((this.mask & that.mask) == that.mask);
if (!maskTest) {
return false;
}
if (!Config.nameMatches(that.getName(), this.getName())) {
return false;
}
return true;
}
@Override
public String getActions() {
return actions;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + mask;
result = 31 * result + actions.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
InstancePermission other = (InstancePermission) obj;
if (getName() == null && other.getName() != null) {
return false;
}
if (!getName().equals(other.getName())) {
return false;
}
if (mask != other.mask) {
return false;
}
return true;
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_security_permission_InstancePermission.java |
1,385 | public static class Id {
public static final Id EMPTY = new Id(null);
private final String path;
private final String[] pathElements;
public Id(String path) {
this.path = path;
if (path == null) {
pathElements = Strings.EMPTY_ARRAY;
} else {
pathElements = Strings.delimitedListToStringArray(path, ".");
}
}
public boolean hasPath() {
return path != null;
}
public String path() {
return this.path;
}
public String[] pathElements() {
return this.pathElements;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Id id = (Id) o;
if (path != null ? !path.equals(id.path) : id.path != null) return false;
if (!Arrays.equals(pathElements, id.pathElements)) return false;
return true;
}
@Override
public int hashCode() {
int result = path != null ? path.hashCode() : 0;
result = 31 * result + (pathElements != null ? Arrays.hashCode(pathElements) : 0);
return result;
}
} | 0true
| src_main_java_org_elasticsearch_cluster_metadata_MappingMetaData.java |
954 | public class OBinaryProtocol {
public static final int SIZE_BYTE = 1;
public static final int SIZE_CHAR = 2;
public static final int SIZE_SHORT = 2;
public static final int SIZE_INT = 4;
public static final int SIZE_LONG = 8;
public static int string2bytes(final String iInputText, final OutputStream iStream) throws IOException {
if (iInputText == null)
return -1;
final int beginOffset = iStream instanceof OMemoryStream ? ((OMemoryStream) iStream).getPosition() : -1;
final int len = iInputText.length();
for (int i = 0; i < len; i++) {
int c = iInputText.charAt(i);
if (c < 0x80) {
// 7-bits done in one byte.
iStream.write(c);
} else if (c < 0x800) {
// 8-11 bits done in 2 bytes
iStream.write(0xC0 | c >> 6);
iStream.write(0x80 | c & 0x3F);
} else {
// 12-16 bits done in 3 bytes
iStream.write(0xE0 | c >> 12);
iStream.write(0x80 | c >> 6 & 0x3F);
iStream.write(0x80 | c & 0x3F);
}
}
return beginOffset;
}
public static final byte[] string2bytes(final String iInputText) {
if (iInputText == null)
return null;
final int len = iInputText.length();
// worst case, all chars could require 3-byte encodings.
final byte[] output = new byte[len * 3];
// index output[]
int j = 0;
for (int i = 0; i < len; i++) {
int c = iInputText.charAt(i);
if (c < 0x80) {
// 7-bits done in one byte.
output[j++] = (byte) c;
} else if (c < 0x800) {
// 8-11 bits done in 2 bytes
output[j++] = (byte) (0xC0 | c >> 6);
output[j++] = (byte) (0x80 | c & 0x3F);
} else {
// 12-16 bits done in 3 bytes
output[j++] = (byte) (0xE0 | c >> 12);
output[j++] = (byte) (0x80 | c >> 6 & 0x3F);
output[j++] = (byte) (0x80 | c & 0x3F);
}
}// end for
// Prune back our byte array. For efficiency we could hand item back
// partly filled, which is only a minor inconvenience to the caller
// most of the time to save copying the array.
final byte[] chopped = new byte[j];
System.arraycopy(output, 0, chopped, 0, j/* length */);
return chopped;
}// end encode
public static final String bytes2string(final OMemoryStream input, final int iLenght) {
final char[] output = new char[iLenght];
// index input[]
int i = 0;
// index output[]
int j = 0;
while (i < iLenght) {
// get next byte unsigned
int b = input.getAsByte() & 0xff;
i++;
// classify based on the high order 3 bits
switch (b >>> 5) {
default:
// one byte encoding
// 0xxxxxxx
// use just low order 7 bits
// 00000000 0xxxxxxx
output[j++] = (char) (b & 0x7f);
break;
case 6:
// two byte encoding
// 110yyyyy 10xxxxxx
// use low order 6 bits
int y = b & 0x1f;
// use low order 6 bits of the next byte
// It should have high order bits 10, which we don't check.
int x = input.getAsByte() & 0x3f;
i++;
// 00000yyy yyxxxxxx
output[j++] = (char) (y << 6 | x);
break;
case 7:
// three byte encoding
// 1110zzzz 10yyyyyy 10xxxxxx
assert (b & 0x10) == 0 : "UTF8Decoder does not handle 32-bit characters";
// use low order 4 bits
final int z = b & 0x0f;
// use low order 6 bits of the next byte
// It should have high order bits 10, which we don't check.
y = input.getAsByte() & 0x3f;
i++;
// use low order 6 bits of the next byte
// It should have high order bits 10, which we don't check.
x = input.getAsByte() & 0x3f;
i++;
// zzzzyyyy yyxxxxxx
final int asint = (z << 12 | y << 6 | x);
output[j++] = (char) asint;
break;
}// end switch
}// end while
return new String(output, 0/* offset */, j/* count */);
}
public static final String bytes2string(final byte[] iInput) {
if (iInput == null)
return null;
return OBinaryProtocol.bytes2string(iInput, 0, iInput.length);
}
public static final String bytes2string(final byte[] input, final int iBeginOffset, final int iLenght) {
final char[] output = new char[iLenght];
// index input[]
int i = iBeginOffset;
// index output[]
int j = 0;
while (i < iLenght + iBeginOffset) {
// get next byte unsigned
int b = input[i++] & 0xff;
// classify based on the high order 3 bits
switch (b >>> 5) {
default:
// one byte encoding
// 0xxxxxxx
// use just low order 7 bits
// 00000000 0xxxxxxx
output[j++] = (char) (b & 0x7f);
break;
case 6:
// two byte encoding
// 110yyyyy 10xxxxxx
// use low order 6 bits
int y = b & 0x1f;
// use low order 6 bits of the next byte
// It should have high order bits 10, which we don't check.
int x = input[i++] & 0x3f;
// 00000yyy yyxxxxxx
output[j++] = (char) (y << 6 | x);
break;
case 7:
// three byte encoding
// 1110zzzz 10yyyyyy 10xxxxxx
assert (b & 0x10) == 0 : "UTF8Decoder does not handle 32-bit characters";
// use low order 4 bits
final int z = b & 0x0f;
// use low order 6 bits of the next byte
// It should have high order bits 10, which we don't check.
y = input[i++] & 0x3f;
// use low order 6 bits of the next byte
// It should have high order bits 10, which we don't check.
x = input[i++] & 0x3f;
// zzzzyyyy yyxxxxxx
final int asint = (z << 12 | y << 6 | x);
output[j++] = (char) asint;
break;
}// end switch
}// end while
return new String(output, 0/* offset */, j/* count */);
}
public static byte[] char2bytes(final char value) {
return OBinaryProtocol.char2bytes(value, new byte[2], 0);
}
public static byte[] char2bytes(final char value, final byte[] b, final int iBeginOffset) {
b[iBeginOffset] = (byte) ((value >>> 8) & 0xFF);
b[iBeginOffset + 1] = (byte) ((value >>> 0) & 0xFF);
return b;
}
public static int long2bytes(final long value, final OutputStream iStream) throws IOException {
final int beginOffset = iStream instanceof OMemoryStream ? ((OMemoryStream) iStream).getPosition() : -1;
iStream.write((int) (value >>> 56) & 0xFF);
iStream.write((int) (value >>> 48) & 0xFF);
iStream.write((int) (value >>> 40) & 0xFF);
iStream.write((int) (value >>> 32) & 0xFF);
iStream.write((int) (value >>> 24) & 0xFF);
iStream.write((int) (value >>> 16) & 0xFF);
iStream.write((int) (value >>> 8) & 0xFF);
iStream.write((int) (value >>> 0) & 0xFF);
return beginOffset;
}
public static byte[] long2bytes(final long value) {
return OBinaryProtocol.long2bytes(value, new byte[8], 0);
}
public static byte[] long2bytes(final long value, final byte[] b, final int iBeginOffset) {
b[iBeginOffset] = (byte) ((value >>> 56) & 0xFF);
b[iBeginOffset + 1] = (byte) ((value >>> 48) & 0xFF);
b[iBeginOffset + 2] = (byte) ((value >>> 40) & 0xFF);
b[iBeginOffset + 3] = (byte) ((value >>> 32) & 0xFF);
b[iBeginOffset + 4] = (byte) ((value >>> 24) & 0xFF);
b[iBeginOffset + 5] = (byte) ((value >>> 16) & 0xFF);
b[iBeginOffset + 6] = (byte) ((value >>> 8) & 0xFF);
b[iBeginOffset + 7] = (byte) ((value >>> 0) & 0xFF);
return b;
}
public static int int2bytes(final int value, final OutputStream iStream) throws IOException {
final int beginOffset = iStream instanceof OMemoryStream ? ((OMemoryStream) iStream).getPosition() : -1;
iStream.write((value >>> 24) & 0xFF);
iStream.write((value >>> 16) & 0xFF);
iStream.write((value >>> 8) & 0xFF);
iStream.write((value >>> 0) & 0xFF);
return beginOffset;
}
public static byte[] int2bytes(final int value) {
return OBinaryProtocol.int2bytes(value, new byte[4], 0);
}
public static byte[] int2bytes(final int value, final byte[] b, final int iBeginOffset) {
b[iBeginOffset] = (byte) ((value >>> 24) & 0xFF);
b[iBeginOffset + 1] = (byte) ((value >>> 16) & 0xFF);
b[iBeginOffset + 2] = (byte) ((value >>> 8) & 0xFF);
b[iBeginOffset + 3] = (byte) ((value >>> 0) & 0xFF);
return b;
}
public static int short2bytes(final short value, final OutputStream iStream) throws IOException {
final int beginOffset = iStream instanceof OMemoryStream ? ((OMemoryStream) iStream).getPosition() : -1;
iStream.write((value >>> 8) & 0xFF);
iStream.write((value >>> 0) & 0xFF);
return beginOffset;
}
public static byte[] short2bytes(final short value) {
return OBinaryProtocol.short2bytes(value, new byte[2], 0);
}
public static byte[] short2bytes(final short value, final byte[] b, final int iBeginOffset) {
b[iBeginOffset] = (byte) ((value >>> 8) & 0xFF);
b[iBeginOffset + 1] = (byte) ((value >>> 0) & 0xFF);
return b;
}
public static long bytes2long(final byte[] b) {
return OBinaryProtocol.bytes2long(b, 0);
}
public static long bytes2long(final InputStream iStream) throws IOException {
return ((long) (0xff & iStream.read()) << 56 | (long) (0xff & iStream.read()) << 48 | (long) (0xff & iStream.read()) << 40
| (long) (0xff & iStream.read()) << 32 | (long) (0xff & iStream.read()) << 24 | (0xff & iStream.read()) << 16
| (0xff & iStream.read()) << 8 | (0xff & iStream.read()));
}
public static long bytes2long(final byte[] b, final int offset) {
return ((0xff & b[offset + 7]) | (0xff & b[offset + 6]) << 8 | (0xff & b[offset + 5]) << 16
| (long) (0xff & b[offset + 4]) << 24 | (long) (0xff & b[offset + 3]) << 32 | (long) (0xff & b[offset + 2]) << 40
| (long) (0xff & b[offset + 1]) << 48 | (long) (0xff & b[offset]) << 56);
}
/**
* Convert the byte array to an int.
*
* @param b
* The byte array
* @return The integer
*/
public static int bytes2int(final byte[] b) {
return bytes2int(b, 0);
}
public static int bytes2int(final InputStream iStream) throws IOException {
return ((0xff & iStream.read()) << 24 | (0xff & iStream.read()) << 16 | (0xff & iStream.read()) << 8 | (0xff & iStream.read()));
}
/**
* Convert the byte array to an int starting from the given offset.
*
* @param b
* The byte array
* @param offset
* The array offset
* @return The integer
*/
public static int bytes2int(final byte[] b, final int offset) {
return (b[offset]) << 24 | (0xff & b[offset + 1]) << 16 | (0xff & b[offset + 2]) << 8 | ((0xff & b[offset + 3]));
}
public static int bytes2short(final InputStream iStream) throws IOException {
return (short) ((iStream.read() << 8) | (iStream.read() & 0xff));
}
public static short bytes2short(final byte[] b) {
return bytes2short(b, 0);
}
public static short bytes2short(final byte[] b, final int offset) {
return (short) ((b[offset] << 8) | (b[offset + 1] & 0xff));
}
public static char bytes2char(final byte[] b) {
return OBinaryProtocol.bytes2char(b, 0);
}
public static char bytes2char(final byte[] b, final int offset) {
return (char) ((b[offset] << 8) + (b[offset + 1] & 0xff));
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_serialization_OBinaryProtocol.java |
316 | public class OStorageClusterHoleConfiguration extends OStorageFileConfiguration {
private static final long serialVersionUID = 1L;
private static final String DEF_EXTENSION = ".och";
private static final String DEF_INCREMENT_SIZE = "50%";
public OStorageClusterHoleConfiguration() {
super();
}
public OStorageClusterHoleConfiguration(OStorageSegmentConfiguration iParent, String iPath, String iType, String iMaxSize) {
super(iParent, iPath + DEF_EXTENSION, iType, iMaxSize, DEF_INCREMENT_SIZE);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_config_OStorageClusterHoleConfiguration.java |
231 | @Entity
@Table(name = "BLC_MODULE_CONFIGURATION")
@EntityListeners(value = { AuditableListener.class })
@Inheritance(strategy = InheritanceType.JOINED)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "blStandardElements")
@AdminPresentationClass(excludeFromPolymorphism = true, friendlyName = "AbstractModuleConfiguration")
public abstract class AbstractModuleConfiguration implements ModuleConfiguration, Status {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "ModuleConfigurationId")
@GenericGenerator(
name = "ModuleConfigurationId",
strategy = "org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name = "segment_value", value = "ModuleConfigurationImpl"),
@Parameter(name = "entity_name", value = "org.broadleafcommerce.common.config.domain.AbstractModuleConfiguration")
}
)
@Column(name = "MODULE_CONFIG_ID")
protected Long id;
@Column(name = "MODULE_NAME", nullable = false)
@AdminPresentation(friendlyName = "AbstractModuleConfiguration_Module_Name", order = 2000, prominent = true, requiredOverride = RequiredOverride.REQUIRED)
protected String moduleName;
@Column(name = "ACTIVE_START_DATE", nullable = true)
@AdminPresentation(friendlyName = "AbstractModuleConfiguration_Active_Start_Date", order = 3000, prominent = true, fieldType = SupportedFieldType.DATE)
protected Date activeStartDate;
@Column(name = "ACTIVE_END_DATE", nullable = true)
@AdminPresentation(friendlyName = "AbstractModuleConfiguration_Active_End_Date", order = 4000, prominent = true, fieldType = SupportedFieldType.DATE)
protected Date activeEndDate;
@Column(name = "IS_DEFAULT", nullable = false)
@AdminPresentation(friendlyName = "AbstractModuleConfiguration_Is_Default", order = 5000, prominent = true, requiredOverride = RequiredOverride.REQUIRED)
protected Boolean isDefault = false;
@Column(name = "CONFIG_TYPE", nullable = false)
@AdminPresentation(friendlyName = "AbstractModuleConfiguration_Config_Type", order = 1000, prominent = true, fieldType = SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration = "org.broadleafcommerce.common.config.service.type.ModuleConfigurationType",
requiredOverride = RequiredOverride.REQUIRED, readOnly = true)
protected String configType;
@Column(name = "MODULE_PRIORITY", nullable = false)
@AdminPresentation(friendlyName = "AbstractModuleConfiguration_Priority",
order = 6000, prominent = true, requiredOverride = RequiredOverride.REQUIRED, tooltip = "AbstractModuleConfiguration_Priority_Tooltip")
protected Integer priority = 100;
@Embedded
protected Auditable auditable = new Auditable();
@Embedded
protected ArchiveStatus archiveStatus = new ArchiveStatus();
@Override
public Long getId() {
return this.id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getModuleName() {
return moduleName;
}
@Override
public void setModuleName(String name) {
this.moduleName = name;
}
@Override
public Boolean getIsDefault() {
if (this.isDefault == null) {
this.isDefault = Boolean.FALSE;
}
return this.isDefault;
}
@Override
public void setIsDefault(Boolean isDefault) {
this.isDefault = isDefault;
}
/**
* Subclasses of this must set the ModuleConfigType in their constructor.
*/
protected void setModuleConfigurationType(ModuleConfigurationType moduleConfigurationType) {
this.configType = moduleConfigurationType.getType();
}
@Override
public ModuleConfigurationType getModuleConfigurationType() {
return ModuleConfigurationType.getInstance(this.configType);
}
@Override
public void setAuditable(Auditable auditable) {
this.auditable = auditable;
}
@Override
public Auditable getAuditable() {
return this.auditable;
}
@Override
public void setArchived(Character archived) {
archiveStatus.setArchived(archived);
}
@Override
public Character getArchived() {
return archiveStatus.getArchived();
}
@Override
public boolean isActive() {
return DateUtil.isActive(activeStartDate, activeEndDate, true) && 'Y' != getArchived();
}
@Override
public void setActiveStartDate(Date startDate) {
this.activeStartDate = startDate;
}
@Override
public Date getActiveStartDate() {
return this.activeStartDate;
}
@Override
public void setActiveEndDate(Date endDate) {
this.activeEndDate = endDate;
}
@Override
public Date getActiveEndDate() {
return this.activeEndDate;
}
@Override
public Integer getPriority() {
return priority;
}
@Override
public void setPriority(Integer priority) {
this.priority = priority;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_config_domain_AbstractModuleConfiguration.java |
105 | PREFIX {
@Override
public boolean evaluate(Object value, Object condition) {
this.preevaluate(value,condition);
if (value==null) return false;
return evaluateRaw(value.toString(),(String)condition);
}
@Override
public boolean evaluateRaw(String value, String prefix) {
return value.startsWith(prefix.trim());
}
@Override
public boolean isValidCondition(Object condition) {
return condition != null && condition instanceof String;
}
}, | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Text.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.