Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
158 |
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
public sun.misc.Unsafe run() throws Exception {
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
for (java.lang.reflect.Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x))
return k.cast(x);
}
throw new NoSuchFieldError("the Unsafe");
}});
| 0true
|
src_main_java_jsr166y_ConcurrentLinkedDeque.java
|
972 |
private class TransportHandler extends BaseTransportRequestHandler<Request> {
@Override
public Request newInstance() {
return newRequest();
}
@Override
public void messageReceived(final Request request, final TransportChannel channel) throws Exception {
request.listenerThreaded(false);
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response response) {
TransportResponseOptions options = TransportResponseOptions.options().withCompress(transportCompress());
try {
channel.sendResponse(response, options);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response", e);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public String toString() {
return transportAction;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_nodes_TransportNodesOperationAction.java
|
826 |
public class ReduceSearchPhaseException extends SearchPhaseExecutionException {
public ReduceSearchPhaseException(String phaseName, String msg, ShardSearchFailure[] shardFailures) {
super(phaseName, "[reduce] " + msg, shardFailures);
}
public ReduceSearchPhaseException(String phaseName, String msg, Throwable cause, ShardSearchFailure[] shardFailures) {
super(phaseName, "[reduce] " + msg, cause, shardFailures);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_search_ReduceSearchPhaseException.java
|
438 |
public static class Counts implements Streamable, ToXContent {
int total;
int masterOnly;
int dataOnly;
int masterData;
int client;
public void addNodeInfo(NodeInfo nodeInfo) {
total++;
DiscoveryNode node = nodeInfo.getNode();
if (node.masterNode()) {
if (node.dataNode()) {
masterData++;
} else {
masterOnly++;
}
} else if (node.dataNode()) {
dataOnly++;
} else if (node.clientNode()) {
client++;
}
}
public int getTotal() {
return total;
}
public int getMasterOnly() {
return masterOnly;
}
public int getDataOnly() {
return dataOnly;
}
public int getMasterData() {
return masterData;
}
public int getClient() {
return client;
}
public static Counts readCounts(StreamInput in) throws IOException {
Counts c = new Counts();
c.readFrom(in);
return c;
}
@Override
public void readFrom(StreamInput in) throws IOException {
total = in.readVInt();
masterOnly = in.readVInt();
dataOnly = in.readVInt();
masterData = in.readVInt();
client = in.readVInt();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(total);
out.writeVInt(masterOnly);
out.writeVInt(dataOnly);
out.writeVInt(masterData);
out.writeVInt(client);
}
static final class Fields {
static final XContentBuilderString TOTAL = new XContentBuilderString("total");
static final XContentBuilderString MASTER_ONLY = new XContentBuilderString("master_only");
static final XContentBuilderString DATA_ONLY = new XContentBuilderString("data_only");
static final XContentBuilderString MASTER_DATA = new XContentBuilderString("master_data");
static final XContentBuilderString CLIENT = new XContentBuilderString("client");
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.field(Fields.TOTAL, total);
builder.field(Fields.MASTER_ONLY, masterOnly);
builder.field(Fields.DATA_ONLY, dataOnly);
builder.field(Fields.MASTER_DATA, masterData);
builder.field(Fields.CLIENT, client);
return builder;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsNodes.java
|
748 |
public class PlotSettingsControlPanel extends JPanel {
private static final long serialVersionUID = 6158825155688815494L;
// Access bundle file where externalized strings are defined.
private static final ResourceBundle BUNDLE =
ResourceBundle.getBundle(PlotSettingsControlPanel.class.getName().substring(0,
PlotSettingsControlPanel.class.getName().lastIndexOf("."))+".Bundle");
private final static Logger logger = LoggerFactory.getLogger(PlotSettingsControlPanel.class);
private static final String MANUAL_LABEL = BUNDLE.getString("Manual.label");
private static final int INTERCONTROL_HORIZONTAL_SPACING = 0;
private static final int INDENTATION_SEMI_FIXED_CHECKBOX = 16;
private static final int NONTIME_TITLE_SPACING = 0;
private static final int Y_SPAN_SPACING = 50;
private static final int INNER_PADDING = 5;
private static final int INNER_PADDING_TOP = 5;
private static final int X_AXIS_TYPE_VERTICAL_SPACING = 2;
private static final Border TOP_PADDED_MARGINS = BorderFactory.createEmptyBorder(5, 0, 0, 0);
private static final Border BOTTOM_PADDED_MARGINS = BorderFactory.createEmptyBorder(0, 0, 2, 0);
private static final int BEHAVIOR_CELLS_X_PADDING = 18;
private static final Border CONTROL_PANEL_MARGINS = BorderFactory.createEmptyBorder(INNER_PADDING_TOP, INNER_PADDING, INNER_PADDING, INNER_PADDING);
private static final Border SETUP_AND_BEHAVIOR_MARGINS = BorderFactory.createEmptyBorder(0, INNER_PADDING, INNER_PADDING, INNER_PADDING);
// Stabilize width of panel on left of the static plot image
private static final Dimension Y_AXIS_BUTTONS_PANEL_PREFERRED_SIZE = new Dimension(250, 0);
private static final Double NONTIME_AXIS_SPAN_INIT_VALUE = Double.valueOf(30);
private static final int JTEXTFIELD_COLS = 8;
private static final int NUMERIC_TEXTFIELD_COLS1 = 12;
private static final DecimalFormat nonTimePaddingFormat = new DecimalFormat("###.###");
private static final DecimalFormat timePaddingFormat = new DecimalFormat("##.###");
private static final String DATE_FORMAT = "D/HH:mm:ss";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
static GregorianCalendar ZERO_TIME_SPAN_CALENDAR = new GregorianCalendar();
static {
ZERO_TIME_SPAN_CALENDAR.set(Calendar.DAY_OF_YEAR, 1);
ZERO_TIME_SPAN_CALENDAR.set(Calendar.HOUR_OF_DAY, 0);
ZERO_TIME_SPAN_CALENDAR.set(Calendar.MINUTE, 0);
ZERO_TIME_SPAN_CALENDAR.set(Calendar.SECOND, 0);
}
private static Date ZERO_TIME_SPAN_DATE = new Date();
static {
// Sets value to current Year and time zone
GregorianCalendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
ZERO_TIME_SPAN_DATE.setTime(cal.getTimeInMillis());
}
// Space between paired controls (e.g., label followed by text field)
private static final int SPACE_BETWEEN_ROW_ITEMS = 3;
private static final Color OK_PANEL_BACKGROUND_COLOR = LafColor.WINDOW_BORDER.darker();
private static final int PADDING_COLUMNS = 3;
// Maintain link to the plot view this panel is supporting.
private PlotViewManifestation plotViewManifestion;
// Maintain link to the controller this panel is calling to persist setting and create the plot
PlotSettingController controller;
// Non-Time Axis Maximums panel
NonTimeAxisMaximumsPanel nonTimeAxisMaximumsPanel;
// Non-Time Axis Minimums panel
NonTimeAxisMinimumsPanel nonTimeAxisMinimumsPanel;
//Time Axis Minimums panel
public TimeAxisMinimumsPanel timeAxisMinimumsPanel;
//Time Axis Maximums panel
public TimeAxisMaximumsPanel timeAxisMaximumsPanel;
// Top panel controls: Manipulate controls around static plot image
private JComboBox timeDropdown;
JRadioButton xAxisAsTimeRadioButton;
JRadioButton yAxisAsTimeRadioButton;
private JRadioButton yMaxAtTop;
private JRadioButton yMaxAtBottom;
private JRadioButton xMaxAtRight;
private JRadioButton xMaxAtLeft;
private JCheckBox groupByCollection;
//=========================================================================
/*
* X Axis panels
*/
XAxisSpanCluster xAxisSpanCluster;
XAxisAdjacentPanel xAxisAdjacentPanel;
// Join minimums and maximums panels
XAxisButtonsPanel xAxisButtonsPanel;
JLabel xMinLabel;
JLabel xMaxLabel;
private JLabel xAxisType;
//=========================================================================
/*
* Y Axis panels
*/
YMaximumsPlusPanel yMaximumsPlusPanel;
YAxisSpanPanel yAxisSpanPanel;
YMinimumsPlusPanel yMinimumsPlusPanel;
private YAxisButtonsPanel yAxisButtonsPanel;
private JLabel yAxisType;
/*
* Time Axis fields
*/
JRadioButton timeAxisMaxAuto;
ParenthesizedTimeLabel timeAxisMaxAutoValue;
JRadioButton timeAxisMaxManual;
TimeTextField timeAxisMaxManualValue;
JRadioButton timeAxisMinAuto;
ParenthesizedTimeLabel timeAxisMinAutoValue;
JRadioButton timeAxisMinManual;
TimeTextField timeAxisMinManualValue;
TimeSpanTextField timeSpanValue;
public JRadioButton timeAxisMinCurrent;
public JRadioButton timeAxisMaxCurrent;
public ParenthesizedTimeLabel timeAxisMinCurrentValue;
public ParenthesizedTimeLabel timeAxisMaxCurrentValue;
/*
* Non-time Axis fields
*/
JRadioButton nonTimeAxisMaxCurrent;
ParenthesizedNumericLabel nonTimeAxisMaxCurrentValue;
JRadioButton nonTimeAxisMaxManual;
NumericTextField nonTimeAxisMaxManualValue;
JRadioButton nonTimeAxisMaxAutoAdjust;
ParenthesizedNumericLabel nonTimeAxisMaxAutoAdjustValue;
JRadioButton nonTimeAxisMinCurrent;
ParenthesizedNumericLabel nonTimeAxisMinCurrentValue;
JRadioButton nonTimeAxisMinManual;
NumericTextField nonTimeAxisMinManualValue;
JRadioButton nonTimeAxisMinAutoAdjust;
ParenthesizedNumericLabel nonTimeAxisMinAutoAdjustValue;
NumericTextField nonTimeSpanValue;
/*
* Plot Behavior panel controls
*/
JRadioButton nonTimeMinAutoAdjustMode;
JRadioButton nonTimeMaxAutoAdjustMode;
JRadioButton nonTimeMinFixedMode;
JRadioButton nonTimeMaxFixedMode;
JCheckBox nonTimeMinSemiFixedMode;
JCheckBox nonTimeMaxSemiFixedMode;
JTextField nonTimeMinPadding;
JTextField nonTimeMaxPadding;
JCheckBox pinTimeAxis;
JRadioButton timeJumpMode;
JRadioButton timeScrunchMode;
JTextField timeJumpPadding;
JTextField timeScrunchPadding;
/*
* Plot line setup panel controls
*/
private JLabel drawLabel;
private JRadioButton linesOnly;
private JRadioButton markersAndLines;
private JRadioButton markersOnly;
private JLabel connectionLineTypeLabel;
private JRadioButton direct;
private JRadioButton step;
private StillPlotImagePanel imagePanel;
private JLabel behaviorTimeAxisLetter;
private JLabel behaviorNonTimeAxisLetter;
private GregorianCalendar recycledCalendarA = new GregorianCalendar();
private GregorianCalendar recycledCalendarB = new GregorianCalendar();
private JButton okButton;
private JButton resetButton;
// Saved Settings of Plot Settings Panel controls. Used to affect Apply and Reset buttons
private Object ssWhichAxisAsTime;
private Object ssXMaxAtWhich;
private Object ssYMaxAtWhich;
private Object ssTimeMin;
private Object ssTimeMax;
private Object ssNonTimeMin;
private Object ssNonTimeMax;
private Object ssTimeAxisMode;
private Object ssPinTimeAxis;
private List<JToggleButton> ssNonTimeMinAxisMode = new ArrayList<JToggleButton>(2);
private List<JToggleButton> ssNonTimeMaxAxisMode = new ArrayList<JToggleButton>(2);
private String ssNonTimeMinPadding;
private String ssNonTimeMaxPadding;
private String ssTimeAxisJumpMaxPadding;
private String ssTimeAxisScrunchMaxPadding;
private Object ssDraw;
private Object ssConnectionLineType;
// Initialize this to avoid nulls on persistence
private long ssTimeMinManualValue = 0L;
private long ssTimeMaxManualValue = 0L;
private String ssNonTimeMinManualValue = "0.0";
private String ssNonTimeMaxManualValue = "1.0";
private boolean timeMinManualHasBeenSelected = false;
private boolean timeMaxManualHasBeenSelected = false;
private boolean ssGroupByCollection = false;
//===================================================================================
public static class CalendarDump {
public static String dumpDateAndTime(GregorianCalendar calendar) {
StringBuilder buffer = new StringBuilder();
buffer.append(calendar.get(Calendar.YEAR) + " - ");
buffer.append(calendar.get(Calendar.DAY_OF_YEAR) + "/");
buffer.append(calendar.get(Calendar.HOUR_OF_DAY) + ":");
buffer.append(calendar.get(Calendar.MINUTE) + ":");
buffer.append(calendar.get(Calendar.SECOND));
buffer.append(", Zone " + (calendar.get(Calendar.ZONE_OFFSET) / (3600 * 1000)));
return buffer.toString();
}
public static String dumpMillis(long timeInMillis) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(timeInMillis);
return dumpDateAndTime(cal);
}
}
class ParenthesizedTimeLabel extends JLabel {
private static final long serialVersionUID = -6004293775277749905L;
private GregorianCalendar timeInMillis;
private JRadioButton companionButton;
public ParenthesizedTimeLabel(JRadioButton button) {
companionButton = button;
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
companionButton.setSelected(true);
companionButton.requestFocusInWindow();
updateMainButtons();
}
});
}
public void setTime(GregorianCalendar inputTime) {
timeInMillis = inputTime;
setText("(" + dateFormat.format(inputTime.getTime()) + ")");
}
public GregorianCalendar getCalendar() {
return timeInMillis;
}
public long getTimeInMillis() {
return timeInMillis.getTimeInMillis();
}
public String getSavedTime() {
return CalendarDump.dumpDateAndTime(timeInMillis);
}
public int getSecond() {
return timeInMillis.get(Calendar.SECOND);
}
public int getMinute() {
return timeInMillis.get(Calendar.MINUTE);
}
public int getHourOfDay() {
return timeInMillis.get(Calendar.HOUR_OF_DAY);
}
}
class ParenthesizedNumericLabel extends JLabel {
private static final long serialVersionUID = 3403375470853249483L;
private JRadioButton companionButton;
public ParenthesizedNumericLabel(JRadioButton button) {
companionButton = button;
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
companionButton.setSelected(true);
companionButton.requestFocusInWindow();
updateMainButtons();
}
});
}
public Double getValue() {
String data = getText();
if (data == null) {
return null;
}
if (data.length() < 3) {
logger.error("Numeric label in plot settings contained invalid content [" + data + "]");
return null;
}
Double result = null;
try {
result = Double.parseDouble(data.substring(1, data.length() - 1));
} catch(NumberFormatException e) {
logger.error("Could not parse numeric value from ["+ data.substring(1, data.length() - 1) + "]");
}
return result;
}
public void setValue(Double input) {
String formatNum = nonTimePaddingFormat.format(input);
if (formatNum.equals("0"))
formatNum = "0.0";
if (formatNum.equals("1"))
formatNum = "1.0";
setText("(" + formatNum + ")");
}
}
/*
* Focus listener for the Time axis Manual and Span fields
*/
class TimeFieldFocusListener extends FocusAdapter {
// This class can be used with a null button
private JRadioButton companionButton;
public TimeFieldFocusListener(JRadioButton assocButton) {
companionButton = assocButton;
}
@Override
public void focusGained(FocusEvent e) {
if (e.isTemporary())
return;
if (companionButton != null) {
companionButton.setSelected(true);
}
updateMainButtons();
}
@Override
public void focusLost(FocusEvent e) {
if (e.isTemporary())
return;
try {
timeSpanValue.commitEdit();
} catch (ParseException exception) {
exception.printStackTrace();
}
updateTimeAxisControls();
}
}
/*
* Common action listener for the Time axis Mode buttons
*/
class TimeAxisModeListener implements ActionListener {
private JTextComponent companionField;
public TimeAxisModeListener(JTextComponent field) {
companionField = field;
}
@Override
public void actionPerformed(ActionEvent e) {
updateMainButtons();
String content = companionField.getText();
companionField.requestFocusInWindow();
companionField.setSelectionStart(0);
if (content != null) {
companionField.setSelectionEnd(content.length());
}
}
}
/*
* Focus listener for the Time Padding fields
*/
class TimePaddingFocusListener extends FocusAdapter {
@Override
public void focusLost(FocusEvent e) {
if (e.isTemporary())
return;
updateTimeAxisControls();
}
}
class NonTimeFieldFocusListener extends FocusAdapter {
private JRadioButton companionButton;
public NonTimeFieldFocusListener(JRadioButton assocButton) {
companionButton = assocButton;
}
@Override
public void focusGained(FocusEvent e) {
if (e.isTemporary())
return;
companionButton.setSelected(true);
updateNonTimeAxisControls();
}
@Override
public void focusLost(FocusEvent e) {
if (e.isTemporary())
return;
updateNonTimeAxisControls();
}
}
/*
* Guide to the inner classes implementing the movable panels next to the static plot image
*
* XAxisAdjacentPanel - Narrow panel just below X axis
* XAxisSpanCluster - child panel
* XAxisButtonsPanel - Main panel below X axis
* minimumsPanel - child
* maximumsPanel - child
*
* YAxisButtonsPanel - Main panel to left of Y axis
* YMaximumsPlusPanel - child panel
* YSpanPanel - child
* YMinimumsPlusPanel - child
*
*/
// Panel holding the Y Axis Span controls
class YAxisSpanPanel extends JPanel {
private static final long serialVersionUID = 6888092349514542052L;
private JLabel ySpanTag;
private JComponent spanValue;
private Component boxGlue;
private Component boxOnRight;
public YAxisSpanPanel() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
nonTimePaddingFormat.setParseIntegerOnly(false);
nonTimeSpanValue = new NumericTextField(NUMERIC_TEXTFIELD_COLS1, nonTimePaddingFormat);
nonTimeSpanValue.setColumns(JTEXTFIELD_COLS);
nonTimeSpanValue.setValue(NONTIME_AXIS_SPAN_INIT_VALUE);
spanValue = nonTimeSpanValue;
ySpanTag = new JLabel("Span: ");
boxGlue = Box.createHorizontalGlue();
boxOnRight = Box.createRigidArea(new Dimension(Y_SPAN_SPACING, 0));
layoutPanel();
// Instrument
ySpanTag.setName("ySpanTag");
}
void layoutPanel() {
removeAll();
add(boxGlue);
add(ySpanTag);
add(spanValue);
add(boxOnRight);
}
void setSpanField(JComponent field) {
spanValue = field;
layoutPanel();
}
}
// Panel holding the combined "Min" label and Y Axis minimums panel
class YMinimumsPlusPanel extends JPanel {
private static final long serialVersionUID = 2995723041366974233L;
private JPanel coreMinimumsPanel;
private JLabel minJLabel = new JLabel("Min");
public YMinimumsPlusPanel() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
minJLabel.setAlignmentY(Component.BOTTOM_ALIGNMENT);
minJLabel.setFont(minJLabel.getFont().deriveFont(Font.BOLD));
nonTimeAxisMinimumsPanel = new NonTimeAxisMinimumsPanel();
nonTimeAxisMinimumsPanel.setAlignmentY(Component.BOTTOM_ALIGNMENT);
minJLabel.setAlignmentY(Component.BOTTOM_ALIGNMENT);
add(nonTimeAxisMinimumsPanel);
add(minJLabel);
// Instrument
minJLabel.setName("minJLabel");
}
public void setPanel(JPanel minPanel) {
coreMinimumsPanel = minPanel;
removeAll();
add(coreMinimumsPanel);
add(minJLabel);
revalidate();
}
public void setAxisTagAlignment(float componentAlignment) {
coreMinimumsPanel.setAlignmentY(componentAlignment);
minJLabel.setAlignmentY(componentAlignment);
}
}
// Panel holding the combined "Max" label and Y Axis maximums panel
class YMaximumsPlusPanel extends JPanel {
private static final long serialVersionUID = -7611052255395258026L;
private JPanel coreMaximumsPanel;
private JLabel maxJLabel = new JLabel("Max");
public YMaximumsPlusPanel() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
maxJLabel.setAlignmentY(Component.TOP_ALIGNMENT);
maxJLabel.setFont(maxJLabel.getFont().deriveFont(Font.BOLD));
nonTimeAxisMaximumsPanel = new NonTimeAxisMaximumsPanel();
nonTimeAxisMaximumsPanel.setAlignmentY(Component.TOP_ALIGNMENT);
maxJLabel.setAlignmentY(Component.TOP_ALIGNMENT);
add(nonTimeAxisMaximumsPanel);
add(maxJLabel);
// Instrument
maxJLabel.setName("maxJLabel");
}
public void setPanel(JPanel maxPanel) {
coreMaximumsPanel = maxPanel;
removeAll();
add(coreMaximumsPanel);
add(maxJLabel);
revalidate();
}
public void setAxisTagAlignment(float componentAlignment) {
coreMaximumsPanel.setAlignmentY(componentAlignment);
maxJLabel.setAlignmentY(componentAlignment);
revalidate();
}
}
// Panel holding the Time Axis minimum controls
class TimeAxisMinimumsPanel extends JPanel {
private static final long serialVersionUID = 3651502189841560982L;
public TimeAxisMinimumsPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
timeAxisMinCurrent = new JRadioButton(BUNDLE.getString("Currentmin.label"));
timeAxisMinCurrentValue = new ParenthesizedTimeLabel(timeAxisMinCurrent);
timeAxisMinCurrentValue.setTime(new GregorianCalendar());
timeAxisMinManual = new JRadioButton(MANUAL_LABEL);
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter("###/##:##:##");
formatter.setPlaceholderCharacter('0');
} catch (ParseException e) {
logger.error("Parse error in creating time field", e);
}
timeAxisMinManualValue = new TimeTextField(formatter);
timeAxisMinAuto = new JRadioButton(BUNDLE.getString("Now.label"));
timeAxisMinAutoValue = new ParenthesizedTimeLabel(timeAxisMinAuto);
timeAxisMinAutoValue.setTime(new GregorianCalendar());
timeAxisMinAutoValue.setText("should update every second");
timeAxisMinAuto.setSelected(true);
JPanel yAxisMinRow1 = createMultiItemRow(timeAxisMinCurrent, timeAxisMinCurrentValue);
JPanel yAxisMinRow2 = createMultiItemRow(timeAxisMinManual, timeAxisMinManualValue);
JPanel yAxisMinRow3 = createMultiItemRow(timeAxisMinAuto, timeAxisMinAutoValue);
add(yAxisMinRow1);
add(yAxisMinRow2);
add(yAxisMinRow3);
add(Box.createVerticalGlue());
ButtonGroup minButtonGroup = new ButtonGroup();
minButtonGroup.add(timeAxisMinCurrent);
minButtonGroup.add(timeAxisMinManual);
minButtonGroup.add(timeAxisMinAuto);
timeAxisMinAuto.setToolTipText(BUNDLE.getString("TimeAxisMins.label"));
}
}
// Panel holding the Time Axis maximum controls
class TimeAxisMaximumsPanel extends JPanel {
private static final long serialVersionUID = 6105026690366452860L;
public TimeAxisMaximumsPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
timeAxisMaxCurrent = new JRadioButton(BUNDLE.getString("CurrentMax.label"));
timeAxisMaxCurrentValue = new ParenthesizedTimeLabel(timeAxisMaxCurrent);
GregorianCalendar initCalendar = new GregorianCalendar();
initCalendar.add(Calendar.MINUTE, 10);
timeAxisMaxCurrentValue.setTime(initCalendar);
timeAxisMaxManual = new JRadioButton(MANUAL_LABEL);
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter("###/##:##:##");
formatter.setPlaceholderCharacter('0');
} catch (ParseException e) {
e.printStackTrace();
}
timeAxisMaxManualValue = new TimeTextField(formatter);
initCalendar.setTimeInMillis(timeAxisMaxManualValue.getValueInMillis() + 1000);
timeAxisMaxManualValue.setTime(initCalendar);
timeAxisMaxAuto = new JRadioButton(BUNDLE.getString("MinPlusSpan.label"));
timeAxisMaxAutoValue = new ParenthesizedTimeLabel(timeAxisMaxAuto);
timeAxisMaxAutoValue.setTime(initCalendar);
JPanel yAxisMaxRow1 = createMultiItemRow(timeAxisMaxCurrent, timeAxisMaxCurrentValue);
JPanel yAxisMaxRow2 = createMultiItemRow(timeAxisMaxManual, timeAxisMaxManualValue);
JPanel yAxisMaxRow3 = createMultiItemRow(timeAxisMaxAuto, timeAxisMaxAutoValue);
timeAxisMaxAuto.setSelected(true);
add(yAxisMaxRow1);
add(yAxisMaxRow2);
add(yAxisMaxRow3);
add(Box.createVerticalGlue());
ButtonGroup maxButtonGroup = new ButtonGroup();
maxButtonGroup.add(timeAxisMaxCurrent);
maxButtonGroup.add(timeAxisMaxManual);
maxButtonGroup.add(timeAxisMaxAuto);
timeAxisMaxAuto.setToolTipText(BUNDLE.getString("TimeAxisMins.label"));
}
}
// Panel holding the min, max and span controls
class YAxisButtonsPanel extends JPanel {
private static final long serialVersionUID = 3430980575280458813L;
private GridBagConstraints gbcForMax;
private GridBagConstraints gbcForMin;
private GridBagConstraints gbcForSpan;
public YAxisButtonsPanel() {
setLayout(new GridBagLayout());
setPreferredSize(Y_AXIS_BUTTONS_PANEL_PREFERRED_SIZE);
// Align radio buttons for Max and Min on the left
gbcForMax = new GridBagConstraints();
gbcForMax.gridx = 0;
gbcForMax.fill = GridBagConstraints.HORIZONTAL;
gbcForMax.anchor = GridBagConstraints.WEST;
gbcForMax.weightx = 1;
gbcForMax.weighty = 0;
gbcForMin = new GridBagConstraints();
gbcForMin.gridx = 0;
gbcForMin.fill = GridBagConstraints.HORIZONTAL;
gbcForMin.anchor = GridBagConstraints.WEST;
gbcForMin.weightx = 1;
gbcForMin.weighty = 0;
// Align Span controls on the right
gbcForSpan = new GridBagConstraints();
gbcForSpan.gridx = 0;
// Let fill default to NONE and weightx default to 0
gbcForSpan.anchor = GridBagConstraints.EAST;
gbcForSpan.weighty = 1;
}
public void setNormalOrder(boolean normalDirection) {
removeAll();
if (normalDirection) {
gbcForMax.gridy = 0;
gbcForMax.anchor = GridBagConstraints.NORTHWEST;
add(yMaximumsPlusPanel, gbcForMax);
gbcForSpan.gridy = 1;
add(yAxisSpanPanel, gbcForSpan);
gbcForMin.gridy = 2;
gbcForMin.anchor = GridBagConstraints.SOUTHWEST;
add(yMinimumsPlusPanel, gbcForMin);
yMaximumsPlusPanel.setAxisTagAlignment(Component.TOP_ALIGNMENT);
yMinimumsPlusPanel.setAxisTagAlignment(Component.BOTTOM_ALIGNMENT);
} else {
gbcForMin.gridy = 0;
gbcForMin.anchor = GridBagConstraints.NORTHWEST;
add(yMinimumsPlusPanel, gbcForMin);
gbcForSpan.gridy = 1;
add(yAxisSpanPanel, gbcForSpan);
gbcForMax.gridy = 2;
gbcForMax.anchor = GridBagConstraints.SOUTHWEST;
add(yMaximumsPlusPanel, gbcForMax);
yMaximumsPlusPanel.setAxisTagAlignment(Component.BOTTOM_ALIGNMENT);
yMinimumsPlusPanel.setAxisTagAlignment(Component.TOP_ALIGNMENT);
}
revalidate();
}
public void insertMinMaxPanels(JPanel minPanel, JPanel maxPanel) {
yMinimumsPlusPanel.setPanel(minPanel);
yMaximumsPlusPanel.setPanel(maxPanel);
revalidate();
}
}
// Panel holding the X axis Minimums panel and Maximums panel
class XAxisButtonsPanel extends JPanel {
private static final long serialVersionUID = -5671943216161507045L;
private JPanel minimumsPanel;
private JPanel maximumsPanel;
private GridBagConstraints gbcLeft;
private GridBagConstraints gbcRight;
public XAxisButtonsPanel() {
this.setLayout(new GridBagLayout());
gbcLeft = new GridBagConstraints();
gbcLeft.gridx = 0;
gbcLeft.gridy = 0;
gbcLeft.fill = GridBagConstraints.BOTH;
gbcLeft.anchor = GridBagConstraints.WEST;
gbcLeft.weightx = 1;
gbcRight = new GridBagConstraints();
gbcRight.gridx = 1;
gbcRight.gridy = 0;
gbcRight.fill = GridBagConstraints.BOTH;
gbcLeft.anchor = GridBagConstraints.EAST;
gbcRight.weightx = 1;
}
public void setNormalOrder(boolean normalDirection) {
removeAll();
if (normalDirection) {
add(minimumsPanel, gbcLeft);
add(maximumsPanel, gbcRight);
} else {
add(maximumsPanel, gbcLeft);
add(minimumsPanel, gbcRight);
}
revalidate();
}
public void insertMinMaxPanels(JPanel minPanel, JPanel maxPanel) {
minimumsPanel = minPanel;
maximumsPanel = maxPanel;
}
}
// Non-time axis Minimums panel
class NonTimeAxisMinimumsPanel extends JPanel {
private static final long serialVersionUID = -2619634570876465687L;
public NonTimeAxisMinimumsPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
nonTimeAxisMinCurrent = new JRadioButton(BUNDLE.getString("CurrentSmallestDatum.label"), true);
nonTimeAxisMinCurrentValue = new ParenthesizedNumericLabel(nonTimeAxisMinCurrent);
nonTimeAxisMinCurrentValue.setValue(0.0);
nonTimeAxisMinManual = new JRadioButton(MANUAL_LABEL, false);
nonTimeAxisMinManualValue = new NumericTextField(NUMERIC_TEXTFIELD_COLS1, nonTimePaddingFormat);
nonTimeAxisMinManualValue.setColumns(JTEXTFIELD_COLS);
nonTimeAxisMinManualValue.setText(nonTimeAxisMinCurrentValue.getValue().toString());
nonTimeAxisMinAutoAdjust = new JRadioButton(BUNDLE.getString("MaxMinusSpan.label"), false);
nonTimeAxisMinAutoAdjustValue = new ParenthesizedNumericLabel(nonTimeAxisMinAutoAdjust);
nonTimeAxisMinAutoAdjustValue.setValue(0.0);
JPanel xAxisMinRow1 = createMultiItemRow(nonTimeAxisMinCurrent, nonTimeAxisMinCurrentValue);
JPanel xAxisMinRow2 = createMultiItemRow(nonTimeAxisMinManual, nonTimeAxisMinManualValue);
JPanel xAxisMinRow3 = createMultiItemRow(nonTimeAxisMinAutoAdjust, nonTimeAxisMinAutoAdjustValue);
ButtonGroup minimumsGroup = new ButtonGroup();
minimumsGroup.add(nonTimeAxisMinCurrent);
minimumsGroup.add(nonTimeAxisMinManual);
minimumsGroup.add(nonTimeAxisMinAutoAdjust);
// Layout
add(xAxisMinRow1);
add(xAxisMinRow2);
add(xAxisMinRow3);
nonTimeAxisMinCurrent.setToolTipText(BUNDLE.getString("NonTimeAxisMin.label"));
// Instrument
xAxisMinRow1.setName("xAxisMinRow1");
xAxisMinRow2.setName("xAxisMinRow2");
xAxisMinRow3.setName("xAxisMinRow3");
}
}
// Non-time axis Maximums panel
class NonTimeAxisMaximumsPanel extends JPanel {
private static final long serialVersionUID = -768623994853270825L;
public NonTimeAxisMaximumsPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
nonTimeAxisMaxCurrent = new JRadioButton(BUNDLE.getString("CurrentLargestDatum.label"), true);
nonTimeAxisMaxCurrentValue = new ParenthesizedNumericLabel(nonTimeAxisMaxCurrent);
nonTimeAxisMaxCurrentValue.setValue(1.0);
nonTimeAxisMaxManual = new JRadioButton(MANUAL_LABEL, false);
DecimalFormat format = new DecimalFormat("###.######");
format.setParseIntegerOnly(false);
nonTimeAxisMaxManualValue = new NumericTextField(NUMERIC_TEXTFIELD_COLS1, format);
nonTimeAxisMaxManualValue.setColumns(JTEXTFIELD_COLS);
nonTimeAxisMaxManualValue.setText(nonTimeAxisMaxCurrentValue.getValue().toString());
nonTimeAxisMaxAutoAdjust = new JRadioButton(BUNDLE.getString("MinPlusSpan.label"), false);
nonTimeAxisMaxAutoAdjustValue = new ParenthesizedNumericLabel(nonTimeAxisMaxAutoAdjust);
nonTimeAxisMaxAutoAdjustValue.setValue(1.0);
JPanel xAxisMaxRow1 = createMultiItemRow(nonTimeAxisMaxCurrent, nonTimeAxisMaxCurrentValue);
JPanel xAxisMaxRow2 = createMultiItemRow(nonTimeAxisMaxManual, nonTimeAxisMaxManualValue);
JPanel xAxisMaxRow3 = createMultiItemRow(nonTimeAxisMaxAutoAdjust, nonTimeAxisMaxAutoAdjustValue);
ButtonGroup maximumsGroup = new ButtonGroup();
maximumsGroup.add(nonTimeAxisMaxManual);
maximumsGroup.add(nonTimeAxisMaxCurrent);
maximumsGroup.add(nonTimeAxisMaxAutoAdjust);
// Layout
add(xAxisMaxRow1);
add(xAxisMaxRow2);
add(xAxisMaxRow3);
nonTimeAxisMaxCurrent.setToolTipText(BUNDLE.getString("NonTimeAxisMax.label"));
// Instrument
xAxisMaxRow1.setName("xAxisMaxRow1");
xAxisMaxRow2.setName("xAxisMaxRow2");
xAxisMaxRow3.setName("xAxisMaxRow3");
}
}
// Panel holding X axis tags for Min and Max, and the Span field
class XAxisAdjacentPanel extends JPanel {
private static final long serialVersionUID = 4160271246055659710L;
GridBagConstraints gbcLeft = new GridBagConstraints();
GridBagConstraints gbcRight = new GridBagConstraints();
GridBagConstraints gbcCenter = new GridBagConstraints();
public XAxisAdjacentPanel() {
this.setLayout(new GridBagLayout());
xMinLabel = new JLabel(BUNDLE.getString("Min.label"));
xMaxLabel = new JLabel(BUNDLE.getString("Max.label"));
xMinLabel.setFont(xMinLabel.getFont().deriveFont(Font.BOLD));
xMaxLabel.setFont(xMaxLabel.getFont().deriveFont(Font.BOLD));
setBorder(BOTTOM_PADDED_MARGINS);
gbcLeft.anchor = GridBagConstraints.WEST;
gbcLeft.gridx = 0;
gbcLeft.gridy = 0;
gbcLeft.weightx = 0.5;
gbcCenter.anchor = GridBagConstraints.NORTH;
gbcCenter.gridx = 1;
gbcCenter.gridy = 0;
gbcRight.anchor = GridBagConstraints.EAST;
gbcRight.gridx = 2;
gbcRight.gridy = 0;
gbcRight.weightx = 0.5;
}
public void setNormalOrder(boolean normalDirection) {
removeAll();
if (normalDirection) {
add(xMinLabel, gbcLeft);
add(xAxisSpanCluster, gbcCenter);
add(xMaxLabel, gbcRight);
} else {
add(xMaxLabel, gbcLeft);
add(xAxisSpanCluster, gbcCenter);
add(xMinLabel, gbcRight);
}
revalidate();
}
}
// Panel holding X axis Span controls
class XAxisSpanCluster extends JPanel {
private static final long serialVersionUID = -3947426156383446643L;
private JComponent spanValue;
private JLabel spanTag;
private Component boxStrut;
public XAxisSpanCluster() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
spanTag = new JLabel("Span: ");
// Create a text field with a ddd/hh:mm:ss format for time
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter("###/##:##:##");
formatter.setPlaceholderCharacter('0');
} catch (ParseException e) {
logger.error("Error in creating a mask formatter", e);
}
timeSpanValue = new TimeSpanTextField(formatter);
spanValue = timeSpanValue;
boxStrut = Box.createHorizontalStrut(INTERCONTROL_HORIZONTAL_SPACING);
layoutPanel();
// Instrument
spanTag.setName("spanTag");
}
void layoutPanel() {
removeAll();
add(spanTag);
add(boxStrut);
add(spanValue);
}
void setSpanField(JComponent field) {
spanValue = field;
layoutPanel();
}
}
// Panel that holds the still image of a plot in the Initial Settings area
public class StillPlotImagePanel extends JPanel {
private static final long serialVersionUID = 8645833372400367908L;
private JLabel timeOnXAxisNormalPicture;
private JLabel timeOnYAxisNormalPicture;
private JLabel timeOnXAxisReversedPicture;
private JLabel timeOnYAxisReversedPicture;
public StillPlotImagePanel() {
timeOnXAxisNormalPicture = new JLabel("", IconLoader.INSTANCE.getIcon(IconLoader.Icons.PLOT_TIME_ON_X_NORMAL), JLabel.CENTER);
timeOnYAxisNormalPicture = new JLabel("", IconLoader.INSTANCE.getIcon(IconLoader.Icons.PLOT_TIME_ON_Y_NORMAL), JLabel.CENTER);
timeOnXAxisReversedPicture = new JLabel("", IconLoader.INSTANCE.getIcon(IconLoader.Icons.PLOT_TIME_ON_X_REVERSED), JLabel.CENTER);
timeOnYAxisReversedPicture = new JLabel("", IconLoader.INSTANCE.getIcon(IconLoader.Icons.PLOT_TIME_ON_Y_REVERSED), JLabel.CENTER);
add(timeOnXAxisNormalPicture); // default
// Instrument
timeOnXAxisNormalPicture.setName("timeOnXAxisNormalPicture");
timeOnYAxisNormalPicture.setName("timeOnYAxisNormalPicture");
timeOnXAxisReversedPicture.setName("timeOnXAxisReversedPicture");
timeOnYAxisReversedPicture.setName("timeOnYAxisReversedPicture");
}
public void setImageToTimeOnXAxis(boolean normalDirection) {
removeAll();
if (normalDirection) {
add(timeOnXAxisNormalPicture);
} else {
add(timeOnXAxisReversedPicture);
}
revalidate();
}
public void setImageToTimeOnYAxis(boolean normalDirection) {
removeAll();
if (normalDirection) {
add(timeOnYAxisNormalPicture);
} else {
add(timeOnYAxisReversedPicture);
}
revalidate();
}
}
/* ================================================
* Main Constructor for Plot Settings Control panel
* ================================================
*/
public PlotSettingsControlPanel(PlotViewManifestation plotMan) {
// This sets the display of date/time fields that use this format object to use GMT
dateFormat.setTimeZone(TimeZone.getTimeZone(PlotConstants.DEFAULT_TIME_ZONE));
// store reference to the plot
plotViewManifestion = plotMan;
// Create controller for this panel.
controller = new PlotSettingController(this);
setLayout(new BorderLayout());
setBorder(CONTROL_PANEL_MARGINS);
addAncestorListener(new AncestorListener () {
@Override
public void ancestorAdded(AncestorEvent event) {
}
@Override
public void ancestorMoved(AncestorEvent event) {
}
@Override
public void ancestorRemoved(AncestorEvent event) {
// this could be changed to use resetButton.doClick();
ActionListener[] resetListeners = resetButton.getActionListeners();
if (resetListeners.length == 1) {
resetListeners[0].actionPerformed(null);
} else {
logger.error("Reset button has unexpected listeners.");
}
}
});
// Assemble the panel contents - two collapsible panels
JPanel overallPanel = new JPanel();
overallPanel.setLayout(new BoxLayout(overallPanel, BoxLayout.Y_AXIS));
JPanel controlsAPanel = new SectionPanel(BUNDLE.getString("PlotSetup.label"), getInitialSetupPanel());
JPanel controlsBPanel = new SectionPanel(BUNDLE.getString("WhenSpaceRunsOut.label"), getPlotBehaviorPanel());
JPanel controlsCPanel = new SectionPanel(BUNDLE.getString("LineSetup.label"), getLineSetupPanel());
overallPanel.add(controlsAPanel);
overallPanel.add(Box.createRigidArea(new Dimension(0, 7)));
overallPanel.add(controlsBPanel);
overallPanel.add(Box.createRigidArea(new Dimension(0, 7)));
overallPanel.add(controlsCPanel);
// Use panels and layouts to achieve desired spacing
JPanel squeezeBox = new JPanel(new BorderLayout());
squeezeBox.add(overallPanel, BorderLayout.NORTH);
PlotControlsLayout controlsLayout = new PlotControlsLayout();
PlotControlsLayout.ResizersScrollPane scroller =
controlsLayout.new ResizersScrollPane(squeezeBox, controlsAPanel, controlsBPanel);
scroller.setBorder(BorderFactory.createEmptyBorder());
JPanel paddableOverallPanel = new JPanel(controlsLayout);
paddableOverallPanel.add(scroller, PlotControlsLayout.MIDDLE);
paddableOverallPanel.add(createApplyButtonPanel(), PlotControlsLayout.LOWER);
add(paddableOverallPanel, BorderLayout.CENTER);
behaviorTimeAxisLetter.setText("X");
behaviorNonTimeAxisLetter.setText("Y");
// Set the initial value of the Time Min Auto value ("Now")
GregorianCalendar nextTime = new GregorianCalendar();
nextTime.setTimeInMillis(plotViewManifestion.getCurrentMCTTime());
nextTime.setTimeZone(TimeZone.getTimeZone(PlotConstants.DEFAULT_TIME_ZONE));
if (nextTime.getTimeInMillis() == 0.0) {
nextTime = plotViewManifestion.getPlot().getMinTime();
nextTime.setTimeZone(TimeZone.getTimeZone(PlotConstants.DEFAULT_TIME_ZONE));
}
timeAxisMinAutoValue.setTime(nextTime);
instrumentNames();
// Initialize state of control panel to match that of the plot.
PlotAbstraction plot = plotViewManifestion.getPlot();
if (plot!=null){
setControlPanelState(plot.getAxisOrientationSetting(),
plot.getXAxisMaximumLocation(),
plot.getYAxisMaximumLocation(),
plot.getTimeAxisSubsequentSetting(),
plot.getNonTimeAxisSubsequentMinSetting(),
plot.getNonTimeAxisSubsequentMaxSetting(),
plot.getNonTimeMax(),
plot.getNonTimeMin(),
plot.getTimeMin(),
plot.getTimeMax(),
plot.getTimePadding(),
plot.getNonTimeMaxPadding(),
plot.getNonTimeMinPadding(),
plot.useOrdinalPositionForSubplots(),
plot.getTimeAxisUserPin().isPinned(),
plot.getPlotLineDraw(),
plot.getPlotLineConnectionType());
}
// Save the panel controls' initial settings to control the Apply and Reset buttons'
// enabled/disabled states.
saveUIControlsSettings();
setupApplyResetListeners();
okButton.setEnabled(false);
refreshDisplay();
}
@SuppressWarnings("serial")
static public class SectionPanel extends JPanel {
public SectionPanel(String titleText, JPanel inputPanel) {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
setBorder(BorderFactory.createTitledBorder(titleText));
add(inputPanel, gbc);
JLabel padding = new JLabel();
gbc.weighty = 1.0;
add(padding, gbc);
}
}
/*
* Take a snapshot of the UI controls' settings. ("ss" = saved setting)
* For button groups, only the selected button needs to be recorded.
* For spinners, the displayed text is recorded.
*/
private void saveUIControlsSettings() {
// Time system drop-down box - currently has only one possible value
// Choice of axis for Time
ssWhichAxisAsTime = findSelectedButton(xAxisAsTimeRadioButton, yAxisAsTimeRadioButton);
// X-axis orientation
ssXMaxAtWhich = findSelectedButton(xMaxAtRight, xMaxAtLeft);
// Y axis orientation
ssYMaxAtWhich = findSelectedButton(yMaxAtTop, yMaxAtBottom);
// Time Axis Minimums
ssTimeMin = findSelectedButton(timeAxisMinCurrent, timeAxisMinManual, timeAxisMinAuto);
// Time Axis Maximums
ssTimeMax = findSelectedButton(timeAxisMaxCurrent, timeAxisMaxManual, timeAxisMaxAuto);
// Non-Time Axis Minimums
ssNonTimeMin = findSelectedButton(nonTimeAxisMinCurrent, nonTimeAxisMinManual, nonTimeAxisMinAutoAdjust);
// Non-Time Axis Maximums
ssNonTimeMax = findSelectedButton(nonTimeAxisMaxCurrent, nonTimeAxisMaxManual, nonTimeAxisMaxAutoAdjust);
// Panel - Plot Behavior When Space Runs Out
// Time Axis Table
ssTimeAxisMode = findSelectedButton(timeJumpMode, timeScrunchMode);
ssTimeAxisJumpMaxPadding = timeJumpPadding.getText();
ssTimeAxisScrunchMaxPadding = timeScrunchPadding.getText();
ssPinTimeAxis = pinTimeAxis.isSelected();
// Non-Time Axis Table
ssNonTimeMinAxisMode = findSelectedButtons(nonTimeMinAutoAdjustMode, nonTimeMinSemiFixedMode, nonTimeMinFixedMode);
ssNonTimeMaxAxisMode = findSelectedButtons(nonTimeMaxAutoAdjustMode, nonTimeMaxSemiFixedMode, nonTimeMaxFixedMode);
ssNonTimeMinPadding = nonTimeMinPadding.getText();
ssNonTimeMaxPadding = nonTimeMaxPadding.getText();
// Time Axis Manual fields
ssTimeMinManualValue = timeAxisMinManualValue.getValueInMillis();
ssTimeMaxManualValue = timeAxisMaxManualValue.getValueInMillis();
// Non-Time Axis Manual fields
ssNonTimeMinManualValue = nonTimeAxisMinManualValue.getText();
ssNonTimeMaxManualValue = nonTimeAxisMaxManualValue.getText();
// stacked plot grouping
ssGroupByCollection = groupByCollection.isSelected();
// Line drawing options
ssDraw = findSelectedButton(linesOnly, markersAndLines, markersOnly);
ssConnectionLineType = findSelectedButton(direct, step);
}
/*
* Does the Plot Settings Control Panel have pending changes ?
* Compare the values in the ss-variables to the current settings
*/
boolean isPanelDirty() {
JToggleButton selectedButton = null;
// Time system dropdown currently has only one possible selection, so no code is needed yet.
// X or Y Axis As Time
selectedButton = findSelectedButton(xAxisAsTimeRadioButton, yAxisAsTimeRadioButton);
if (ssWhichAxisAsTime != selectedButton) {
return true;
}
// X Axis orientation
selectedButton = findSelectedButton(xMaxAtRight, xMaxAtLeft);
if (ssXMaxAtWhich != selectedButton) {
return true;
}
// Y Axis orientation
selectedButton = findSelectedButton(yMaxAtTop, yMaxAtBottom);
if (ssYMaxAtWhich != selectedButton) {
return true;
}
// Time Axis Minimums
selectedButton = findSelectedButton(timeAxisMinCurrent, timeAxisMinManual, timeAxisMinAuto);
if (ssTimeMin != selectedButton) {
return true;
}
// If the Manual setting was initially selected, check if the Manual value changed
// Note that we convert our time value back to a string to avoid differing evaluations of milliseconds
recycledCalendarA.setTimeInMillis(ssTimeMinManualValue);
if ( (ssTimeMin == timeAxisMinManual && ssTimeMin.getClass().isInstance(timeAxisMinManual)) &&
!dateFormat.format(recycledCalendarA.getTime()).equals(timeAxisMinManualValue.getValue()) ){
return true;
}
// Time Axis Maximums
selectedButton = findSelectedButton(timeAxisMaxCurrent, timeAxisMaxManual, timeAxisMaxAuto);
if (ssTimeMax != selectedButton) {
return true;
}
// If the Manual setting was initially selected, check if the Manual value changed
// Note that we convert our time value back to a string to avoid differing evaluations of milliseconds
recycledCalendarA.setTimeInMillis(ssTimeMaxManualValue);
if ( (ssTimeMax == timeAxisMaxManual && ssTimeMax.getClass().isInstance(timeAxisMaxManual)) &&
!dateFormat.format(recycledCalendarA.getTime()).equals(timeAxisMaxManualValue.getValue()) ) {
return true;
}
// Non-Time Axis Minimums
selectedButton = findSelectedButton(nonTimeAxisMinCurrent, nonTimeAxisMinManual, nonTimeAxisMinAutoAdjust);
if (ssNonTimeMin != selectedButton) {
return true;
}
// If the Manual setting was initially selected, check if the Manual value changed
if (ssNonTimeMin == nonTimeAxisMinManual &&
! ssNonTimeMinManualValue.equals(nonTimeAxisMinManualValue.getText())) {
return true;
}
// Non-Time Axis Maximums
selectedButton = findSelectedButton(nonTimeAxisMaxCurrent, nonTimeAxisMaxManual, nonTimeAxisMaxAutoAdjust);
if (ssNonTimeMax != selectedButton) {
return true;
}
// If the Manual setting was initially selected, check if the Manual value changed
if (ssNonTimeMax == nonTimeAxisMaxManual &&
! ssNonTimeMaxManualValue.equals(nonTimeAxisMaxManualValue.getText())) {
return true;
}
// Panel - Plot Behavior When Space Runs Out
// Time Axis Table
selectedButton = findSelectedButton(timeJumpMode, timeScrunchMode);
if (ssTimeAxisMode != selectedButton) {
return true;
}
if (! ssTimeAxisJumpMaxPadding.equals(timeJumpPadding.getText())) {
return true;
}
if (! ssTimeAxisScrunchMaxPadding.equals(timeScrunchPadding.getText())) {
return true;
}
if (!ssPinTimeAxis.equals(pinTimeAxis.isSelected())) {
return true;
}
// Non-Time Axis Table
if (!buttonStateMatch(findSelectedButtons(nonTimeMinAutoAdjustMode, nonTimeMinSemiFixedMode, nonTimeMinFixedMode),
ssNonTimeMinAxisMode)) {
return true;
}
if (!buttonStateMatch(findSelectedButtons(nonTimeMaxAutoAdjustMode, nonTimeMaxSemiFixedMode, nonTimeMaxFixedMode),
ssNonTimeMaxAxisMode)) {
return true;
}
if (! ssNonTimeMinPadding.equals(nonTimeMinPadding.getText())) {
return true;
}
if (! ssNonTimeMaxPadding.equals(nonTimeMaxPadding.getText())) {
return true;
}
if (ssGroupByCollection != groupByCollection.isSelected()) {
return true;
}
// Line Setup panel: Draw options
selectedButton = findSelectedButton(linesOnly, markersAndLines, markersOnly);
if (ssDraw != selectedButton) {
return true;
}
// Line Setup panel: Connection line type options
selectedButton = findSelectedButton(direct, step);
if (ssConnectionLineType != selectedButton) {
return true;
}
return false;
}
private JToggleButton findSelectedButton( JToggleButton... buttons) {
for ( JToggleButton button : buttons) {
if (button.isSelected()) {
return button;
}
}
logger.error("Unexpected, no selected button in subject group in Plot Settings Control Panel.");
return null;
}
static List<JToggleButton> findSelectedButtons( JToggleButton... buttons) {
List<JToggleButton> selectedButtons = new ArrayList<JToggleButton>(2);
for ( JToggleButton button : buttons) {
if (button.isSelected()) {
selectedButtons.add(button);
}
}
return selectedButtons;
}
/**
* Return true if tw
* @param buttonSet1
* @param buttonSet2
* @return
*/
static boolean buttonStateMatch(List<JToggleButton> buttonSet1, List<JToggleButton> buttonSet2) {
return buttonSet1.size() == buttonSet2.size() &&
buttonSet1.containsAll(buttonSet2);
}
/*
* Add listeners to the UI controls to connect the logic for enabling the
* Apply and Reset buttons
*/
private void setupApplyResetListeners() {
timeDropdown.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateMainButtons();
}
});
// Add listener to radio buttons not on the axes
ActionListener buttonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateMainButtons();
}
};
xAxisAsTimeRadioButton.addActionListener(buttonListener);
yAxisAsTimeRadioButton.addActionListener(buttonListener);
xMaxAtRight.addActionListener(buttonListener);
xMaxAtLeft.addActionListener(buttonListener);
yMaxAtTop.addActionListener(buttonListener);
yMaxAtBottom.addActionListener(buttonListener);
timeJumpMode.addActionListener(new TimeAxisModeListener(timeJumpPadding));
timeScrunchMode.addActionListener(new TimeAxisModeListener(timeScrunchPadding));
pinTimeAxis.addActionListener(buttonListener);
nonTimeMinAutoAdjustMode.addActionListener(buttonListener);
nonTimeMinFixedMode.addActionListener(buttonListener);
nonTimeMaxAutoAdjustMode.addActionListener(buttonListener);
nonTimeMaxFixedMode.addActionListener(buttonListener);
// Add listeners to the Time axis buttons
ActionListener timeAxisListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateTimeAxisControls();
}
};
timeAxisMinCurrent.addActionListener(timeAxisListener);
timeAxisMinAuto.addActionListener(timeAxisListener);
timeAxisMaxCurrent.addActionListener(timeAxisListener);
timeAxisMaxAuto.addActionListener(timeAxisListener);
timeAxisMinManual.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timeMinManualHasBeenSelected = true;
updateTimeAxisControls();
}
});
timeAxisMaxManual.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timeMaxManualHasBeenSelected = true;
updateTimeAxisControls();
}
});
// Add listeners to the Non-Time axis buttons
ActionListener nonTimeAxisListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateNonTimeAxisControls();
}
};
nonTimeAxisMinCurrent.addActionListener(nonTimeAxisListener);
nonTimeAxisMinAutoAdjust.addActionListener(nonTimeAxisListener);
nonTimeAxisMaxCurrent.addActionListener(nonTimeAxisListener);
nonTimeAxisMaxAutoAdjust.addActionListener(nonTimeAxisListener);
nonTimeAxisMinManual.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (nonTimeAxisMinManual.isSelected()) {
nonTimeAxisMinManualValue.requestFocusInWindow();
nonTimeAxisMinManualValue.setSelectionStart(0);
String content = nonTimeAxisMinManualValue.getText();
if (content != null) {
nonTimeAxisMinManualValue.setSelectionEnd(content.length());
}
updateNonTimeAxisControls();
}
}
});
nonTimeAxisMaxManual.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (nonTimeAxisMaxManual.isSelected()) {
nonTimeAxisMaxManualValue.requestFocusInWindow();
nonTimeAxisMaxManualValue.setSelectionStart(0);
String content = nonTimeAxisMaxManualValue.getText();
if (content != null) {
nonTimeAxisMaxManualValue.setSelectionEnd(content.length());
}
updateNonTimeAxisControls();
}
}
});
// Add listeners to Non-Time axis text fields
nonTimeSpanValue.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
if (e.isTemporary())
return;
updateNonTimeAxisControls();
}
});
// Add listeners to Time axis text fields
timeAxisMinManualValue.addFocusListener(new TimeFieldFocusListener(timeAxisMinManual) {
@Override
public void focusGained(FocusEvent e) {
timeMinManualHasBeenSelected = true;
super.focusGained(e);
}
});
timeAxisMaxManualValue.addFocusListener(new TimeFieldFocusListener(timeAxisMaxManual) {
@Override
public void focusGained(FocusEvent e) {
timeMaxManualHasBeenSelected = true;
super.focusGained(e);
}
});
timeSpanValue.addFocusListener(new TimeFieldFocusListener(null));
// Plot Behavior section: Add listeners to Padding text fields
timeJumpPadding.addFocusListener(new TimePaddingFocusListener() {
@Override
public void focusGained(FocusEvent e) {
timeJumpMode.setSelected(true);
}
});
timeScrunchPadding.addFocusListener(new TimePaddingFocusListener() {
@Override
public void focusGained(FocusEvent e) {
timeScrunchMode.setSelected(true);
}
});
FocusListener nontimePaddingListener = new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
if (e.isTemporary())
return;
updateNonTimeAxisControls();
}
};
nonTimeMinPadding.addFocusListener(nontimePaddingListener);
nonTimeMaxPadding.addFocusListener(nontimePaddingListener);
}
// Apply and Reset buttons at bottom of the Plot Settings Control Panel
private JPanel createApplyButtonPanel() {
okButton = new JButton(BUNDLE.getString("Apply.label"));
resetButton = new JButton(BUNDLE.getString("Reset.label"));
okButton.setEnabled(false);
resetButton.setEnabled(false);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setupPlot();
PlotAbstraction plot = plotViewManifestion.getPlot();
if (plot!=null){
setControlPanelState(plot.getAxisOrientationSetting(),
plot.getXAxisMaximumLocation(),
plot.getYAxisMaximumLocation(),
plot.getTimeAxisSubsequentSetting(),
plot.getNonTimeAxisSubsequentMinSetting(),
plot.getNonTimeAxisSubsequentMaxSetting(),
plot.getNonTimeMax(),
plot.getNonTimeMin(),
plot.getTimeMin(),
plot.getTimeMax(),
plot.getTimePadding(),
plot.getNonTimeMaxPadding(),
plot.getNonTimeMinPadding(),
plot.useOrdinalPositionForSubplots(),
plot.getTimeAxisUserPin().isPinned(),
plot.getPlotLineDraw(),
plot.getPlotLineConnectionType());
}
okButton.setEnabled(false);
saveUIControlsSettings();
plotViewManifestion.getManifestedComponent().save();
}
});
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PlotAbstraction plot = plotViewManifestion.getPlot();
if (plot!=null){
setControlPanelState(plot.getAxisOrientationSetting(),
plot.getXAxisMaximumLocation(),
plot.getYAxisMaximumLocation(),
plot.getTimeAxisSubsequentSetting(),
plot.getNonTimeAxisSubsequentMinSetting(),
plot.getNonTimeAxisSubsequentMaxSetting(),
plot.getNonTimeMax(),
plot.getNonTimeMin(),
plot.getTimeMin(),
plot.getTimeMax(),
plot.getTimePadding(),
plot.getNonTimeMaxPadding(),
plot.getNonTimeMinPadding(),
plot.useOrdinalPositionForSubplots(),
plot.getTimeAxisUserPin().isPinned(),
plot.getPlotLineDraw(),
plot.getPlotLineConnectionType());
}
okButton.setEnabled(false);
resetButton.setEnabled(false);
saveUIControlsSettings();
}
});
JPanel okButtonPadded = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 7));
okButtonPadded.add(okButton);
okButtonPadded.add(resetButton);
JPanel okPanel = new JPanel();
okPanel.setLayout(new BorderLayout());
okPanel.add(okButtonPadded, BorderLayout.EAST);
// Instrument
okPanel.setName("okPanel");
okButton.setName("okButton");
okButtonPadded.setName("okButtonPadded");
// Set the panel color to a nice shade of gray
okButtonPadded.setOpaque(false);
okPanel.setBackground(OK_PANEL_BACKGROUND_COLOR);
return okPanel;
}
// Assign internal names to the top level class variables
private void instrumentNames() {
timeAxisMinimumsPanel.setName("timeAxisMinimumsPanel");
timeAxisMaximumsPanel.setName("timeAxisMaximumsPanel");
nonTimeAxisMaximumsPanel.setName("nonTimeAxisMaximumsPanel");
nonTimeAxisMinimumsPanel.setName("nonTimeAxisMinimumsPanel");
timeAxisMinAuto.setName("timeAxisMinAuto");
timeAxisMinAutoValue.setName("timeAxisMinAutoValue");
timeAxisMinManual.setName("timeAxisMinManual");
timeAxisMinManualValue.setName("timeAxisMinManualValue");
timeAxisMaxAuto.setName("timeAxisMaxAuto");
timeAxisMaxAutoValue.setName("timeAxisMaxAutoValue");
timeAxisMaxManual.setName("timeAxisMaxManual");
timeAxisMaxManualValue.setName("timeAxisMaxManualValue");
nonTimeAxisMinCurrent.setName("nonTimeAxisMinCurrent");
nonTimeAxisMinCurrentValue.setName("nonTimeAxisMinCurrentValue");
nonTimeAxisMinManual.setName("nonTimeAxisMinManual");
nonTimeAxisMinManualValue.setName("nonTimeAxisMinManualValue");
nonTimeAxisMinAutoAdjust.setName("nonTimeAxisMinAutoAdjust");
nonTimeAxisMaxCurrent.setName("nonTimeAxisMaxCurrent");
nonTimeAxisMaxCurrentValue.setName("nonTimeAxisMaxCurrentValue");
nonTimeAxisMaxManual.setName("nonTimeAxisMaxManual");
nonTimeAxisMaxManualValue.setName("nonTimeAxisMaxManualValue");
nonTimeAxisMaxAutoAdjust.setName("nonTimeAxisMaxAutoAdjust");
timeJumpMode.setName("timeJumpMode");
timeScrunchMode.setName("timeScrunchMode");
timeJumpPadding.setName("timeJumpPadding");
timeScrunchPadding.setName("timeScrunchPadding");
nonTimeMinAutoAdjustMode.setName("nonTimeMinAutoAdjustMode");
nonTimeMaxAutoAdjustMode.setName("nonTimeMaxAutoAdjustMode");
nonTimeMinFixedMode.setName("nonTimeMinFixedMode");
nonTimeMaxFixedMode.setName("nonTimeMaxFixedMode");
nonTimeMinSemiFixedMode.setName("nonTimeMinSemiFixedMode");
nonTimeMaxSemiFixedMode.setName("nonTimeMaxSemiFixedMode");
imagePanel.setName("imagePanel");
timeDropdown.setName("timeDropdown");
timeSpanValue.setName("timeSpanValue");
nonTimeSpanValue.setName("nonTimeSpanValue");
xMinLabel.setName("xMinLabel");
xMaxLabel.setName("xMaxLabel");
xAxisAsTimeRadioButton.setName("xAxisAsTimeRadioButton");
yAxisAsTimeRadioButton.setName("yAxisAsTimeRadioButton");
xMaxAtRight.setName("xMaxAtRight");
xMaxAtLeft.setName("xMaxAtLeft");
yMaxAtTop.setName("yMaxAtTop");
yMaxAtBottom.setName("yMaxAtBottom");
yAxisType.setName("yAxisType");
xAxisType.setName("xAxisType");
xAxisSpanCluster.setName("xAxisSpanCluster");
xAxisAdjacentPanel.setName("xAxisAdjacentPanel");
xAxisButtonsPanel.setName("xAxisButtonsPanel");
yAxisSpanPanel.setName("ySpanPanel");
yMaximumsPlusPanel.setName("yMaximumsPlusPanel");
yMinimumsPlusPanel.setName("yMinimumsPlusPanel");
yAxisButtonsPanel.setName("yAxisButtonsPanel");
}
/**
* This method scans and sets the Time Axis controls next to the static plot image.
* Triggered by time axis button selection.
*/
GregorianCalendar scratchCalendar = new GregorianCalendar();
GregorianCalendar workCalendar = new GregorianCalendar();
{
workCalendar.setTimeZone(TimeZone.getTimeZone(PlotConstants.DEFAULT_TIME_ZONE));
}
void updateTimeAxisControls() {
// Enable/disable the Span control
timeSpanValue.setEnabled(timeAxisMaxAuto.isSelected());
// Set the value of the Time Span field and the various Min and Max Time fields
if (timeAxisMinAuto.isSelected() && timeAxisMaxAuto.isSelected()) {
// If both Auto buttons are selected, Span value is used
scratchCalendar.setTimeInMillis(timeAxisMinAutoValue.getTimeInMillis());
scratchCalendar.add(Calendar.SECOND, timeSpanValue.getSecond());
scratchCalendar.add(Calendar.MINUTE, timeSpanValue.getMinute());
scratchCalendar.add(Calendar.HOUR_OF_DAY, timeSpanValue.getHourOfDay());
scratchCalendar.add(Calendar.DAY_OF_YEAR, timeSpanValue.getDayOfYear());
timeAxisMaxAutoValue.setTime(scratchCalendar);
} else if (timeAxisMinAuto.isSelected() && timeAxisMaxManual.isSelected()) {
/*
* Min Auto ("Now"), and Max Manual
*/
timeSpanValue.setTime(subtractTimes(timeAxisMinAutoValue.getTimeInMillis(),
timeAxisMaxManualValue.getValueInMillis()));
} else if (timeAxisMinAuto.isSelected() && timeAxisMaxCurrent.isSelected()) {
/*
* Min Auto ("Now"), and Current Max
*/
timeSpanValue.setTime(subtractTimes(timeAxisMinAutoValue.getTimeInMillis(),
timeAxisMaxCurrentValue.getTimeInMillis()));
} else if (timeAxisMinManual.isSelected() && timeAxisMaxAuto.isSelected()) {
/*
* Min Manual, and Max Auto ("Min+Span")
*/
scratchCalendar.setTimeInMillis(timeAxisMinManualValue.getValueInMillis());
scratchCalendar.add(Calendar.SECOND, timeSpanValue.getSecond());
scratchCalendar.add(Calendar.MINUTE, timeSpanValue.getMinute());
scratchCalendar.add(Calendar.HOUR_OF_DAY, timeSpanValue.getHourOfDay());
scratchCalendar.add(Calendar.DAY_OF_YEAR, timeSpanValue.getDayOfYear());
timeAxisMaxAutoValue.setTime(scratchCalendar);
} else if (timeAxisMinManual.isSelected() && timeAxisMaxManual.isSelected()) {
/*
* Min Manual, and Max Manual
* - subtract the Min Manual from the Max Manual to get the new Span value
*/
timeSpanValue.setTime(subtractTimes(timeAxisMinManualValue.getValueInMillis(),
timeAxisMaxManualValue.getValueInMillis()));
} else if (timeAxisMinManual.isSelected() && timeAxisMaxCurrent.isSelected()) {
/*
* Min Manual, and Current Max
* - subtract the Min Manual from the Current Max to get the new Span value
*/
timeSpanValue.setTime(subtractTimes(timeAxisMinManualValue.getValueInMillis(),
timeAxisMaxCurrentValue.getTimeInMillis()));
} else if (timeAxisMinCurrent.isSelected() && timeAxisMaxAuto.isSelected()) {
/*
* Current Min, and Max Auto ("Min+Span")
* - set the Max Auto value to the sum of Current Min and the Span value
*/
scratchCalendar.setTimeInMillis(timeAxisMinCurrentValue.getTimeInMillis());
scratchCalendar.add(Calendar.SECOND, timeSpanValue.getSecond());
scratchCalendar.add(Calendar.MINUTE, timeSpanValue.getMinute());
scratchCalendar.add(Calendar.HOUR_OF_DAY, timeSpanValue.getHourOfDay());
scratchCalendar.add(Calendar.DAY_OF_YEAR, timeSpanValue.getDayOfYear());
timeAxisMaxAutoValue.setTime(scratchCalendar);
} else if (timeAxisMinCurrent.isSelected() && timeAxisMaxManual.isSelected()) {
/*
* Current Min, and Max Manual
* - subtract the Current Min from Max Manual to get the new Span value
*/
timeSpanValue.setTime(subtractTimes(timeAxisMinCurrentValue.getTimeInMillis(),
timeAxisMaxManualValue.getValueInMillis()));
} else if (timeAxisMinCurrent.isSelected() && timeAxisMaxCurrent.isSelected()) {
/*
* Current Min, and Current Max
* - subtract the Current Min from the Current Max to get the new Span value
*/
timeSpanValue.setTime(subtractTimes(timeAxisMinCurrentValue.getTimeInMillis(),
timeAxisMaxCurrentValue.getTimeInMillis()));
} else {
logger.error("Program issue: if-else cases are missing one use case.");
}
if (timeAxisMinCurrent.isSelected()) {
scratchCalendar.setTimeInMillis(timeAxisMinCurrentValue.getTimeInMillis());
} else
if (timeAxisMinManual.isSelected()) {
scratchCalendar.setTimeInMillis(timeAxisMinManualValue.getValueInMillis());
} else
if (timeAxisMinAuto.isSelected()) {
scratchCalendar.setTimeInMillis(timeAxisMinAutoValue.getTimeInMillis());
}
scratchCalendar.add(Calendar.SECOND, timeSpanValue.getSecond());
scratchCalendar.add(Calendar.MINUTE, timeSpanValue.getMinute());
scratchCalendar.add(Calendar.HOUR_OF_DAY, timeSpanValue.getHourOfDay());
scratchCalendar.add(Calendar.DAY_OF_YEAR, timeSpanValue.getDayOfYear());
timeAxisMaxAutoValue.setTime(scratchCalendar);
// Update the Time axis Current Min and Max values
GregorianCalendar plotMinTime = plotViewManifestion.getPlot().getMinTime();
GregorianCalendar plotMaxTime = plotViewManifestion.getPlot().getMaxTime();
timeAxisMinCurrentValue.setTime(plotMinTime);
timeAxisMaxCurrentValue.setTime(plotMaxTime);
// If the Manual (Min and Max) fields have NOT been selected up to now, update them with the
// plot's current Min and Max values
if (! timeMinManualHasBeenSelected) {
workCalendar.setTime(plotMinTime.getTime());
timeAxisMinManualValue.setTime(workCalendar);
}
if (! timeMaxManualHasBeenSelected) {
workCalendar.setTime(plotMaxTime.getTime());
timeAxisMaxManualValue.setTime(workCalendar);
}
updateMainButtons();
}
/**
* Returns the difference between two times as a time Duration
* @param begin
* @param end
* @return
*/
private TimeDuration subtractTimes(long begin, long end) {
if (begin < end) {
long difference = end - begin;
long days = difference / (24 * 60 * 60 * 1000);
long remainder = difference - (days * 24 * 60 * 60 * 1000);
long hours = remainder / (60 * 60 * 1000);
remainder = remainder - (hours * 60 * 60 * 1000);
long minutes = remainder / (60 * 1000);
remainder = remainder - (minutes * 60 * 1000);
long seconds = remainder / (1000);
return new TimeDuration((int) days, (int) hours, (int) minutes, (int) seconds);
} else {
return new TimeDuration(0, 0, 0, 0);
}
}
/**
* This method scans and sets the Non-Time Axis controls next to the static plot image.
* Triggered when a non-time radio button is selected or on update tick
*/
void updateNonTimeAxisControls() {
assert !(nonTimeAxisMinAutoAdjust.isSelected() && nonTimeAxisMaxAutoAdjust.isSelected()) : "Illegal condition: Both span radio buttons are selected.";
// Enable/disable the non-time Span value
if (nonTimeAxisMinAutoAdjust.isSelected() || nonTimeAxisMaxAutoAdjust.isSelected()) {
nonTimeSpanValue.setEnabled(true);
} else {
nonTimeSpanValue.setEnabled(false);
}
// Enable/disable the non-time Auto-Adjust (Span-dependent) controls
if (nonTimeAxisMaxAutoAdjust.isSelected()) {
nonTimeAxisMinAutoAdjust.setEnabled(false);
nonTimeAxisMinAutoAdjustValue.setEnabled(false);
} else
if (nonTimeAxisMinAutoAdjust.isSelected()) {
nonTimeAxisMaxAutoAdjust.setEnabled(false);
nonTimeAxisMaxAutoAdjustValue.setEnabled(false);
} else
// If neither of the buttons using Span is selected, enable both
if (!nonTimeAxisMinAutoAdjust.isSelected() && !nonTimeAxisMaxAutoAdjust.isSelected()) {
nonTimeAxisMinAutoAdjust.setEnabled(true);
nonTimeAxisMaxAutoAdjust.setEnabled(true);
nonTimeAxisMinAutoAdjustValue.setEnabled(true);
nonTimeAxisMaxAutoAdjustValue.setEnabled(true);
}
// Update the Span-dependent controls
// nonTimeAxisMinAutoAdjustValue: (Max - Span)
double maxValue = getNonTimeMaxValue();
// nonTimeAxisMaxAutoAdjustValue: (Min + Span)
double minValue = getNonTimeMinValue();
try {
String span = nonTimeSpanValue.getText();
if (! span.isEmpty()) {
double spanValue = nonTimeSpanValue.getDoubleValue();
nonTimeAxisMinAutoAdjustValue.setValue(maxValue - spanValue);
nonTimeAxisMaxAutoAdjustValue.setValue(minValue + spanValue);
}
} catch (ParseException e) {
logger.error("Plot control panel: Could not parse non-time span value.");
}
if (!(nonTimeAxisMinAutoAdjust.isSelected() || nonTimeAxisMaxAutoAdjust.isSelected())) {
double difference = getNonTimeMaxValue() - getNonTimeMinValue();
nonTimeSpanValue.setValue(difference);
}
updateMainButtons();
}
private boolean isValidTimeAxisValues() {
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(plotViewManifestion.getCurrentMCTTime());
// If the time from MCT is invalid, then we do not evaluate Time Span
if (gc.get(Calendar.YEAR) <= 1970) {
return true;
}
if (timeAxisMinCurrent.isSelected() && timeAxisMaxCurrent.isSelected()
&& timeSpanValue.getText().equals("000/00:00:00") ) {
return true;
}
// For valid MCT times, evaluate the value in Time Span
return timeSpanValue.getSubYearValue() > 0;
}
private boolean isValidNonTimeAxisValues() {
try {
if (nonTimeSpanValue.getText().isEmpty()) {
return false;
}
// When the plot has no data, the current min and max may be the same value,
// usually zero. This should not disable the Apply and Reset buttons.
if (nonTimeAxisMinCurrent.isSelected() && nonTimeAxisMaxCurrent.isSelected()
&& nonTimeSpanValue.getDoubleValue() == 0.0 ) {
return true;
}
// If the plot has data, then check that the Span value is greater than zero.
if (nonTimeSpanValue.getDoubleValue() <= 0.0) {
return false;
}
} catch (ParseException e) {
logger.error("Could not parse the non-time span's value");
}
return true;
}
/**
* This method checks the values in the axis controls and then enables/disables the
* Apply button.
* @param isPanelDirty
*/
private void updateMainButtons() {
// Apply button enable/disable.
if (isPanelDirty() && isValidTimeAxisValues() && isValidNonTimeAxisValues()) {
okButton.setEnabled(true);
okButton.setToolTipText(BUNDLE.getString("ApplyPanelSettingToPlot.label"));
resetButton.setEnabled(true);
resetButton.setToolTipText(BUNDLE.getString("ResetPanelSettingToMatchPlot.label"));
} else {
okButton.setEnabled(false);
// Set tool tip to explain why the control is disabled.
StringBuilder toolTip = new StringBuilder("<HTML>" + BUNDLE.getString("ApplyButtonIsInActive.label") + ":<BR>");
if (!isPanelDirty()) {
toolTip.append(BUNDLE.getString("NoChangedMadeToPanel.label") + "<BR>");
}
if(!isValidTimeAxisValues()) {
toolTip.append(BUNDLE.getString("TimeAxisValuesInvalid.label") + "<BR>");
}
if(!isValidNonTimeAxisValues()) {
toolTip.append(BUNDLE.getString("NonTimeAxisValuesInvalid.label") + "<BR>");
}
toolTip.append("</HTML>");
okButton.setToolTipText(toolTip.toString());
resetButton.setEnabled(false);
resetButton.setToolTipText(BUNDLE.getString("ResetButtonInactiveBecauseNoChangesMade.label"));
}
}
/**
* Update the label representing the time axis' Min + Span value
* Selections are: Min Manual button, Max Auto ("Min + Span") button
*/
public void refreshDisplay() {
// Update the MCT time ("Now")
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(plotViewManifestion.getCurrentMCTTime());
timeAxisMinAutoValue.setTime(gc);
// Update the time min/max values
nonTimeAxisMinCurrentValue.setValue(plotViewManifestion.getMinFeedValue());
nonTimeAxisMaxCurrentValue.setValue(plotViewManifestion.getMaxFeedValue());
updateTimeAxisControls();
updateNonTimeAxisControls();
}
// Initially returns float; but shouldn't this be double precision (?)
double getNonTimeMaxValue() {
if (nonTimeAxisMaxCurrent.isSelected()) {
return nonTimeAxisMaxCurrentValue.getValue().floatValue();
} else if (nonTimeAxisMaxManual.isSelected()) {
//float result = 0;
double result = 1.0;
try {
result = nonTimeAxisMaxManualValue.getDoubleValue().floatValue();
} catch (ParseException e) {
logger.error("Plot control panel: Could not read the non-time axis' maximum manual value");
}
return result;
} else if (nonTimeAxisMaxAutoAdjust.isSelected()) {
return nonTimeAxisMaxAutoAdjustValue.getValue().floatValue();
}
return 1.0;
}
double getNonTimeMinValue() {
if (nonTimeAxisMinCurrent.isSelected()) {
return nonTimeAxisMinCurrentValue.getValue().floatValue();
} else if (nonTimeAxisMinManual.isSelected()) {
double result = 0.0;
try {
result = nonTimeAxisMinManualValue.getDoubleValue().floatValue();
} catch (ParseException e) {
logger.error("Plot control panel: Could not read the non-time axis' minimum manual value");
}
return result;
} else if (nonTimeAxisMinAutoAdjust.isSelected()) {
return nonTimeAxisMinAutoAdjustValue.getValue().floatValue();
}
return 0.0;
}
/**
* Gets the PlotViewManifestation associated with this control panel.
* @return the PlotViewManifesation
*/
public PlotViewManifestation getPlot() {
return plotViewManifestion;
}
// The Initial Settings panel
// Name change: Initial Settings is now labeled Min/Max Setup
private JPanel getInitialSetupPanel() {
JPanel initialSetup = new JPanel();
initialSetup.setLayout(new BoxLayout(initialSetup, BoxLayout.Y_AXIS));
initialSetup.setBorder(SETUP_AND_BEHAVIOR_MARGINS);
yAxisType = new JLabel("(NON-TIME)");
JPanel yAxisTypePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
yAxisTypePanel.add(yAxisType);
imagePanel = new StillPlotImagePanel();
// Start defining the top panel
JPanel initTopPanel = createTopPanel();
// Assemble the bottom panel
JPanel initBottomPanel = new JPanel();
initBottomPanel.setLayout(new GridBagLayout());
initBottomPanel.setBorder(TOP_PADDED_MARGINS);
JPanel yAxisPanelSet = createYAxisPanelSet();
JPanel xAxisPanelSet = createXAxisPanelSet();
JPanel yAxisControlsPanel = new JPanel();
yAxisControlsPanel.setLayout(new BoxLayout(yAxisControlsPanel, BoxLayout.Y_AXIS));
yAxisPanelSet.setAlignmentX(Component.CENTER_ALIGNMENT);
yAxisControlsPanel.add(yAxisPanelSet);
JPanel xAxisControlsPanel = new JPanel(new GridLayout(1, 1));
xAxisControlsPanel.add(xAxisPanelSet);
// The title label for (TIME) or (NON-TIME)
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
initBottomPanel.add(yAxisTypePanel, gbc);
// The Y Axis controls panel
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.gridx = 0;
gbc1.gridy = 1;
gbc1.gridwidth = 1;
gbc1.gridheight = 3;
gbc1.fill = GridBagConstraints.BOTH;
// To align the "Min" or "Max" label with the bottom of the static plot image,
// add a vertical shim under the Y Axis bottom button set and "Min"/"Max" label.
gbc1.insets = new Insets(2, 0, 10, 2);
initBottomPanel.add(yAxisControlsPanel, gbc1);
// The static plot image
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.gridx = 1;
gbc2.gridy = 1;
gbc2.gridwidth = 3;
gbc2.gridheight = 3;
initBottomPanel.add(imagePanel, gbc2);
// The X Axis controls panel
GridBagConstraints gbc3 = new GridBagConstraints();
gbc3.gridx = 1;
gbc3.gridy = 4;
gbc3.gridwidth = 3;
gbc3.gridheight = 1;
gbc3.fill = GridBagConstraints.BOTH;
gbc3.insets = new Insets(0, 8, 0, 0);
initBottomPanel.add(xAxisControlsPanel, gbc3);
// Assemble the major panel: Initial Settings
JPanel topClamp = new JPanel(new BorderLayout());
topClamp.add(initTopPanel, BorderLayout.NORTH);
JPanel bottomClamp = new JPanel(new BorderLayout());
bottomClamp.add(initBottomPanel, BorderLayout.NORTH);
JPanel sideClamp = new JPanel(new BorderLayout());
sideClamp.add(bottomClamp, BorderLayout.WEST);
initialSetup.add(Box.createRigidArea(new Dimension(0, INNER_PADDING)));
initialSetup.add(topClamp);
initialSetup.add(Box.createRigidArea(new Dimension(0, INNER_PADDING)));
initialSetup.add(new JSeparator());
initialSetup.add(sideClamp);
// Instrument
initialSetup.setName("initialSetup");
initTopPanel.setName("initTopPanel");
initBottomPanel.setName("initBottomPanel");
yAxisPanelSet.setName("yAxisPanelSet");
xAxisPanelSet.setName("xAxisPanelSet");
yAxisControlsPanel.setName("yAxisInnerPanel");
xAxisControlsPanel.setName("nontimeSidePanel");
topClamp.setName("topClamp");
bottomClamp.setName("bottomClamp");
return initialSetup;
}
// Top panel that controls which axis plots Time and the direction of each axis
private JPanel createTopPanel() {
JPanel initTopPanel = new JPanel();
initTopPanel.setLayout(new GridBagLayout());
// Left column
timeDropdown = new JComboBox( new Object[]{BUNDLE.getString("GMT.label")});
JPanel timenessRow = new JPanel();
timenessRow.add(new JLabel(BUNDLE.getString("Time.label")));
timenessRow.add(timeDropdown);
xAxisAsTimeRadioButton = new JRadioButton(BUNDLE.getString("XAxisAsTime.label"));
yAxisAsTimeRadioButton = new JRadioButton(BUNDLE.getString("YAxisAsTime.label"));
// Middle column
JLabel xDirTitle = new JLabel(BUNDLE.getString("XAxis.label"));
xMaxAtRight = new JRadioButton(BUNDLE.getString("MaxAtRight.label"));
xMaxAtLeft = new JRadioButton(BUNDLE.getString("MaxAtLeft.label"));
// Right column
JLabel yDirTitle = new JLabel(BUNDLE.getString("YAxis.label"));
yMaxAtTop = new JRadioButton(BUNDLE.getString("MaxAtTop.label"));
yMaxAtBottom = new JRadioButton(BUNDLE.getString("MaxAtBottom.label"));
// Separator lines for the top panel
JSeparator separator1 = new JSeparator(SwingConstants.VERTICAL);
JSeparator separator2 = new JSeparator(SwingConstants.VERTICAL);
// Assemble the top row of cells (combo box, 2 separators and 2 titles)
GridBagConstraints gbcTopA = new GridBagConstraints();
gbcTopA.anchor = GridBagConstraints.WEST;
initTopPanel.add(timenessRow, gbcTopA);
GridBagConstraints gbcSep1 = new GridBagConstraints();
gbcSep1.gridheight = 3;
gbcSep1.fill = GridBagConstraints.BOTH;
gbcSep1.insets = new Insets(0, 5, 0, 5);
initTopPanel.add(separator1, gbcSep1);
GridBagConstraints gbcTopB = new GridBagConstraints();
gbcTopB.anchor = GridBagConstraints.WEST;
gbcTopB.insets = new Insets(0, 4, 0, 0);
initTopPanel.add(xDirTitle, gbcTopB);
initTopPanel.add(separator2, gbcSep1);
initTopPanel.add(yDirTitle, gbcTopB);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.gridy = 1;
gbc.gridx = 0;
initTopPanel.add(xAxisAsTimeRadioButton, gbc);
gbc.gridx = 2;
initTopPanel.add(xMaxAtRight, gbc);
gbc.gridx = 4;
initTopPanel.add(yMaxAtTop, gbc);
gbc.gridy = 2;
gbc.gridx = 0;
gbc.insets = new Insets(5, 0, 0, 0);
initTopPanel.add(yAxisAsTimeRadioButton, gbc);
gbc.gridx = 2;
initTopPanel.add(xMaxAtLeft, gbc);
gbc.gridx = 4;
initTopPanel.add(yMaxAtBottom, gbc);
// add stacked plot grouping
GridBagConstraints groupingGbc = new GridBagConstraints();
groupingGbc.gridheight = 3;
groupingGbc.fill = GridBagConstraints.BOTH;
groupingGbc.insets = new Insets(0, 5, 0, 5);
initTopPanel.add(new JSeparator(JSeparator.VERTICAL), groupingGbc);
// Stacked Plot Grouping Label
groupingGbc.gridheight = 1;
groupingGbc.gridy = 0;
initTopPanel.add(new JLabel(BUNDLE.getString("StackedPlotGroping.label")),groupingGbc);
groupingGbc.gridy = 1;
groupByCollection = new JCheckBox(BUNDLE.getString("GroupByCollection.label"));
groupByCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateMainButtons();
}
});
initTopPanel.add(groupByCollection,groupingGbc);
// Add listeners and set initial state
addTopPanelListenersAndState();
// Instrument
initTopPanel.setName("initTopPanel");
timenessRow.setName("timenessRow");
JPanel horizontalSqueeze = new JPanel(new BorderLayout());
horizontalSqueeze.add(initTopPanel, BorderLayout.WEST);
return horizontalSqueeze;
}
private void addTopPanelListenersAndState() {
xAxisAsTimeRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
xAxisAsTimeRadioButtonActionPerformed();
}
});
yAxisAsTimeRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
yAxisAsTimeRadioButtonActionPerformed();
}
});
xMaxAtRight.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
xMaxAtRightActionPerformed();
}
});
xMaxAtLeft.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
xMaxAtLeftActionPerformed();
}
});
yMaxAtTop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
yMaxAtTopActionPerformed();
}
});
yMaxAtBottom.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
yMaxAtBottomActionPerformed();
}
});
xAxisAsTimeRadioButton.setSelected(true);
xMaxAtRight.setSelected(true);
yMaxAtTop.setSelected(true);
// Button Groups
ButtonGroup timenessGroup = new ButtonGroup();
timenessGroup.add(xAxisAsTimeRadioButton);
timenessGroup.add(yAxisAsTimeRadioButton);
ButtonGroup xDirectionGroup = new ButtonGroup();
xDirectionGroup.add(xMaxAtRight);
xDirectionGroup.add(xMaxAtLeft);
ButtonGroup yDirectionGroup = new ButtonGroup();
yDirectionGroup.add(yMaxAtTop);
yDirectionGroup.add(yMaxAtBottom);
}
private void xAxisAsTimeRadioButtonActionPerformed() {
// Move the time axis panels to the x axis class
// Move the nontime axis panels to the y axis class
xAxisButtonsPanel.insertMinMaxPanels(timeAxisMinimumsPanel, timeAxisMaximumsPanel);
yAxisButtonsPanel.insertMinMaxPanels(nonTimeAxisMinimumsPanel, nonTimeAxisMaximumsPanel);
xAxisSpanCluster.setSpanField(timeSpanValue); //Panel);
yAxisSpanPanel.setSpanField(nonTimeSpanValue);
if (yMaxAtTop.isSelected()) {
yAxisButtonsPanel.setNormalOrder(true);
} else {
yAxisButtonsPanel.setNormalOrder(false);
}
if (xMaxAtRight.isSelected()) {
xMaxAtRight.doClick();
} else {
xMaxAtLeft.doClick();
}
xAxisType.setText("(" + BUNDLE.getString("Time.label") + ")");
yAxisType.setText("(" + BUNDLE.getString("NonTime.label") + ")");
imagePanel.setImageToTimeOnXAxis(xMaxAtRight.isSelected());
behaviorTimeAxisLetter.setText(BUNDLE.getString("X.label"));
behaviorNonTimeAxisLetter.setText(BUNDLE.getString("Y.label"));
}
private void yAxisAsTimeRadioButtonActionPerformed() {
xAxisButtonsPanel.insertMinMaxPanels(nonTimeAxisMinimumsPanel, nonTimeAxisMaximumsPanel);
yAxisButtonsPanel.insertMinMaxPanels(timeAxisMinimumsPanel, timeAxisMaximumsPanel);
xAxisSpanCluster.setSpanField(nonTimeSpanValue);
yAxisSpanPanel.setSpanField(timeSpanValue); //Panel);
if (yMaxAtTop.isSelected()) {
yAxisButtonsPanel.setNormalOrder(true);
} else {
yAxisButtonsPanel.setNormalOrder(false);
}
if (xMaxAtRight.isSelected()) {
xMaxAtRight.doClick();
} else {
xMaxAtLeft.doClick();
}
xAxisType.setText("(" + BUNDLE.getString("NonTime.label") + ")");
yAxisType.setText("(" + BUNDLE.getString("Time.label") + ")");
imagePanel.setImageToTimeOnYAxis(yMaxAtTop.isSelected());
behaviorTimeAxisLetter.setText(BUNDLE.getString("Y.label"));
behaviorNonTimeAxisLetter.setText(BUNDLE.getString("X.label"));
}
private void xMaxAtRightActionPerformed() {
xAxisAdjacentPanel.setNormalOrder(true);
xAxisButtonsPanel.setNormalOrder(true);
if (xAxisAsTimeRadioButton.isSelected()) {
imagePanel.setImageToTimeOnXAxis(true); // normal direction
}
}
private void xMaxAtLeftActionPerformed() {
xAxisAdjacentPanel.setNormalOrder(false);
xAxisButtonsPanel.setNormalOrder(false);
if (xAxisAsTimeRadioButton.isSelected()) {
imagePanel.setImageToTimeOnXAxis(false); // reverse direction
}
}
private void yMaxAtTopActionPerformed() {
yAxisButtonsPanel.setNormalOrder(true);
if (yAxisAsTimeRadioButton.isSelected()) {
imagePanel.setImageToTimeOnYAxis(true); // normal direction
}
}
private void yMaxAtBottomActionPerformed() {
yAxisButtonsPanel.setNormalOrder(false);
if (yAxisAsTimeRadioButton.isSelected()) {
imagePanel.setImageToTimeOnYAxis(false); // reverse direction
}
}
// The controls that exactly align with the X axis
private JPanel createXAxisPanelSet() {
xAxisSpanCluster = new XAxisSpanCluster();
xAxisAdjacentPanel = new XAxisAdjacentPanel();
xAxisAdjacentPanel.setNormalOrder(true);
xAxisButtonsPanel = new XAxisButtonsPanel();
timeAxisMinimumsPanel = new TimeAxisMinimumsPanel();
timeAxisMaximumsPanel = new TimeAxisMaximumsPanel();
xAxisButtonsPanel.insertMinMaxPanels(timeAxisMinimumsPanel, timeAxisMaximumsPanel);
xAxisButtonsPanel.setNormalOrder(true);
JPanel belowXAxisPanel = new JPanel();
belowXAxisPanel.setLayout(new BoxLayout(belowXAxisPanel, BoxLayout.Y_AXIS));
belowXAxisPanel.add(xAxisAdjacentPanel);
belowXAxisPanel.add(xAxisButtonsPanel);
belowXAxisPanel.add(Box.createVerticalStrut(X_AXIS_TYPE_VERTICAL_SPACING));
xAxisType = new JLabel("(TIME)");
belowXAxisPanel.add(xAxisType);
xAxisType.setAlignmentX(Component.CENTER_ALIGNMENT);
// Instrument
belowXAxisPanel.setName("belowXAxisPanel");
return belowXAxisPanel;
}
// The controls that exactly align with the Y axis
private JPanel createYAxisPanelSet() {
yMaximumsPlusPanel = new YMaximumsPlusPanel();
yAxisSpanPanel = new YAxisSpanPanel();
yMinimumsPlusPanel = new YMinimumsPlusPanel();
yAxisButtonsPanel = new YAxisButtonsPanel();
yAxisButtonsPanel.insertMinMaxPanels(nonTimeAxisMinimumsPanel, nonTimeAxisMaximumsPanel);
yAxisButtonsPanel.setNormalOrder(true);
return yAxisButtonsPanel;
}
// Convenience method for populating and applying a standard layout for multi-item rows
private JPanel createMultiItemRow(JRadioButton button, JComponent secondItem) {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
if (button != null) {
button.setSelected(false);
panel.add(button, gbc);
}
if (secondItem != null) {
gbc.gridx = 1;
gbc.insets = new Insets(0, SPACE_BETWEEN_ROW_ITEMS, 0, 0);
gbc.weightx = 1;
panel.add(secondItem, gbc);
}
panel.setName("multiItemRow");
return panel;
}
// The Plot Behavior panel
private JPanel getPlotBehaviorPanel() {
JPanel plotBehavior = new JPanel();
plotBehavior.setLayout(new GridBagLayout());
plotBehavior.setBorder(SETUP_AND_BEHAVIOR_MARGINS);
JPanel modePanel = new JPanel(new GridLayout(1, 1));
JButton bMode = new JButton(BUNDLE.getString("Mode.label"));
bMode.setAlignmentY(CENTER_ALIGNMENT);
modePanel.add(bMode);
JPanel minPanel = new JPanel(new GridLayout(1, 1));
JLabel bMin = new JLabel(BUNDLE.getString("Min.label"));
bMin.setHorizontalAlignment(JLabel.CENTER);
minPanel.add(bMin);
JPanel maxPanel = new JPanel(new GridLayout(1, 1));
maxPanel.add(new JLabel(BUNDLE.getString("Max.label")));
GridLinedPanel timeAxisPanel = createGriddedTimeAxisPanel();
GridLinedPanel nonTimeAxisPanel = createGriddedNonTimeAxisPanel();
behaviorTimeAxisLetter = new JLabel("_");
JPanel behaviorTimeTitlePanel = new JPanel();
behaviorTimeTitlePanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, NONTIME_TITLE_SPACING));
behaviorTimeTitlePanel.add(new JLabel(BUNDLE.getString("TimeAxis.label") + " ("));
behaviorTimeTitlePanel.add(behaviorTimeAxisLetter);
behaviorTimeTitlePanel.add(new JLabel("):"));
pinTimeAxis = new JCheckBox(BUNDLE.getString("PinTimeAxis.label"));
behaviorTimeTitlePanel.add(pinTimeAxis);
behaviorNonTimeAxisLetter = new JLabel("_");
JPanel behaviorNonTimeTitlePanel = new JPanel();
behaviorNonTimeTitlePanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, NONTIME_TITLE_SPACING));
behaviorNonTimeTitlePanel.add(new JLabel(BUNDLE.getString("NonTimeAxis.label") + " ("));
behaviorNonTimeTitlePanel.add(behaviorNonTimeAxisLetter);
behaviorNonTimeTitlePanel.add(new JLabel("):"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(6, 0, 0, 0);
plotBehavior.add(behaviorTimeTitlePanel, gbc);
gbc.gridy++;
gbc.insets = new Insets(0, 0, 0, 0);
plotBehavior.add(timeAxisPanel, gbc);
gbc.gridy++;
gbc.insets = new Insets(6, 0, 0, 0);
plotBehavior.add(behaviorNonTimeTitlePanel, gbc);
gbc.gridy++;
gbc.insets = new Insets(0, 0, 0, 0);
plotBehavior.add(nonTimeAxisPanel, gbc);
// Instrument
plotBehavior.setName("plotBehavior");
modePanel.setName("modePanel");
bMode.setName("bMode");
minPanel.setName("minPanel");
bMin.setName("bMin");
maxPanel.setName("maxPanel");
timeAxisPanel.setName("timeAxisPanel");
nonTimeAxisPanel.setName("nonTimeAxisPanel");
behaviorTimeAxisLetter.setName("behaviorTimeAxisLetter");
behaviorNonTimeAxisLetter.setName("behaviorNonTimeAxisLetter");
JPanel stillBehavior = new JPanel(new BorderLayout());
stillBehavior.add(plotBehavior, BorderLayout.WEST);
return stillBehavior;
}
// The Non-Time Axis table within the Plot Behavior panel
private GridLinedPanel createGriddedNonTimeAxisPanel() {
JLabel titleMin = new JLabel(BUNDLE.getString("Min.label"));
JLabel titleMax = new JLabel(BUNDLE.getString("Max.label"));
JLabel titlePadding = new JLabel(BUNDLE.getString("Padding.label"));
JLabel titleMinPadding = new JLabel(BUNDLE.getString("Min.label"));
JLabel titleMaxPadding = new JLabel(BUNDLE.getString("Max.label"));
setFontToBold(titleMin);
setFontToBold(titleMax);
setFontToBold(titlePadding);
setFontToBold(titleMinPadding);
setFontToBold(titleMaxPadding);
nonTimeMinAutoAdjustMode = new JRadioButton(BUNDLE.getString("AutoAdjusts.label"));
nonTimeMaxAutoAdjustMode = new JRadioButton(BUNDLE.getString("AutoAdjusts.label"));
nonTimeMinFixedMode = new JRadioButton(BUNDLE.getString("Fixed.label"));
nonTimeMaxFixedMode = new JRadioButton(BUNDLE.getString("Fixed.label"));
JPanel nonTimeMinAutoAdjustModePanel = new JPanel();
nonTimeMinAutoAdjustModePanel.add(nonTimeMinAutoAdjustMode);
JPanel nonTimeMaxAutoAdjustModePanel = new JPanel();
nonTimeMaxAutoAdjustModePanel.add(nonTimeMaxAutoAdjustMode);
JPanel nonTimeMinFixedModePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0));
nonTimeMinFixedModePanel.add(nonTimeMinFixedMode);
JPanel nonTimeMaxFixedModePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0));
nonTimeMaxFixedModePanel.add(nonTimeMaxFixedMode);
nonTimeMinAutoAdjustMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
nonTimeMinSemiFixedMode.setEnabled(false);
nonTimeMinSemiFixedMode.setSelected(false);
}
});
nonTimeMinFixedMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(nonTimeMinFixedMode.isSelected()) {
nonTimeMinSemiFixedMode.setEnabled(true);
} else {
nonTimeMinSemiFixedMode.setEnabled(false);
nonTimeMinSemiFixedMode.setSelected(false);
}
}
});
nonTimeMaxAutoAdjustMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
nonTimeMaxSemiFixedMode.setEnabled(false);
nonTimeMaxSemiFixedMode.setSelected(false);
}
});
nonTimeMaxFixedMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(nonTimeMaxFixedMode.isSelected()) {
nonTimeMaxSemiFixedMode.setEnabled(true);
} else {
nonTimeMaxSemiFixedMode.setEnabled(false);
nonTimeMaxSemiFixedMode.setSelected(false);
}
}
});
nonTimeMinAutoAdjustMode.setSelected(true);
nonTimeMaxAutoAdjustMode.setSelected(true);
ButtonGroup minGroup = new ButtonGroup();
minGroup.add(nonTimeMinAutoAdjustMode);
minGroup.add(nonTimeMinFixedMode);
ButtonGroup maxGroup = new ButtonGroup();
maxGroup.add(nonTimeMaxAutoAdjustMode);
maxGroup.add(nonTimeMaxFixedMode);
nonTimeMinSemiFixedMode = new JCheckBox(BUNDLE.getString("SemiFixed.label"));
nonTimeMaxSemiFixedMode = new JCheckBox(BUNDLE.getString("SemiFixed.label"));
JPanel nonTimeMinSemiFixedModePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 2));
JPanel nonTimeMaxSemiFixedModePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 2));
nonTimeMinSemiFixedModePanel.add(nonTimeMinSemiFixedMode);
nonTimeMaxSemiFixedModePanel.add(nonTimeMaxSemiFixedMode);
nonTimeMinSemiFixedMode.setEnabled(false);
nonTimeMaxSemiFixedMode.setEnabled(false);
nonTimeMinPadding = createPaddingTextField(AxisType.NON_TIME, AxisBounds.MIN);
nonTimeMaxPadding = createPaddingTextField(AxisType.NON_TIME, AxisBounds.MAX);
JPanel nonTimeMinPaddingPanel = new JPanel();
nonTimeMinPaddingPanel.add(nonTimeMinPadding);
nonTimeMinPaddingPanel.add(new JLabel(BUNDLE.getString("Percent.label")));
JPanel nonTimeMaxPaddingPanel = new JPanel();
nonTimeMaxPaddingPanel.add(nonTimeMaxPadding);
nonTimeMaxPaddingPanel.add(new JLabel(BUNDLE.getString("Percent.label")));
JPanel nonTimeMins = new JPanel();
nonTimeMins.setLayout(new GridBagLayout());
GridBagConstraints gbc0 = new GridBagConstraints();
gbc0.gridy = 0;
gbc0.anchor = GridBagConstraints.WEST;
nonTimeMins.add(nonTimeMinAutoAdjustModePanel, gbc0);
gbc0.gridy = 1;
nonTimeMins.add(nonTimeMinFixedModePanel, gbc0);
gbc0.gridy = 2;
gbc0.insets = new Insets(0, INDENTATION_SEMI_FIXED_CHECKBOX, 0, 0);
nonTimeMins.add(nonTimeMinSemiFixedModePanel, gbc0);
JPanel nonTimeMaxs = new JPanel();
nonTimeMaxs.setLayout(new GridBagLayout());
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.gridy = 0;
gbc1.anchor = GridBagConstraints.WEST;
nonTimeMaxs.add(nonTimeMaxAutoAdjustModePanel, gbc1);
gbc1.gridy = 1;
nonTimeMaxs.add(nonTimeMaxFixedModePanel, gbc1);
gbc1.gridy = 2;
gbc1.insets = new Insets(0, INDENTATION_SEMI_FIXED_CHECKBOX, 0, 0);
nonTimeMaxs.add(nonTimeMaxSemiFixedModePanel, gbc1);
GridLinedPanel griddedPanel = new GridLinedPanel();
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.ipadx = BEHAVIOR_CELLS_X_PADDING;
griddedPanel.setGBC(gbc);
// Title row A
int row = 0;
gbc.gridwidth = 1;
gbc.gridheight = 2; // First 2 titles are 2 rows high
griddedPanel.addCell(titleMin, 1, row);
griddedPanel.addCell(titleMax, 2, row);
gbc.gridwidth = 2; // "Padding" spans 2 columns, 1 row high
gbc.gridheight = 1;
griddedPanel.addCell(titlePadding, 3, row);
gbc.gridwidth = 1;
// Title row B - only 2 cells occupied
row++;
griddedPanel.addCell(titleMinPadding, 3, row);
griddedPanel.addCell(titleMaxPadding, 4, row);
// Row 1
row++;
griddedPanel.addCell(nonTimeMins, 1, row, GridBagConstraints.WEST);
griddedPanel.addCell(nonTimeMaxs, 2, row, GridBagConstraints.WEST);
griddedPanel.addCell(nonTimeMinPaddingPanel, 3, row);
griddedPanel.addCell(nonTimeMaxPaddingPanel, 4, row);
// Instrument
nonTimeMins.setName("nonTimeMins");
nonTimeMaxs.setName("nonTimeMaxs");
return griddedPanel;
}
/*
* This filter blocks non-numeric characters from being entered in the padding fields
*/
class PaddingFilter extends DocumentFilter {
private StringBuilder insertBuilder;
private StringBuilder replaceBuilder;
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException {
insertBuilder = new StringBuilder(string);
for (int k = insertBuilder.length() - 1; k >= 0; k--) {
int cp = insertBuilder.codePointAt(k);
if (! Character.isDigit(cp)) {
insertBuilder.deleteCharAt(k);
if (Character.isSupplementaryCodePoint(cp)) {
k--;
insertBuilder.deleteCharAt(k);
}
}
}
super.insertString(fb, offset, insertBuilder.toString(), attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr)
throws BadLocationException {
replaceBuilder = new StringBuilder(string);
for (int k = replaceBuilder.length() - 1; k >= 0; k--) {
int cp = replaceBuilder.codePointAt(k);
if (! Character.isDigit(cp)) {
replaceBuilder.deleteCharAt(k);
if (Character.isSupplementaryCodePoint(cp)) {
k--;
replaceBuilder.deleteCharAt(k);
}
}
}
super.replace(fb, offset, length, replaceBuilder.toString(), attr);
}
StringBuilder getInsertBuilder() {
return insertBuilder;
}
StringBuilder getReplaceBuilder() {
return replaceBuilder;
}
}
@SuppressWarnings("serial")
private JTextField createPaddingTextField(AxisType axisType, AxisBounds bound) {
final JFormattedTextField tField = new JFormattedTextField(new InternationalFormatter(
NumberFormat.getIntegerInstance()) {
protected DocumentFilter getDocumentFilter() {
return filter;
}
private DocumentFilter filter = new PaddingFilter();
});
tField.setColumns(PADDING_COLUMNS);
tField.setHorizontalAlignment(JTextField.RIGHT);
if (bound.equals(AxisBounds.MIN)) {
tField.setText(axisType.getMinimumDefaultPaddingAsText());
} else {
tField.setText(axisType.getMaximumDefaultPaddingAsText());
}
tField.addAncestorListener(new AncestorListener() {
@Override
public void ancestorAdded(AncestorEvent event) {
tField.selectAll();
tField.removeAncestorListener(this);
}
@Override
public void ancestorMoved(AncestorEvent event) {
}
@Override
public void ancestorRemoved(AncestorEvent event) {
}
});
return tField;
}
private void setFontToBold(JLabel item) {
item.setFont(item.getFont().deriveFont(Font.BOLD));
}
// The Time Axis table within the Plot Behavior area
private GridLinedPanel createGriddedTimeAxisPanel() {
JLabel titleMode = new JLabel(BUNDLE.getString("Mode.label"));
JLabel titleMin = new JLabel(BUNDLE.getString("Min.label"));
JLabel titleMinPadding = new JLabel(BUNDLE.getString("Min.label"));
JLabel titleMax = new JLabel(BUNDLE.getString("Max.label"));
JLabel titleMaxPadding = new JLabel(BUNDLE.getString("Max.label"));
JLabel titleSpan = new JLabel(BUNDLE.getString("Span.label"));
JLabel titleMax_Min = new JLabel("(" + BUNDLE.getString("MaxMinusMin.label") +")");
JPanel titlePanelSpan = new JPanel();
titlePanelSpan.setLayout(new BoxLayout(titlePanelSpan, BoxLayout.Y_AXIS));
titlePanelSpan.add(titleSpan);
titlePanelSpan.add(titleMax_Min);
titleSpan.setAlignmentX(Component.CENTER_ALIGNMENT);
titleMax_Min.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel titlePaddingOnRedraw = new JLabel(BUNDLE.getString("PaddingOnRedraw.label"));
setFontToBold(titleMode);
setFontToBold(titleMin);
setFontToBold(titleMax);
setFontToBold(titleMinPadding);
setFontToBold(titleMaxPadding);
setFontToBold(titlePaddingOnRedraw);
setFontToBold(titleSpan);
setFontToBold(titleMax_Min);
timeJumpMode = new JRadioButton(BUNDLE.getString("Jump.label"));
timeScrunchMode = new JRadioButton(BUNDLE.getString("Scrunch.label"));
JPanel timeJumpModePanel = new JPanel();
timeJumpModePanel.add(timeJumpMode);
JPanel timeScrunchModePanel = new JPanel();
timeScrunchModePanel.add(timeScrunchMode);
ButtonGroup modeGroup = new ButtonGroup();
modeGroup.add(timeJumpMode);
modeGroup.add(timeScrunchMode);
timeJumpMode.setSelected(true);
timeJumpPadding = createPaddingTextField(AxisType.TIME_IN_JUMP_MODE, AxisBounds.MAX);
timeScrunchPadding = createPaddingTextField(AxisType.TIME_IN_SCRUNCH_MODE, AxisBounds.MAX);
JPanel timeJumpPaddingPanel = new JPanel();
timeJumpPaddingPanel.add(timeJumpPadding);
timeJumpPaddingPanel.add(new JLabel(BUNDLE.getString("Percent.label")));
JPanel timeScrunchPaddingPanel = new JPanel();
timeScrunchPaddingPanel.add(timeScrunchPadding);
timeScrunchPaddingPanel.add(new JLabel(BUNDLE.getString("Percent.label")));
GridLinedPanel griddedPanel = new GridLinedPanel();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.ipadx = BEHAVIOR_CELLS_X_PADDING;
gbc.gridheight = 2;
griddedPanel.setGBC(gbc);
// Title row A
int row = 0;
griddedPanel.addCell(titleMode, 0, row);
griddedPanel.addCell(titleMin, 1, row);
griddedPanel.addCell(titleMax, 2, row);
gbc.gridheight = 2;
griddedPanel.addCell(titlePanelSpan, 3, row);
gbc.gridheight = 1;
gbc.gridwidth = 2;
griddedPanel.addCell(titlePaddingOnRedraw, 4, row);
gbc.gridwidth = 1;
// Title row B - only two entries
row++;
griddedPanel.addCell(titleMinPadding, 4, row);
griddedPanel.addCell(titleMaxPadding, 5, row);
// Row 1
row++;
griddedPanel.addCell(timeJumpModePanel, 0, row, GridBagConstraints.WEST);
griddedPanel.addCell(new JLabel(BUNDLE.getString("AutoAdjusts.label")), 1, row);
griddedPanel.addCell(new JLabel(BUNDLE.getString("AutoAdjusts.label")), 2, row);
griddedPanel.addCell(new JLabel(BUNDLE.getString("Fixed.label")), 3, row);
griddedPanel.addCell(new JLabel(BUNDLE.getString("Dash.label")), 4, row);
griddedPanel.addCell(timeJumpPaddingPanel, 5, row);
// Row 2
row++;
griddedPanel.addCell(timeScrunchModePanel, 0, row, GridBagConstraints.WEST);
griddedPanel.addCell(new JLabel(BUNDLE.getString("Fixed.label")), 1, row);
griddedPanel.addCell(new JLabel(BUNDLE.getString("AutoAdjusts.label")), 2, row);
griddedPanel.addCell(new JLabel(BUNDLE.getString("AutoAdjusts.label")), 3, row);
griddedPanel.addCell(new JLabel(BUNDLE.getString("Dash.label")), 4, row);
griddedPanel.addCell(timeScrunchPaddingPanel, 5, row);
return griddedPanel;
}
static class GridLinedPanel extends JPanel {
private static final long serialVersionUID = -1227455333903006294L;
private GridBagConstraints wrapGbc;
public GridLinedPanel() {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createLineBorder(Color.gray));
}
void setGBC(GridBagConstraints inputGbc) {
wrapGbc = inputGbc;
}
// Wrap each added ui control in a JPanel with a border
void addCell(JLabel uiControl, int xPosition, int yPosition) {
uiControl.setHorizontalAlignment(JLabel.CENTER);
wrapControlInPanel(uiControl, xPosition, yPosition);
}
// Wrap each added ui control in a JPanel with a border
void addCell(JPanel uiControl, int xPosition, int yPosition) {
wrapControlInPanel(uiControl, xPosition, yPosition);
}
private void wrapControlInPanel(JComponent uiControl, int xPosition,
int yPosition) {
JPanel wrapperPanel = new JPanel();
wrapperPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
wrapperPanel.add(uiControl, gbc);
wrapGbc.gridx = xPosition;
wrapGbc.gridy = yPosition;
wrapperPanel.setBorder(new LineBorder(Color.lightGray));
add(wrapperPanel, wrapGbc);
}
private void addCell(JComponent uiControl, int xPosition,
int yPosition, int alignment) {
JPanel wrapperPanel = new JPanel(new GridBagLayout());
wrapperPanel.setBorder(new LineBorder(Color.lightGray));
GridBagConstraints gbc = new GridBagConstraints();
if (alignment == GridBagConstraints.WEST) {
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
}
wrapperPanel.add(uiControl, gbc);
wrapGbc.gridx = xPosition;
wrapGbc.gridy = yPosition;
add(wrapperPanel, wrapGbc);
}
}
private JPanel getLineSetupPanel() {
JPanel panel = new JPanel();
drawLabel = new JLabel(BUNDLE.getString("Draw.label"));
linesOnly = new JRadioButton(BUNDLE.getString("LinesOnly.label"));
markersAndLines = new JRadioButton(BUNDLE.getString("MarkersAndLines.label"));
markersOnly = new JRadioButton(BUNDLE.getString("MarkersOnly.label"));
connectionLineTypeLabel = new JLabel(BUNDLE.getString("ConnectionLineType.label"));
direct = new JRadioButton(BUNDLE.getString("Direct.label"));
step = new JRadioButton(BUNDLE.getString("Step.label"));
direct.setToolTipText(BUNDLE.getString("Direct.tooltip"));
step.setToolTipText(BUNDLE.getString("Step.tooltip"));
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.ipady = 4;
gbc.ipadx = BEHAVIOR_CELLS_X_PADDING;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.NONE;
panel.add(drawLabel, gbc);
gbc.gridy++;
panel.add(linesOnly, gbc);
gbc.gridy++;
panel.add(markersAndLines, gbc);
gbc.gridy++;
panel.add(markersOnly, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridheight = 4;
gbc.fill = GridBagConstraints.VERTICAL;
panel.add(new JSeparator(JSeparator.VERTICAL), gbc);
gbc.gridx = 2;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.NONE;
panel.add(connectionLineTypeLabel, gbc);
gbc.gridy++;
panel.add(direct, gbc);
gbc.gridy++;
panel.add(step, gbc);
JPanel parent = new JPanel();
parent.setLayout(new BorderLayout());
parent.add(panel, BorderLayout.WEST);
parent.setBorder(SETUP_AND_BEHAVIOR_MARGINS);
ButtonGroup drawGroup = new ButtonGroup();
drawGroup.add(linesOnly);
drawGroup.add(markersAndLines);
drawGroup.add(markersOnly);
ButtonGroup connectionGroup = new ButtonGroup();
connectionGroup.add(direct);
connectionGroup.add(step);
ActionListener disabler = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean linesShowing = !markersOnly.isSelected();
connectionLineTypeLabel.setEnabled(linesShowing);
direct.setEnabled(linesShowing);
step.setEnabled(linesShowing);
}
};
linesOnly.addActionListener(disabler);
markersAndLines.addActionListener(disabler);
markersOnly.addActionListener(disabler);
return parent;
}
/**
* Set the state of the widgets in the setting panel according to those specified in the parameters.
* @param timeAxisSetting
* @param xAxisMaximumLocation
* @param yAxisMaximumLocation
* @param timeAxisSubsequentSetting
* @param nonTimeAxisSubsequentMinSetting
* @param nonTimeAxisSubsequentMaxSetting
* @param nonTimeMax
* @param nonTimeMin
* @param minTime
* @param maxTime
* @param timePadding
* @param plotLineDraw indicates how to draw the plot (whether to include lines, markers, etc)
* @param plotLineConnectionType the method of connecting lines on the plot
*/
public void setControlPanelState(AxisOrientationSetting timeAxisSetting,
XAxisMaximumLocationSetting xAxisMaximumLocation,
YAxisMaximumLocationSetting yAxisMaximumLocation,
TimeAxisSubsequentBoundsSetting timeAxisSubsequentSetting,
NonTimeAxisSubsequentBoundsSetting nonTimeAxisSubsequentMinSetting,
NonTimeAxisSubsequentBoundsSetting nonTimeAxisSubsequentMaxSetting,
double nonTimeMax, double nonTimeMin, long minTime,
long maxTime,
double timePadding,
double nonTimePaddingMax,
double nonTimePaddingMin,
boolean groupStackPlotsByOrdinalPosition, boolean timeAxisPinned,
PlotLineDrawingFlags plotLineDraw,
PlotLineConnectionType plotLineConnectionType) {
if (plotViewManifestion.getPlot() == null) {
throw new IllegalArgumentException("Plot Setting control Panel cannot be setup if the PltViewManifestation's plot is null");
}
pinTimeAxis.setSelected(timeAxisPinned);
assert nonTimeMin < nonTimeMax : "Non Time min >= Non Time Max";
assert minTime < maxTime : "Time min >= Time Max " + minTime + " " + maxTime;
// Setup time axis setting.
if (timeAxisSetting == AxisOrientationSetting.X_AXIS_AS_TIME) {
xAxisAsTimeRadioButton.setSelected(true);
yAxisAsTimeRadioButton.setSelected(false);
xAxisAsTimeRadioButtonActionPerformed();
} else if (timeAxisSetting == AxisOrientationSetting.Y_AXIS_AS_TIME) {
xAxisAsTimeRadioButton.setSelected(false);
yAxisAsTimeRadioButton.setSelected(true);
yAxisAsTimeRadioButtonActionPerformed();
} else {
assert false :"Time must be specified as being on either the X or Y axis.";
}
// X Max setting
if (xAxisMaximumLocation == XAxisMaximumLocationSetting.MAXIMUM_AT_RIGHT) {
xMaxAtRight.setSelected(true);
xMaxAtLeft.setSelected(false);
xMaxAtRightActionPerformed();
} else if (xAxisMaximumLocation == XAxisMaximumLocationSetting.MAXIMUM_AT_LEFT) {
xMaxAtRight.setSelected(false);
xMaxAtLeft.setSelected(true);
xMaxAtLeftActionPerformed();
} else {
assert false: "X max location must be set.";
}
// Y Max setting
if (yAxisMaximumLocation == YAxisMaximumLocationSetting.MAXIMUM_AT_TOP) {
yMaxAtTop.setSelected(true);
yMaxAtBottom.setSelected(false);
yMaxAtTopActionPerformed();
} else if (yAxisMaximumLocation == YAxisMaximumLocationSetting.MAXIMUM_AT_BOTTOM) {
yMaxAtTop.setSelected(false);
yMaxAtBottom.setSelected(true);
yMaxAtBottomActionPerformed();
} else {
assert false: "Y max location must be set.";
}
if (timeAxisSubsequentSetting == TimeAxisSubsequentBoundsSetting.JUMP) {
timeJumpMode.setSelected(true);
timeScrunchMode.setSelected(false);
timeJumpPadding.setText(timePaddingFormat.format(timePadding * 100));
timeAxisMaxAuto.setSelected(false);
timeAxisMaxManual.setSelected(false);
timeAxisMaxCurrent.setSelected(true);
timeAxisMinAuto.setSelected(false);
timeAxisMinManual.setSelected(false);
timeAxisMinCurrent.setSelected(true);
workCalendar.setTime(plotViewManifestion.getPlot().getMaxTime().getTime());
timeAxisMaxManualValue.setTime(workCalendar);
workCalendar.setTime(plotViewManifestion.getPlot().getMinTime().getTime());
timeAxisMinManualValue.setTime(workCalendar);
} else if (timeAxisSubsequentSetting == TimeAxisSubsequentBoundsSetting.SCRUNCH) {
timeJumpMode.setSelected(false);
timeScrunchMode.setSelected(true);
timeScrunchPadding.setText(timePaddingFormat.format(timePadding * 100));
timeAxisMaxAuto.setSelected(false);
timeAxisMaxManual.setSelected(false);
timeAxisMaxCurrent.setSelected(true);
timeAxisMinAuto.setSelected(false);
timeAxisMinManual.setSelected(false);
timeAxisMinCurrent.setSelected(true);
GregorianCalendar minCalendar = new GregorianCalendar();
minCalendar.setTimeZone(dateFormat.getTimeZone());
minCalendar.setTimeInMillis(minTime);
timeAxisMinManualValue.setTime(minCalendar);
} else {
assert false : "No time subsequent mode selected";
}
// Set the Current Min and Max values
timeAxisMinCurrentValue.setTime(plotViewManifestion.getPlot().getMinTime());
timeAxisMaxCurrentValue.setTime(plotViewManifestion.getPlot().getMaxTime());
// Non Time Subsequent Settings
// Min
if (NonTimeAxisSubsequentBoundsSetting.AUTO == nonTimeAxisSubsequentMinSetting) {
nonTimeMinAutoAdjustMode.setSelected(true);
nonTimeMinFixedMode.setSelected(false);
nonTimeMinSemiFixedMode.setSelected(false);
nonTimeMinSemiFixedMode.setEnabled(false);
} else if (NonTimeAxisSubsequentBoundsSetting.FIXED == nonTimeAxisSubsequentMinSetting) {
nonTimeMinAutoAdjustMode.setSelected(false);
nonTimeMinFixedMode.setSelected(true);
nonTimeMinSemiFixedMode.setSelected(false);
nonTimeMinSemiFixedMode.setEnabled(true);
} else if (NonTimeAxisSubsequentBoundsSetting.SEMI_FIXED == nonTimeAxisSubsequentMinSetting) {
nonTimeMinAutoAdjustMode.setSelected(false);
nonTimeMinFixedMode.setSelected(true);
nonTimeMinSemiFixedMode.setSelected(true);
nonTimeMinSemiFixedMode.setEnabled(true);
} else {
assert false : "No non time min subsequent setting specified";
}
// Max
if (NonTimeAxisSubsequentBoundsSetting.AUTO == nonTimeAxisSubsequentMaxSetting) {
nonTimeMaxAutoAdjustMode.setSelected(true);
nonTimeMaxFixedMode.setSelected(false);
nonTimeMaxSemiFixedMode.setSelected(false);
nonTimeMaxSemiFixedMode.setEnabled(false);
} else if (NonTimeAxisSubsequentBoundsSetting.FIXED == nonTimeAxisSubsequentMaxSetting) {
nonTimeMaxAutoAdjustMode.setSelected(false);
nonTimeMaxFixedMode.setSelected(true);
nonTimeMaxSemiFixedMode.setSelected(false);
nonTimeMaxSemiFixedMode.setEnabled(true);
} else if (NonTimeAxisSubsequentBoundsSetting.SEMI_FIXED == nonTimeAxisSubsequentMaxSetting) {
nonTimeMaxAutoAdjustMode.setSelected(false);
nonTimeMaxFixedMode.setSelected(true);
nonTimeMaxSemiFixedMode.setSelected(true);
nonTimeMaxSemiFixedMode.setEnabled(true);
} else {
assert false : "No non time max subsequent setting specified";
}
// Non time Axis Settings.
// Non-Time Min. Control Panel
if (NonTimeAxisSubsequentBoundsSetting.AUTO == nonTimeAxisSubsequentMinSetting) {
nonTimeAxisMinCurrent.setSelected(true);
nonTimeAxisMinManual.setSelected(false);
nonTimeAxisMinAutoAdjust.setSelected(false);
nonTimeMinPadding.setText(nonTimePaddingFormat.format(nonTimePaddingMin * 100));
} else if (NonTimeAxisSubsequentBoundsSetting.SEMI_FIXED == nonTimeAxisSubsequentMinSetting
|| NonTimeAxisSubsequentBoundsSetting.FIXED == nonTimeAxisSubsequentMinSetting) {
nonTimeAxisMinCurrent.setSelected(false);
if (!nonTimeAxisMinManual.isSelected()) {
nonTimeAxisMinManual.setSelected(true);
}
nonTimeAxisMinManualValue.setText(nonTimePaddingFormat.format(nonTimeMin));
nonTimeAxisMinAutoAdjust.setSelected(false);
}
// Non-Time Max. Control Panel
if (NonTimeAxisSubsequentBoundsSetting.AUTO == nonTimeAxisSubsequentMaxSetting) {
nonTimeAxisMaxCurrent.setSelected(true);
nonTimeAxisMaxManual.setSelected(false);
nonTimeAxisMaxAutoAdjust.setSelected(false);
nonTimeMaxPadding.setText(nonTimePaddingFormat.format(nonTimePaddingMax * 100));
} else if (NonTimeAxisSubsequentBoundsSetting.SEMI_FIXED == nonTimeAxisSubsequentMaxSetting
|| NonTimeAxisSubsequentBoundsSetting.FIXED == nonTimeAxisSubsequentMaxSetting) {
nonTimeAxisMaxCurrent.setSelected(false);
if (!nonTimeAxisMaxManual.isSelected()) {
nonTimeAxisMaxManual.setSelected(true);
}
nonTimeAxisMaxManualValue.setText(nonTimePaddingFormat.format(nonTimeMax));
nonTimeAxisMaxAutoAdjust.setSelected(false);
}
// Draw
if (plotLineDraw.drawLine() && plotLineDraw.drawMarkers()) {
markersAndLines.setSelected(true);
} else if (plotLineDraw.drawLine()) {
linesOnly.setSelected(true);
} else if (plotLineDraw.drawMarkers()) {
markersOnly.setSelected(true);
} else {
logger.warn("Plot line drawing configuration is unset.");
}
// Connection line type
if (plotLineConnectionType == PlotLineConnectionType.DIRECT) {
direct.setSelected(true);
} else if (plotLineConnectionType == PlotLineConnectionType.STEP_X_THEN_Y) {
step.setSelected(true);
}
updateTimeAxisControls();
groupByCollection.setSelected(!groupStackPlotsByOrdinalPosition);
}
// Get the plot setting from the GUI widgets, inform the plot controller and request a new plot.
void setupPlot() {
// Axis on which time will be displayed
if ( xAxisAsTimeRadioButton.isSelected() ) {
assert !yAxisAsTimeRadioButton.isSelected() : "Both axis location boxes are selected!";
controller.setTimeAxis(AxisOrientationSetting.X_AXIS_AS_TIME);
} else if (yAxisAsTimeRadioButton.isSelected()) {
controller.setTimeAxis(AxisOrientationSetting.Y_AXIS_AS_TIME);
} else {
assert false: "Time must be specified as being on either the X or Y axis.";
controller.setTimeAxis(AxisOrientationSetting.X_AXIS_AS_TIME);
}
// X Max Location setting
if (xMaxAtRight.isSelected()) {
assert !xMaxAtLeft.isSelected(): "Both x max location settings are selected!";
controller.setXAxisMaximumLocation(XAxisMaximumLocationSetting.MAXIMUM_AT_RIGHT);
} else if (xMaxAtLeft.isSelected()) {
controller.setXAxisMaximumLocation(XAxisMaximumLocationSetting.MAXIMUM_AT_LEFT);
} else {
assert false: "X max location must be set.";
controller.setXAxisMaximumLocation(XAxisMaximumLocationSetting.MAXIMUM_AT_RIGHT);
}
// Y Max Location setting
if (yMaxAtTop.isSelected()) {
assert !yMaxAtBottom.isSelected(): "Both y max location settings are selected!";
controller.setYAxisMaximumLocation(YAxisMaximumLocationSetting.MAXIMUM_AT_TOP);
} else if (yMaxAtBottom.isSelected()) {
controller.setYAxisMaximumLocation(YAxisMaximumLocationSetting.MAXIMUM_AT_BOTTOM);
} else {
assert false: "Y max location must be set.";
controller.setYAxisMaximumLocation(YAxisMaximumLocationSetting.MAXIMUM_AT_TOP);
}
controller.setTimeAxisPinned(pinTimeAxis.isSelected());
// Time Subsequent settings
if (timeJumpMode.isSelected()) {
assert !timeScrunchMode.isSelected() : "Both jump and scruch are set!";
controller.setTimeAxisSubsequentBounds(TimeAxisSubsequentBoundsSetting.JUMP);
controller.setTimePadding(Double.valueOf(timeJumpPadding.getText()).doubleValue() / 100.);
} else if (timeScrunchMode.isSelected()) {
assert !timeJumpMode.isSelected() : "Both scrunch and jump are set!";
controller.setTimeAxisSubsequentBounds(TimeAxisSubsequentBoundsSetting.SCRUNCH);
controller.setTimePadding(Double.valueOf(timeScrunchPadding.getText()).doubleValue() / 100.);
} else {
assert false : "No time subsequent mode selected";
controller.setTimeAxisSubsequentBounds(TimeAxisSubsequentBoundsSetting.JUMP);
}
// Non Time Subsequent Settings
// Min
if (nonTimeMinAutoAdjustMode.isSelected()) {
assert !nonTimeMinFixedMode.isSelected() : "Both non time min subsequent modes are selected!";
controller.setNonTimeAxisSubsequentMinBounds(NonTimeAxisSubsequentBoundsSetting.AUTO);
} else if (nonTimeMinFixedMode.isSelected() && !nonTimeMinSemiFixedMode.isSelected()) {
assert !nonTimeMinAutoAdjustMode.isSelected() : "Both non time min subsequent modes are selected!";
controller.setNonTimeAxisSubsequentMinBounds(NonTimeAxisSubsequentBoundsSetting.FIXED);
} else if (nonTimeMinFixedMode.isSelected() && nonTimeMinSemiFixedMode.isSelected()) {
assert !nonTimeMinAutoAdjustMode.isSelected() : "Both non time min subsequent modes are selected!";
controller.setNonTimeAxisSubsequentMinBounds(NonTimeAxisSubsequentBoundsSetting.SEMI_FIXED);
} else {
assert false : "No non time min subsequent setting specified";
controller.setNonTimeAxisSubsequentMinBounds(NonTimeAxisSubsequentBoundsSetting.AUTO);
}
controller.setNonTimeMinPadding(Double.parseDouble(nonTimeMinPadding.getText()) / 100.);
// Max
if (nonTimeMaxAutoAdjustMode.isSelected()) {
assert !nonTimeMaxFixedMode.isSelected() : "Both non time max subsequent modes are selected!";
controller.setNonTimeAxisSubsequentMaxBounds(NonTimeAxisSubsequentBoundsSetting.AUTO);
} else if (nonTimeMaxFixedMode.isSelected() && !nonTimeMaxSemiFixedMode.isSelected()) {
assert !nonTimeMaxAutoAdjustMode.isSelected() : "Both non time max subsequent modes are selected!";
controller.setNonTimeAxisSubsequentMaxBounds(NonTimeAxisSubsequentBoundsSetting.FIXED);
} else if (nonTimeMaxFixedMode.isSelected() && nonTimeMaxSemiFixedMode.isSelected()) {
assert !nonTimeMaxAutoAdjustMode.isSelected() : "Both non time max subsequent modes are selected!";
controller.setNonTimeAxisSubsequentMaxBounds(NonTimeAxisSubsequentBoundsSetting.SEMI_FIXED);
} else {
assert false : "No non time ax subsequent setting specified";
controller.setNonTimeAxisSubsequentMaxBounds(NonTimeAxisSubsequentBoundsSetting.AUTO);
}
controller.setNonTimeMaxPadding(Double.valueOf(nonTimeMaxPadding.getText()).doubleValue() / 100.);
// Time
GregorianCalendar timeMin = recycledCalendarA;
GregorianCalendar timeMax = recycledCalendarB;
if (timeAxisMinAuto.isSelected()) {
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(plotViewManifestion.getCurrentMCTTime());
timeMin = gc;
} else if (timeAxisMinManual.isSelected()) {
timeMin.setTimeInMillis(timeAxisMinManualValue.getValueInMillis());
} else if (timeAxisMinCurrent.isSelected()) {
timeMin.setTimeInMillis(timeAxisMinCurrentValue.getTimeInMillis());
} else throw new IllegalArgumentException("No time setting button is selected.");
if (timeAxisMaxAuto.isSelected()) {
timeMax.setTime(timeMin.getTime());
timeMax.add(Calendar.SECOND, timeSpanValue.getSecond());
timeMax.add(Calendar.MINUTE, timeSpanValue.getMinute());
timeMax.add(Calendar.HOUR_OF_DAY, timeSpanValue.getHourOfDay());
timeMax.add(Calendar.DAY_OF_YEAR, timeSpanValue.getDayOfYear());
} else if (timeAxisMaxManual.isSelected()) {
timeMax.setTimeInMillis(timeAxisMaxManualValue.getValueInMillis());
} else if (timeAxisMaxCurrent.isSelected()) {
timeMax.setTimeInMillis(timeAxisMaxCurrentValue.getTimeInMillis());
} else throw new IllegalArgumentException("No time setting button is selected.");
// Check that values are valid.
assert timeMin.getTimeInMillis() < timeMax.getTimeInMillis() : "Time min is > timeMax. Min = "
+ CalendarDump.dumpDateAndTime(timeMin) + ", Max = " + CalendarDump.dumpDateAndTime(timeMax);
if (timeMin.getTimeInMillis() < timeMax.getTimeInMillis()) {
controller.setTimeMinMaxValues(timeMin, timeMax);
} else {
logger.warn("User error - The minimum time was not less than the maximum time");
}
double nonTimeMin = 0.0;
double nonTimeMax = 1.0;
// Non time
if (nonTimeAxisMinCurrent.isSelected()) {
nonTimeMin = plotViewManifestion.getMinFeedValue();
} else if (nonTimeAxisMinManual.isSelected()) {
nonTimeMin = Double.valueOf(nonTimeAxisMinManualValue.getText()).doubleValue();
} else if (nonTimeAxisMinAutoAdjust.isSelected()) {
nonTimeMin = nonTimeAxisMinAutoAdjustValue.getValue();
} else {
logger.error("Non Time min axis setting not yet supported.");
}
if (nonTimeAxisMaxCurrent.isSelected()) {
nonTimeMax = plotViewManifestion.getMaxFeedValue();
} else if (nonTimeAxisMaxManual.isSelected()) {
nonTimeMax = Double.valueOf(nonTimeAxisMaxManualValue.getText()).doubleValue();
} else if (nonTimeAxisMaxAutoAdjust.isSelected()) {
nonTimeMax = nonTimeAxisMaxAutoAdjustValue.getValue();
} else {
logger.error("Non Time Max axis setting not yet supported.");
}
if (nonTimeMin >= nonTimeMax) {
nonTimeMin = 0.0;
nonTimeMax = 1.0;
}
// Draw
controller.setPlotLineDraw(new PlotLineDrawingFlags(
linesOnly.isSelected() || markersAndLines.isSelected(),
markersOnly.isSelected() || markersAndLines.isSelected()
));
// Connection line type
if (direct.isSelected()) {
controller.setPlotLineConnectionType(PlotLineConnectionType.DIRECT);
} else if (step.isSelected()) {
controller.setPlotLineConnectionType(PlotLineConnectionType.STEP_X_THEN_Y);
}
controller.setUseOrdinalPositionToGroupSubplots(!groupByCollection.isSelected());
controller.setNonTimeMinMaxValues(nonTimeMin, nonTimeMax);
// Settings complete. Create plot.
controller.createPlot();
}
/**
* Return the controller associated with this settings panel. Usage intent is for testing only,
* hence this is package private.
* @return
*/
PlotSettingController getController() {
return controller;
}
public void updateControlsToMatchPlot() {
resetButton.setEnabled(true);
resetButton.doClick(0);
}
}
| 1no label
|
fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_view_PlotSettingsControlPanel.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
|
420 |
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface AdminPresentationOperationTypes {
/**
* <p>How should the system execute an addition for this item</p>
*
* <p>OperationType BASIC will result in the item being inserted<BR>
* OperationType ADORNEDTARGETLIST will result in a adorned target entity being added (not either of the associated entities).<BR>
* CrossSaleProductImpl is an example of an adorned target entity, since it adds additional fields around the target Product entity.<BR>
* OperationType MAP will result in the item being added to the requisite map in the containing entity.</p>
*
* @return the type of the add operation
*/
OperationType addType() default OperationType.BASIC;
/**
* <p>How should the system execute an update for this item</p>
*
* <p>OperationType BASIC will result in the item being updated based on it's primary key<BR>
* OperationType ADORNEDTARGETLIST will result in a join structure entity being updated (not either of the associated entities).<BR>
* CrossSaleProductImpl is an example of an adorned target entity, since it adds additional fields around the target Product entity.<BR>
* OperationType MAP will result in the item being updated to the requisite map in the containing entity.</p>
*
* @return the type of the update operation
*/
OperationType updateType() default OperationType.BASIC;
/**
* <p>How should the system execute a removal of this item.</p>
*
* <p>OperationType BASIC will result in the item being removed based on its primary key<BR>
* OperationType NONDESTRUCTIVEREMOVE will result in the item being removed from the containing list in the containing entity. This
* is useful when you don't want the item to actually be deleted, but simply removed from the parent collection.<BR>
* OperationType ADORNEDTARGETLIST will result in a join structure being deleted (not either of the associated entities).<BR>
* CrossSaleProductImpl is an example of an adorned target entity, since it adds additional fields around the target Product entity.<BR>
* OperationType MAP will result in the item being removed from the requisite map in the containing entity.</p>
*
* @return the type of remove operation
*/
OperationType removeType() default OperationType.BASIC;
/**
* <p>How should the system execute a fetch</p>
*
* <p>OperationType BASIC will result in a search for items having one or more basic properties matches<BR>
* OperationType ADORNEDTARGETLIST will result in search for target items that match the parent association in the adorned target entity.<BR>
* CrossSaleProductImpl is an example of an adorned target entity, since it adds additional fields around the target Product entity.<BR>
* OperationType MAP will result retrieval of all map entries for the requisite map in the containing entity.</p>
*
* @return the type of the fetch operation
*/
OperationType fetchType() default OperationType.BASIC;
/**
* <p>OperationType values are generally ignored for inspect and should be defined as BASIC for consistency in most circumstances.
* This API is meant to support future persistence modules where specialized inspect phase management may be required.</p>
*
* @return the type of the inspect operation
*/
OperationType inspectType() default OperationType.BASIC;
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentationOperationTypes.java
|
4,212 |
public class StoreModule extends AbstractModule {
private final Settings settings;
private final IndexStore indexStore;
private Class<? extends Distributor> distributor;
public StoreModule(Settings settings, IndexStore indexStore) {
this.indexStore = indexStore;
this.settings = settings;
}
public void setDistributor(Class<? extends Distributor> distributor) {
this.distributor = distributor;
}
@Override
protected void configure() {
bind(DirectoryService.class).to(indexStore.shardDirectory()).asEagerSingleton();
bind(Store.class).asEagerSingleton();
if (distributor == null) {
distributor = loadDistributor(settings);
}
bind(Distributor.class).to(distributor).asEagerSingleton();
}
private Class<? extends Distributor> loadDistributor(Settings settings) {
final Class<? extends Distributor> distributor;
final String type = settings.get("index.store.distributor");
if ("least_used".equals(type)) {
distributor = LeastUsedDistributor.class;
} else if ("random".equals(type)) {
distributor = RandomWeightedDistributor.class;
} else {
distributor = settings.getAsClass("index.store.distributor", LeastUsedDistributor.class,
"org.elasticsearch.index.store.distributor.", "Distributor");
}
return distributor;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_store_StoreModule.java
|
5,402 |
public abstract class FieldDataSource {
public static class MetaData {
public static final MetaData UNKNOWN = new MetaData();
public enum Uniqueness {
UNIQUE,
NOT_UNIQUE,
UNKNOWN;
public boolean unique() {
return this == UNIQUE;
}
}
private long maxAtomicUniqueValuesCount = -1;
private boolean multiValued = true;
private Uniqueness uniqueness = Uniqueness.UNKNOWN;
private MetaData() {}
private MetaData(MetaData other) {
this.maxAtomicUniqueValuesCount = other.maxAtomicUniqueValuesCount;
this.multiValued = other.multiValued;
this.uniqueness = other.uniqueness;
}
private MetaData(long maxAtomicUniqueValuesCount, boolean multiValued, Uniqueness uniqueness) {
this.maxAtomicUniqueValuesCount = maxAtomicUniqueValuesCount;
this.multiValued = multiValued;
this.uniqueness = uniqueness;
}
public long maxAtomicUniqueValuesCount() {
return maxAtomicUniqueValuesCount;
}
public boolean multiValued() {
return multiValued;
}
public Uniqueness uniqueness() {
return uniqueness;
}
public static MetaData load(IndexFieldData indexFieldData, SearchContext context) {
MetaData metaData = new MetaData();
metaData.uniqueness = Uniqueness.UNIQUE;
for (AtomicReaderContext readerContext : context.searcher().getTopReaderContext().leaves()) {
AtomicFieldData fieldData = indexFieldData.load(readerContext);
metaData.multiValued |= fieldData.isMultiValued();
metaData.maxAtomicUniqueValuesCount = Math.max(metaData.maxAtomicUniqueValuesCount, fieldData.getNumberUniqueValues());
}
return metaData;
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(MetaData other) {
return new Builder(other);
}
public static class Builder {
private final MetaData metaData;
private Builder() {
metaData = new MetaData();
}
private Builder(MetaData metaData) {
this.metaData = new MetaData(metaData);
}
public Builder maxAtomicUniqueValuesCount(long maxAtomicUniqueValuesCount) {
metaData.maxAtomicUniqueValuesCount = maxAtomicUniqueValuesCount;
return this;
}
public Builder multiValued(boolean multiValued) {
metaData.multiValued = multiValued;
return this;
}
public Builder uniqueness(Uniqueness uniqueness) {
metaData.uniqueness = uniqueness;
return this;
}
public MetaData build() {
return metaData;
}
}
}
/**
* Get the current {@link BytesValues}.
*/
public abstract BytesValues bytesValues();
/**
* Ask the underlying data source to provide pre-computed hashes, optional operation.
*/
public void setNeedsHashes(boolean needsHashes) {}
public abstract MetaData metaData();
public static abstract class Bytes extends FieldDataSource {
public static abstract class WithOrdinals extends Bytes {
public abstract BytesValues.WithOrdinals bytesValues();
public static class FieldData extends WithOrdinals implements ReaderContextAware {
protected boolean needsHashes;
protected final IndexFieldData.WithOrdinals<?> indexFieldData;
protected final MetaData metaData;
protected AtomicFieldData.WithOrdinals<?> atomicFieldData;
private BytesValues.WithOrdinals bytesValues;
public FieldData(IndexFieldData.WithOrdinals<?> indexFieldData, MetaData metaData) {
this.indexFieldData = indexFieldData;
this.metaData = metaData;
needsHashes = false;
}
@Override
public MetaData metaData() {
return metaData;
}
public final void setNeedsHashes(boolean needsHashes) {
this.needsHashes = needsHashes;
}
@Override
public void setNextReader(AtomicReaderContext reader) {
atomicFieldData = indexFieldData.load(reader);
if (bytesValues != null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
}
@Override
public BytesValues.WithOrdinals bytesValues() {
if (bytesValues == null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
return bytesValues;
}
}
}
public static class FieldData extends Bytes implements ReaderContextAware {
protected boolean needsHashes;
protected final IndexFieldData<?> indexFieldData;
protected final MetaData metaData;
protected AtomicFieldData<?> atomicFieldData;
private BytesValues bytesValues;
public FieldData(IndexFieldData<?> indexFieldData, MetaData metaData) {
this.indexFieldData = indexFieldData;
this.metaData = metaData;
needsHashes = false;
}
@Override
public MetaData metaData() {
return metaData;
}
public final void setNeedsHashes(boolean needsHashes) {
this.needsHashes = needsHashes;
}
@Override
public void setNextReader(AtomicReaderContext reader) {
atomicFieldData = indexFieldData.load(reader);
if (bytesValues != null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
}
@Override
public org.elasticsearch.index.fielddata.BytesValues bytesValues() {
if (bytesValues == null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
return bytesValues;
}
}
public static class Script extends Bytes {
private final ScriptBytesValues values;
public Script(SearchScript script) {
values = new ScriptBytesValues(script);
}
@Override
public MetaData metaData() {
return MetaData.UNKNOWN;
}
@Override
public org.elasticsearch.index.fielddata.BytesValues bytesValues() {
return values;
}
}
public static class SortedAndUnique extends Bytes implements ReaderContextAware {
private final FieldDataSource delegate;
private final MetaData metaData;
private BytesValues bytesValues;
public SortedAndUnique(FieldDataSource delegate) {
this.delegate = delegate;
this.metaData = MetaData.builder(delegate.metaData()).uniqueness(MetaData.Uniqueness.UNIQUE).build();
}
@Override
public MetaData metaData() {
return metaData;
}
@Override
public void setNextReader(AtomicReaderContext reader) {
bytesValues = null; // order may change per-segment -> reset
}
@Override
public org.elasticsearch.index.fielddata.BytesValues bytesValues() {
if (bytesValues == null) {
bytesValues = delegate.bytesValues();
if (bytesValues.isMultiValued() &&
(!delegate.metaData().uniqueness.unique() || bytesValues.getOrder() != Order.BYTES)) {
bytesValues = new SortedUniqueBytesValues(bytesValues);
}
}
return bytesValues;
}
static class SortedUniqueBytesValues extends FilterBytesValues {
final BytesRef spare;
int[] sortedIds;
final BytesRefHash bytes;
int numUniqueValues;
int pos = Integer.MAX_VALUE;
public SortedUniqueBytesValues(BytesValues delegate) {
super(delegate);
bytes = new BytesRefHash();
spare = new BytesRef();
}
@Override
public int setDocument(int docId) {
final int numValues = super.setDocument(docId);
if (numValues == 0) {
sortedIds = null;
return 0;
}
bytes.clear();
bytes.reinit();
for (int i = 0; i < numValues; ++i) {
bytes.add(super.nextValue(), super.currentValueHash());
}
numUniqueValues = bytes.size();
sortedIds = bytes.sort(BytesRef.getUTF8SortedAsUnicodeComparator());
pos = 0;
return numUniqueValues;
}
@Override
public BytesRef nextValue() {
bytes.get(sortedIds[pos++], spare);
return spare;
}
@Override
public int currentValueHash() {
return spare.hashCode();
}
@Override
public Order getOrder() {
return Order.BYTES;
}
}
}
}
public static abstract class Numeric extends FieldDataSource {
/** Whether the underlying data is floating-point or not. */
public abstract boolean isFloatingPoint();
/** Get the current {@link LongValues}. */
public abstract LongValues longValues();
/** Get the current {@link DoubleValues}. */
public abstract DoubleValues doubleValues();
public static class WithScript extends Numeric {
private final LongValues longValues;
private final DoubleValues doubleValues;
private final FieldDataSource.WithScript.BytesValues bytesValues;
public WithScript(Numeric delegate, SearchScript script) {
this.longValues = new LongValues(delegate, script);
this.doubleValues = new DoubleValues(delegate, script);
this.bytesValues = new FieldDataSource.WithScript.BytesValues(delegate, script);
}
@Override
public boolean isFloatingPoint() {
return true; // even if the underlying source produces longs, scripts can change them to doubles
}
@Override
public BytesValues bytesValues() {
return bytesValues;
}
@Override
public LongValues longValues() {
return longValues;
}
@Override
public DoubleValues doubleValues() {
return doubleValues;
}
@Override
public MetaData metaData() {
return MetaData.UNKNOWN;
}
static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final Numeric source;
private final SearchScript script;
public LongValues(Numeric source, SearchScript script) {
super(true);
this.source = source;
this.script = script;
}
@Override
public int setDocument(int docId) {
return source.longValues().setDocument(docId);
}
@Override
public long nextValue() {
script.setNextVar("_value", source.longValues().nextValue());
return script.runAsLong();
}
}
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues {
private final Numeric source;
private final SearchScript script;
public DoubleValues(Numeric source, SearchScript script) {
super(true);
this.source = source;
this.script = script;
}
@Override
public int setDocument(int docId) {
return source.doubleValues().setDocument(docId);
}
@Override
public double nextValue() {
script.setNextVar("_value", source.doubleValues().nextValue());
return script.runAsDouble();
}
}
}
public static class FieldData extends Numeric implements ReaderContextAware {
protected boolean needsHashes;
protected final IndexNumericFieldData<?> indexFieldData;
protected final MetaData metaData;
protected AtomicNumericFieldData atomicFieldData;
private BytesValues bytesValues;
private LongValues longValues;
private DoubleValues doubleValues;
public FieldData(IndexNumericFieldData<?> indexFieldData, MetaData metaData) {
this.indexFieldData = indexFieldData;
this.metaData = metaData;
needsHashes = false;
}
@Override
public MetaData metaData() {
return metaData;
}
@Override
public boolean isFloatingPoint() {
return indexFieldData.getNumericType().isFloatingPoint();
}
@Override
public final void setNeedsHashes(boolean needsHashes) {
this.needsHashes = needsHashes;
}
@Override
public void setNextReader(AtomicReaderContext reader) {
atomicFieldData = indexFieldData.load(reader);
if (bytesValues != null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
if (longValues != null) {
longValues = atomicFieldData.getLongValues();
}
if (doubleValues != null) {
doubleValues = atomicFieldData.getDoubleValues();
}
}
@Override
public org.elasticsearch.index.fielddata.BytesValues bytesValues() {
if (bytesValues == null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
return bytesValues;
}
@Override
public org.elasticsearch.index.fielddata.LongValues longValues() {
if (longValues == null) {
longValues = atomicFieldData.getLongValues();
}
assert longValues.getOrder() == Order.NUMERIC;
return longValues;
}
@Override
public org.elasticsearch.index.fielddata.DoubleValues doubleValues() {
if (doubleValues == null) {
doubleValues = atomicFieldData.getDoubleValues();
}
assert doubleValues.getOrder() == Order.NUMERIC;
return doubleValues;
}
}
public static class Script extends Numeric {
private final ScriptValueType scriptValueType;
private final ScriptDoubleValues doubleValues;
private final ScriptLongValues longValues;
private final ScriptBytesValues bytesValues;
public Script(SearchScript script, ScriptValueType scriptValueType) {
this.scriptValueType = scriptValueType;
longValues = new ScriptLongValues(script);
doubleValues = new ScriptDoubleValues(script);
bytesValues = new ScriptBytesValues(script);
}
@Override
public MetaData metaData() {
return MetaData.UNKNOWN;
}
@Override
public boolean isFloatingPoint() {
return scriptValueType != null ? scriptValueType.isFloatingPoint() : true;
}
@Override
public LongValues longValues() {
return longValues;
}
@Override
public DoubleValues doubleValues() {
return doubleValues;
}
@Override
public BytesValues bytesValues() {
return bytesValues;
}
}
public static class SortedAndUnique extends Numeric implements ReaderContextAware {
private final Numeric delegate;
private final MetaData metaData;
private LongValues longValues;
private DoubleValues doubleValues;
private BytesValues bytesValues;
public SortedAndUnique(Numeric delegate) {
this.delegate = delegate;
this.metaData = MetaData.builder(delegate.metaData()).uniqueness(MetaData.Uniqueness.UNIQUE).build();
}
@Override
public MetaData metaData() {
return metaData;
}
@Override
public boolean isFloatingPoint() {
return delegate.isFloatingPoint();
}
@Override
public void setNextReader(AtomicReaderContext reader) {
longValues = null; // order may change per-segment -> reset
doubleValues = null;
bytesValues = null;
}
@Override
public org.elasticsearch.index.fielddata.LongValues longValues() {
if (longValues == null) {
longValues = delegate.longValues();
if (longValues.isMultiValued() &&
(!delegate.metaData().uniqueness.unique() || longValues.getOrder() != Order.NUMERIC)) {
longValues = new SortedUniqueLongValues(longValues);
}
}
return longValues;
}
@Override
public org.elasticsearch.index.fielddata.DoubleValues doubleValues() {
if (doubleValues == null) {
doubleValues = delegate.doubleValues();
if (doubleValues.isMultiValued() &&
(!delegate.metaData().uniqueness.unique() || doubleValues.getOrder() != Order.NUMERIC)) {
doubleValues = new SortedUniqueDoubleValues(doubleValues);
}
}
return doubleValues;
}
@Override
public org.elasticsearch.index.fielddata.BytesValues bytesValues() {
if (bytesValues == null) {
bytesValues = delegate.bytesValues();
if (bytesValues.isMultiValued() &&
(!delegate.metaData().uniqueness.unique() || bytesValues.getOrder() != Order.BYTES)) {
bytesValues = new SortedUniqueBytesValues(bytesValues);
}
}
return bytesValues;
}
private static class SortedUniqueLongValues extends FilterLongValues {
int numUniqueValues;
long[] array = new long[2];
int pos = Integer.MAX_VALUE;
final InPlaceMergeSorter sorter = new InPlaceMergeSorter() {
@Override
protected void swap(int i, int j) {
final long tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
@Override
protected int compare(int i, int j) {
final long l1 = array[i];
final long l2 = array[j];
return Longs.compare(l1, l2);
}
};
protected SortedUniqueLongValues(LongValues delegate) {
super(delegate);
}
@Override
public int setDocument(int docId) {
final int numValues = super.setDocument(docId);
array = ArrayUtil.grow(array, numValues);
for (int i = 0; i < numValues; ++i) {
array[i] = super.nextValue();
}
pos = 0;
return numUniqueValues = CollectionUtils.sortAndDedup(array, numValues);
}
@Override
public long nextValue() {
assert pos < numUniqueValues;
return array[pos++];
}
@Override
public Order getOrder() {
return Order.NUMERIC;
}
}
private static class SortedUniqueDoubleValues extends FilterDoubleValues {
int numUniqueValues;
double[] array = new double[2];
int pos = Integer.MAX_VALUE;
final InPlaceMergeSorter sorter = new InPlaceMergeSorter() {
@Override
protected void swap(int i, int j) {
final double tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
@Override
protected int compare(int i, int j) {
return Double.compare(array[i], array[j]);
}
};
SortedUniqueDoubleValues(DoubleValues delegate) {
super(delegate);
}
@Override
public int setDocument(int docId) {
final int numValues = super.setDocument(docId);
array = ArrayUtil.grow(array, numValues);
for (int i = 0; i < numValues; ++i) {
array[i] = super.nextValue();
}
pos = 0;
return numUniqueValues = CollectionUtils.sortAndDedup(array, numValues);
}
@Override
public double nextValue() {
assert pos < numUniqueValues;
return array[pos++];
}
@Override
public Order getOrder() {
return Order.NUMERIC;
}
}
}
}
// No need to implement ReaderContextAware here, the delegate already takes care of updating data structures
public static class WithScript extends Bytes {
private final BytesValues bytesValues;
public WithScript(FieldDataSource delegate, SearchScript script) {
this.bytesValues = new BytesValues(delegate, script);
}
@Override
public MetaData metaData() {
return MetaData.UNKNOWN;
}
@Override
public BytesValues bytesValues() {
return bytesValues;
}
static class BytesValues extends org.elasticsearch.index.fielddata.BytesValues {
private final FieldDataSource source;
private final SearchScript script;
private final BytesRef scratch;
public BytesValues(FieldDataSource source, SearchScript script) {
super(true);
this.source = source;
this.script = script;
scratch = new BytesRef();
}
@Override
public int setDocument(int docId) {
return source.bytesValues().setDocument(docId);
}
@Override
public BytesRef nextValue() {
BytesRef value = source.bytesValues().nextValue();
script.setNextVar("_value", value.utf8ToString());
scratch.copyChars(script.run().toString());
return scratch;
}
}
}
public static class GeoPoint extends FieldDataSource implements ReaderContextAware {
protected boolean needsHashes;
protected final IndexGeoPointFieldData<?> indexFieldData;
private final MetaData metaData;
protected AtomicGeoPointFieldData<?> atomicFieldData;
private BytesValues bytesValues;
private GeoPointValues geoPointValues;
public GeoPoint(IndexGeoPointFieldData<?> indexFieldData, MetaData metaData) {
this.indexFieldData = indexFieldData;
this.metaData = metaData;
needsHashes = false;
}
@Override
public MetaData metaData() {
return metaData;
}
@Override
public final void setNeedsHashes(boolean needsHashes) {
this.needsHashes = needsHashes;
}
@Override
public void setNextReader(AtomicReaderContext reader) {
atomicFieldData = indexFieldData.load(reader);
if (bytesValues != null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
if (geoPointValues != null) {
geoPointValues = atomicFieldData.getGeoPointValues();
}
}
@Override
public org.elasticsearch.index.fielddata.BytesValues bytesValues() {
if (bytesValues == null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
return bytesValues;
}
public org.elasticsearch.index.fielddata.GeoPointValues geoPointValues() {
if (geoPointValues == null) {
geoPointValues = atomicFieldData.getGeoPointValues();
}
return geoPointValues;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_support_FieldDataSource.java
|
5,068 |
static class FieldDataWarmer extends IndicesWarmer.Listener {
@Override
public TerminationHandle warm(final IndexShard indexShard, IndexMetaData indexMetaData, final WarmerContext context, ThreadPool threadPool) {
final MapperService mapperService = indexShard.mapperService();
final Map<String, FieldMapper<?>> warmUp = new HashMap<String, FieldMapper<?>>();
boolean parentChild = false;
for (DocumentMapper docMapper : mapperService) {
for (FieldMapper<?> fieldMapper : docMapper.mappers().mappers()) {
if (fieldMapper instanceof ParentFieldMapper) {
ParentFieldMapper parentFieldMapper = (ParentFieldMapper) fieldMapper;
if (parentFieldMapper.active()) {
parentChild = true;
}
}
final FieldDataType fieldDataType = fieldMapper.fieldDataType();
if (fieldDataType == null) {
continue;
}
if (fieldDataType.getLoading() != Loading.EAGER) {
continue;
}
final String indexName = fieldMapper.names().indexName();
if (warmUp.containsKey(indexName)) {
continue;
}
warmUp.put(indexName, fieldMapper);
}
}
final IndexFieldDataService indexFieldDataService = indexShard.indexFieldDataService();
final Executor executor = threadPool.executor(executor());
final CountDownLatch latch = new CountDownLatch(context.newSearcher().reader().leaves().size() * warmUp.size() + (parentChild ? 1 : 0));
for (final AtomicReaderContext ctx : context.newSearcher().reader().leaves()) {
for (final FieldMapper<?> fieldMapper : warmUp.values()) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
final long start = System.nanoTime();
indexFieldDataService.getForField(fieldMapper).load(ctx);
if (indexShard.warmerService().logger().isTraceEnabled()) {
indexShard.warmerService().logger().trace("warmed fielddata for [{}], took [{}]", fieldMapper.names().name(), TimeValue.timeValueNanos(System.nanoTime() - start));
}
} catch (Throwable t) {
indexShard.warmerService().logger().warn("failed to warm-up fielddata for [{}]", t, fieldMapper.names().name());
} finally {
latch.countDown();
}
}
});
}
}
if (parentChild) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
final long start = System.nanoTime();
indexShard.indexService().cache().idCache().refresh(context.newSearcher().reader().leaves());
if (indexShard.warmerService().logger().isTraceEnabled()) {
indexShard.warmerService().logger().trace("warmed id_cache, took [{}]", TimeValue.timeValueNanos(System.nanoTime() - start));
}
} catch (Throwable t) {
indexShard.warmerService().logger().warn("failed to warm-up id cache", t);
} finally {
latch.countDown();
}
}
});
}
return new TerminationHandle() {
@Override
public void awaitTermination() throws InterruptedException {
latch.await();
}
};
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_SearchService.java
|
2,626 |
public static class PingResponse implements Streamable {
public static PingResponse[] EMPTY = new PingResponse[0];
private ClusterName clusterName;
private DiscoveryNode target;
private DiscoveryNode master;
private PingResponse() {
}
public PingResponse(DiscoveryNode target, DiscoveryNode master, ClusterName clusterName) {
this.target = target;
this.master = master;
this.clusterName = clusterName;
}
public ClusterName clusterName() {
return this.clusterName;
}
public DiscoveryNode target() {
return target;
}
public DiscoveryNode master() {
return master;
}
public static PingResponse readPingResponse(StreamInput in) throws IOException {
PingResponse response = new PingResponse();
response.readFrom(in);
return response;
}
@Override
public void readFrom(StreamInput in) throws IOException {
clusterName = readClusterName(in);
target = readNode(in);
if (in.readBoolean()) {
master = readNode(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
clusterName.writeTo(out);
target.writeTo(out);
if (master == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
master.writeTo(out);
}
}
@Override
public String toString() {
return "ping_response{target [" + target + "], master [" + master + "], cluster_name[" + clusterName.value() + "]}";
}
}
| 1no label
|
src_main_java_org_elasticsearch_discovery_zen_ping_ZenPing.java
|
5,228 |
public static class Bucket implements Histogram.Bucket {
long key;
long docCount;
InternalAggregations aggregations;
public Bucket(long key, long docCount, InternalAggregations aggregations) {
this.key = key;
this.docCount = docCount;
this.aggregations = aggregations;
}
@Override
public String getKey() {
return String.valueOf(key);
}
@Override
public Text getKeyAsText() {
return new StringText(getKey());
}
@Override
public Number getKeyAsNumber() {
return key;
}
@Override
public long getDocCount() {
return docCount;
}
@Override
public Aggregations getAggregations() {
return aggregations;
}
<B extends Bucket> B reduce(List<B> buckets, CacheRecycler cacheRecycler) {
if (buckets.size() == 1) {
// we only need to reduce the sub aggregations
Bucket bucket = buckets.get(0);
bucket.aggregations.reduce(cacheRecycler);
return (B) bucket;
}
List<InternalAggregations> aggregations = new ArrayList<InternalAggregations>(buckets.size());
Bucket reduced = null;
for (Bucket bucket : buckets) {
if (reduced == null) {
reduced = bucket;
} else {
reduced.docCount += bucket.docCount;
}
aggregations.add((InternalAggregations) bucket.getAggregations());
}
reduced.aggregations = InternalAggregations.reduce(aggregations, cacheRecycler);
return (B) reduced;
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_bucket_histogram_InternalHistogram.java
|
1,219 |
return new V<T>() {
@Override
public boolean release() throws ElasticsearchException {
if (t != Thread.currentThread()) {
// Releasing from a different thread doesn't break anything but this is bad practice as pages should be acquired
// as late as possible and released as soon as possible in a try/finally fashion
throw new RuntimeException("Page was allocated in " + t + " but released in " + Thread.currentThread());
}
final Throwable t = ACQUIRED_PAGES.remove(v);
if (t == null) {
throw new IllegalStateException("Releasing a page that has not been acquired");
}
return v.release();
}
@Override
public T v() {
return v.v();
}
@Override
public boolean isRecycled() {
return v.isRecycled();
}
};
| 1no label
|
src_test_java_org_elasticsearch_cache_recycler_MockPageCacheRecycler.java
|
122 |
private static final class RecoveredBranchInfo
{
final byte[] branchId;
private RecoveredBranchInfo( byte[] branchId )
{
this.branchId = branchId;
}
@Override
public int hashCode()
{
return Arrays.hashCode( branchId );
}
@Override
public boolean equals( Object obj )
{
if ( obj == null || obj.getClass() != RecoveredBranchInfo.class )
{
return false;
}
return Arrays.equals( branchId, ( ( RecoveredBranchInfo )obj ).branchId );
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TxManager.java
|
844 |
public class AlterRequest extends AbstractAlterRequest {
public AlterRequest() {
}
public AlterRequest(String name, Data function) {
super(name, function);
}
@Override
protected Operation prepareOperation() {
return new AlterOperation(name, function);
}
@Override
public int getClassId() {
return AtomicReferencePortableHook.ALTER;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_AlterRequest.java
|
462 |
public class ODatabaseCompare extends ODatabaseImpExpAbstract {
private OStorage storage1;
private OStorage storage2;
private ODatabaseDocumentTx databaseDocumentTxOne;
private ODatabaseDocumentTx databaseDocumentTxTwo;
private boolean compareEntriesForAutomaticIndexes = false;
private boolean autoDetectExportImportMap = true;
private OIndex<OIdentifiable> exportImportHashTable = null;
private int differences = 0;
public ODatabaseCompare(String iDb1URL, String iDb2URL, final OCommandOutputListener iListener) throws IOException {
super(null, null, iListener);
listener.onMessage("\nComparing two local databases:\n1) " + iDb1URL + "\n2) " + iDb2URL + "\n");
storage1 = Orient.instance().loadStorage(iDb1URL);
storage1.open(null, null, null);
storage2 = Orient.instance().loadStorage(iDb2URL);
storage2.open(null, null, null);
}
public ODatabaseCompare(String iDb1URL, String iDb2URL, final String userName, final String userPassword,
final OCommandOutputListener iListener) throws IOException {
super(null, null, iListener);
listener.onMessage("\nComparing two local databases:\n1) " + iDb1URL + "\n2) " + iDb2URL + "\n");
databaseDocumentTxOne = new ODatabaseDocumentTx(iDb1URL);
databaseDocumentTxOne.open(userName, userPassword);
databaseDocumentTxTwo = new ODatabaseDocumentTx(iDb2URL);
databaseDocumentTxTwo.open(userName, userPassword);
storage1 = databaseDocumentTxOne.getStorage();
storage2 = databaseDocumentTxTwo.getStorage();
// exclude automatically generated clusters
excludeClusters.add("orids");
excludeClusters.add(OMetadataDefault.CLUSTER_INDEX_NAME);
excludeClusters.add(OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME);
}
public boolean isCompareEntriesForAutomaticIndexes() {
return compareEntriesForAutomaticIndexes;
}
public void setAutoDetectExportImportMap(boolean autoDetectExportImportMap) {
this.autoDetectExportImportMap = autoDetectExportImportMap;
}
public void setCompareEntriesForAutomaticIndexes(boolean compareEntriesForAutomaticIndexes) {
this.compareEntriesForAutomaticIndexes = compareEntriesForAutomaticIndexes;
}
public boolean compare() {
if (isDocumentDatabases() && (databaseDocumentTxOne == null || databaseDocumentTxTwo == null)) {
listener.onMessage("\nPassed in URLs are related to document databases but credentials "
+ "were not provided to open them. Please provide user name + password for databases to compare");
return false;
}
if (!isDocumentDatabases() && (databaseDocumentTxOne != null || databaseDocumentTxTwo != null)) {
listener.onMessage("\nPassed in URLs are not related to document databases but credentials "
+ "were provided to open them. Please do not provide user name + password for databases to compare");
return false;
}
try {
ODocumentHelper.RIDMapper ridMapper = null;
if (autoDetectExportImportMap) {
listener
.onMessage("\nAuto discovery of mapping between RIDs of exported and imported records is switched on, try to discover mapping data on disk.");
exportImportHashTable = (OIndex<OIdentifiable>) databaseDocumentTxTwo.getMetadata().getIndexManager()
.getIndex(ODatabaseImport.EXPORT_IMPORT_MAP_NAME);
if (exportImportHashTable != null) {
listener.onMessage("\nMapping data were found and will be loaded.");
ridMapper = new ODocumentHelper.RIDMapper() {
@Override
public ORID map(ORID rid) {
if (rid == null)
return null;
if (!rid.isPersistent())
return null;
final OIdentifiable result = exportImportHashTable.get(rid);
if (result == null)
return null;
return result.getIdentity();
}
};
} else
listener.onMessage("\nMapping data were not found.");
}
compareClusters();
compareRecords(ridMapper);
if (isDocumentDatabases())
compareIndexes(ridMapper);
if (differences == 0) {
listener.onMessage("\n\nDatabases match.");
return true;
} else {
listener.onMessage("\n\nDatabases do not match. Found " + differences + " difference(s).");
return false;
}
} catch (Exception e) {
e.printStackTrace();
throw new ODatabaseExportException("Error on compare of database '" + storage1.getName() + "' against '" + storage2.getName()
+ "'", e);
} finally {
storage1.close();
storage2.close();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void compareIndexes(ODocumentHelper.RIDMapper ridMapper) {
listener.onMessage("\nStarting index comparison:");
boolean ok = true;
final OIndexManager indexManagerOne = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<OIndexManager>() {
public OIndexManager call() {
return databaseDocumentTxOne.getMetadata().getIndexManager();
}
});
final OIndexManager indexManagerTwo = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<OIndexManager>() {
public OIndexManager call() {
return databaseDocumentTxTwo.getMetadata().getIndexManager();
}
});
final Collection<? extends OIndex<?>> indexesOne = makeDbCall(databaseDocumentTxOne,
new ODbRelatedCall<Collection<? extends OIndex<?>>>() {
public Collection<? extends OIndex<?>> call() {
return indexManagerOne.getIndexes();
}
});
int indexesSizeOne = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<Integer>() {
public Integer call() {
return indexesOne.size();
}
});
int indexesSizeTwo = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<Integer>() {
public Integer call() {
return indexManagerTwo.getIndexes().size();
}
});
if (exportImportHashTable != null)
indexesSizeTwo--;
if (indexesSizeOne != indexesSizeTwo) {
ok = false;
listener.onMessage("\n- ERR: Amount of indexes are different.");
listener.onMessage("\n--- DB1: " + indexesSizeOne);
listener.onMessage("\n--- DB2: " + indexesSizeTwo);
listener.onMessage("\n");
++differences;
}
final Iterator<? extends OIndex<?>> iteratorOne = makeDbCall(databaseDocumentTxOne,
new ODbRelatedCall<Iterator<? extends OIndex<?>>>() {
public Iterator<? extends OIndex<?>> call() {
return indexesOne.iterator();
}
});
while (makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Boolean>() {
public Boolean call() {
return iteratorOne.hasNext();
}
})) {
final OIndex indexOne = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<OIndex<?>>() {
public OIndex<?> call() {
return iteratorOne.next();
}
});
final OIndex<?> indexTwo = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<OIndex<?>>() {
public OIndex<?> call() {
return indexManagerTwo.getIndex(indexOne.getName());
}
});
if (indexTwo == null) {
ok = false;
listener.onMessage("\n- ERR: Index " + indexOne.getName() + " is absent in DB2.");
++differences;
continue;
}
if (!indexOne.getType().equals(indexTwo.getType())) {
ok = false;
listener.onMessage("\n- ERR: Index types for index " + indexOne.getName() + " are different.");
listener.onMessage("\n--- DB1: " + indexOne.getType());
listener.onMessage("\n--- DB2: " + indexTwo.getType());
listener.onMessage("\n");
++differences;
continue;
}
if (!indexOne.getClusters().equals(indexTwo.getClusters())) {
ok = false;
listener.onMessage("\n- ERR: Clusters to index for index " + indexOne.getName() + " are different.");
listener.onMessage("\n--- DB1: " + indexOne.getClusters());
listener.onMessage("\n--- DB2: " + indexTwo.getClusters());
listener.onMessage("\n");
++differences;
continue;
}
if (indexOne.getDefinition() == null && indexTwo.getDefinition() != null) {
ok = false;
listener.onMessage("\n- ERR: Index definition for index " + indexOne.getName() + " for DB2 is not null.");
++differences;
continue;
} else if (indexOne.getDefinition() != null && indexTwo.getDefinition() == null) {
ok = false;
listener.onMessage("\n- ERR: Index definition for index " + indexOne.getName() + " for DB2 is null.");
++differences;
continue;
} else if (indexOne.getDefinition() != null && !indexOne.getDefinition().equals(indexTwo.getDefinition())) {
ok = false;
listener.onMessage("\n- ERR: Index definitions for index " + indexOne.getName() + " are different.");
listener.onMessage("\n--- DB1: " + indexOne.getDefinition());
listener.onMessage("\n--- DB2: " + indexTwo.getDefinition());
listener.onMessage("\n");
++differences;
continue;
}
final long indexOneSize = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Long>() {
public Long call() {
return indexOne.getSize();
}
});
final long indexTwoSize = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<Long>() {
public Long call() {
return indexTwo.getSize();
}
});
if (indexOneSize != indexTwoSize) {
ok = false;
listener.onMessage("\n- ERR: Amount of entries for index " + indexOne.getName() + " are different.");
listener.onMessage("\n--- DB1: " + indexOneSize);
listener.onMessage("\n--- DB2: " + indexTwoSize);
listener.onMessage("\n");
++differences;
}
if (((compareEntriesForAutomaticIndexes && !indexOne.getType().equals("DICTIONARY")) || !indexOne.isAutomatic())) {
final Iterator<Map.Entry<Object, Object>> indexIteratorOne = makeDbCall(databaseDocumentTxOne,
new ODbRelatedCall<Iterator<Map.Entry<Object, Object>>>() {
public Iterator<Map.Entry<Object, Object>> call() {
return indexOne.iterator();
}
});
while (makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Boolean>() {
public Boolean call() {
return indexIteratorOne.hasNext();
}
})) {
final Map.Entry<Object, Object> indexOneEntry = makeDbCall(databaseDocumentTxOne,
new ODbRelatedCall<Map.Entry<Object, Object>>() {
public Map.Entry<Object, Object> call() {
return indexIteratorOne.next();
}
});
final Object key = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Object>() {
public Object call() {
return indexOneEntry.getKey();
}
});
Object indexOneValue = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Object>() {
public Object call() {
return indexOneEntry.getValue();
}
});
final Object indexTwoValue = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<Object>() {
public Object call() {
return indexTwo.get(key);
}
});
if (indexTwoValue == null) {
ok = false;
listener.onMessage("\n- ERR: Entry with key " + key + " is absent in index " + indexOne.getName() + " for DB2.");
++differences;
continue;
}
if (indexOneValue instanceof Set && indexTwoValue instanceof Set) {
final Set<Object> indexOneValueSet = (Set<Object>) indexOneValue;
final Set<Object> indexTwoValueSet = (Set<Object>) indexTwoValue;
if (!ODocumentHelper.compareSets(databaseDocumentTxOne, indexOneValueSet, databaseDocumentTxTwo, indexTwoValueSet,
ridMapper)) {
ok = false;
reportIndexDiff(indexOne, key, indexOneValue, indexTwoValue);
}
} else if (indexOneValue instanceof ORID && indexTwoValue instanceof ORID) {
if (ridMapper != null && ((ORID) indexOneValue).isPersistent()) {
OIdentifiable identifiable = ridMapper.map((ORID) indexOneValue);
if (identifiable != null)
indexOneValue = identifiable.getIdentity();
}
if (!indexOneValue.equals(indexTwoValue)) {
ok = false;
reportIndexDiff(indexOne, key, indexOneValue, indexTwoValue);
}
} else if (!indexOneValue.equals(indexTwoValue)) {
ok = false;
reportIndexDiff(indexOne, key, indexOneValue, indexTwoValue);
}
}
}
}
if (ok)
listener.onMessage("OK");
}
private boolean compareClusters() {
listener.onMessage("\nStarting shallow comparison of clusters:");
listener.onMessage("\nChecking the number of clusters...");
if (storage1.getClusterNames().size() != storage1.getClusterNames().size()) {
listener.onMessage("ERR: cluster sizes are different: " + storage1.getClusterNames().size() + " <-> "
+ storage1.getClusterNames().size());
++differences;
}
int cluster2Id;
boolean ok;
for (String clusterName : storage1.getClusterNames()) {
// CHECK IF THE CLUSTER IS INCLUDED
if (includeClusters != null) {
if (!includeClusters.contains(clusterName))
continue;
} else if (excludeClusters != null) {
if (excludeClusters.contains(clusterName))
continue;
}
ok = true;
cluster2Id = storage2.getClusterIdByName(clusterName);
listener.onMessage("\n- Checking cluster " + String.format("%-25s: ", "'" + clusterName + "'"));
if (cluster2Id == -1) {
listener.onMessage("ERR: cluster name " + clusterName + " was not found on database " + storage2);
++differences;
ok = false;
}
if (cluster2Id != storage1.getClusterIdByName(clusterName)) {
listener.onMessage("ERR: cluster id is different for cluster " + clusterName + ": "
+ storage1.getClusterIdByName(clusterName) + " <-> " + cluster2Id);
++differences;
ok = false;
}
if (storage1.count(cluster2Id) != storage2.count(cluster2Id)) {
listener.onMessage("ERR: number of records different in cluster '" + clusterName + "' (id=" + cluster2Id + "): "
+ storage1.count(cluster2Id) + " <-> " + storage2.count(cluster2Id));
++differences;
ok = false;
}
if (ok)
listener.onMessage("OK");
}
listener.onMessage("\n\nShallow analysis done.");
return true;
}
private boolean compareRecords(ODocumentHelper.RIDMapper ridMapper) {
listener.onMessage("\nStarting deep comparison record by record. This may take a few minutes. Wait please...");
int clusterId;
for (String clusterName : storage1.getClusterNames()) {
// CHECK IF THE CLUSTER IS INCLUDED
if (includeClusters != null) {
if (!includeClusters.contains(clusterName))
continue;
} else if (excludeClusters != null) {
if (excludeClusters.contains(clusterName))
continue;
}
clusterId = storage1.getClusterIdByName(clusterName);
OClusterPosition[] db1Range = storage1.getClusterDataRange(clusterId);
OClusterPosition[] db2Range = storage2.getClusterDataRange(clusterId);
final OClusterPosition db1Max = db1Range[1];
final OClusterPosition db2Max = db2Range[1];
final ODocument doc1 = new ODocument();
final ODocument doc2 = new ODocument();
final ORecordId rid = new ORecordId(clusterId);
// TODO why this maximums can be different?
final OClusterPosition clusterMax = db1Max.compareTo(db2Max) > 0 ? db1Max : db2Max;
final OStorage storage;
if (clusterMax.equals(db1Max))
storage = storage1;
else
storage = storage2;
OPhysicalPosition[] physicalPositions = storage.ceilingPhysicalPositions(clusterId, new OPhysicalPosition(
OClusterPositionFactory.INSTANCE.valueOf(0)));
long recordsCounter = 0;
while (physicalPositions.length > 0) {
for (OPhysicalPosition physicalPosition : physicalPositions) {
recordsCounter++;
final OClusterPosition position = physicalPosition.clusterPosition;
rid.clusterPosition = position;
if (isDocumentDatabases() && rid.equals(new ORecordId(storage1.getConfiguration().indexMgrRecordId))
&& rid.equals(new ORecordId(storage2.getConfiguration().indexMgrRecordId)))
continue;
final ORawBuffer buffer1 = storage1.readRecord(rid, null, true, null, false).getResult();
final ORawBuffer buffer2;
if (ridMapper == null)
buffer2 = storage2.readRecord(rid, null, true, null, false).getResult();
else {
final ORID newRid = ridMapper.map(rid);
if (newRid == null)
buffer2 = storage2.readRecord(rid, null, true, null, false).getResult();
else
buffer2 = storage2.readRecord(new ORecordId(newRid), null, true, null, false).getResult();
}
if (buffer1 == null && buffer2 == null)
// BOTH RECORD NULL, OK
continue;
else if (buffer1 == null && buffer2 != null) {
// REC1 NULL
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " is null in DB1");
++differences;
} else if (buffer1 != null && buffer2 == null) {
// REC2 NULL
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " is null in DB2");
++differences;
} else {
if (buffer1.recordType != buffer2.recordType) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " recordType is different: "
+ (char) buffer1.recordType + " <-> " + (char) buffer2.recordType);
++differences;
}
if (buffer1.buffer == null && buffer2.buffer == null) {
} else if (buffer1.buffer == null && buffer2.buffer != null) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " content is different: null <-> "
+ buffer2.buffer.length);
++differences;
} else if (buffer1.buffer != null && buffer2.buffer == null) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " content is different: " + buffer1.buffer.length
+ " <-> null");
++differences;
} else {
if (buffer1.recordType == ODocument.RECORD_TYPE) {
// DOCUMENT: TRY TO INSTANTIATE AND COMPARE
makeDbCall(databaseDocumentTxOne, new ODocumentHelper.ODbRelatedCall<Object>() {
public Object call() {
doc1.reset();
doc1.fromStream(buffer1.buffer);
return null;
}
});
makeDbCall(databaseDocumentTxTwo, new ODocumentHelper.ODbRelatedCall<Object>() {
public Object call() {
doc2.reset();
doc2.fromStream(buffer2.buffer);
return null;
}
});
if (rid.toString().equals(storage1.getConfiguration().schemaRecordId)
&& rid.toString().equals(storage2.getConfiguration().schemaRecordId)) {
makeDbCall(databaseDocumentTxOne, new ODocumentHelper.ODbRelatedCall<java.lang.Object>() {
public Object call() {
convertSchemaDoc(doc1);
return null;
}
});
makeDbCall(databaseDocumentTxTwo, new ODocumentHelper.ODbRelatedCall<java.lang.Object>() {
public Object call() {
convertSchemaDoc(doc2);
return null;
}
});
}
if (!ODocumentHelper.hasSameContentOf(doc1, databaseDocumentTxOne, doc2, databaseDocumentTxTwo, ridMapper)) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " document content is different");
listener.onMessage("\n--- REC1: " + new String(buffer1.buffer));
listener.onMessage("\n--- REC2: " + new String(buffer2.buffer));
listener.onMessage("\n");
++differences;
}
} else {
if (buffer1.buffer.length != buffer2.buffer.length) {
// CHECK IF THE TRIMMED SIZE IS THE SAME
final String rec1 = new String(buffer1.buffer).trim();
final String rec2 = new String(buffer2.buffer).trim();
if (rec1.length() != rec2.length()) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " content length is different: "
+ buffer1.buffer.length + " <-> " + buffer2.buffer.length);
if (buffer1.recordType == ODocument.RECORD_TYPE || buffer1.recordType == ORecordFlat.RECORD_TYPE)
listener.onMessage("\n--- REC1: " + rec1);
if (buffer2.recordType == ODocument.RECORD_TYPE || buffer2.recordType == ORecordFlat.RECORD_TYPE)
listener.onMessage("\n--- REC2: " + rec2);
listener.onMessage("\n");
++differences;
}
} else {
// CHECK BYTE PER BYTE
for (int b = 0; b < buffer1.buffer.length; ++b) {
if (buffer1.buffer[b] != buffer2.buffer[b]) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " content is different at byte #" + b
+ ": " + buffer1.buffer[b] + " <-> " + buffer2.buffer[b]);
listener.onMessage("\n--- REC1: " + new String(buffer1.buffer));
listener.onMessage("\n--- REC2: " + new String(buffer2.buffer));
listener.onMessage("\n");
++differences;
break;
}
}
}
}
}
}
}
physicalPositions = storage.higherPhysicalPositions(clusterId, physicalPositions[physicalPositions.length - 1]);
if (recordsCounter % 10000 == 0)
listener.onMessage("\n" + recordsCounter + " records were processed for cluster " + clusterName + " ...");
}
listener.onMessage("\nCluster comparison was finished, " + recordsCounter + " records were processed for cluster "
+ clusterName + " ...");
}
return true;
}
private void convertSchemaDoc(final ODocument document) {
if (document.field("classes") != null) {
document.setFieldType("classes", OType.EMBEDDEDSET);
for (ODocument classDoc : document.<Set<ODocument>> field("classes")) {
classDoc.setFieldType("properties", OType.EMBEDDEDSET);
}
}
}
private boolean isDocumentDatabases() {
return storage1.getConfiguration().schemaRecordId != null && storage2.getConfiguration().schemaRecordId != null;
}
private void reportIndexDiff(OIndex<?> indexOne, Object key, final Object indexOneValue, final Object indexTwoValue) {
listener.onMessage("\n- ERR: Entry values for key '" + key + "' are different for index " + indexOne.getName());
listener.onMessage("\n--- DB1: " + makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<String>() {
public String call() {
return indexOneValue.toString();
}
}));
listener.onMessage("\n--- DB2: " + makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<String>() {
public String call() {
return indexTwoValue.toString();
}
}));
listener.onMessage("\n");
++differences;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java
|
695 |
constructors[LIST_GET] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListGetRequest();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
|
970 |
public class AwaitOperation extends BaseLockOperation
implements WaitSupport, BackupAwareOperation {
private String conditionId;
private boolean firstRun;
private boolean expired;
public AwaitOperation() {
}
public AwaitOperation(ObjectNamespace namespace, Data key, long threadId, long timeout, String conditionId) {
super(namespace, key, threadId, timeout);
this.conditionId = conditionId;
}
@Override
public void beforeRun() throws Exception {
LockStoreImpl lockStore = getLockStore();
firstRun = lockStore.startAwaiting(key, conditionId, getCallerUuid(), threadId);
}
@Override
public void run() throws Exception {
LockStoreImpl lockStore = getLockStore();
if (!lockStore.lock(key, getCallerUuid(), threadId)) {
throw new IllegalMonitorStateException(
"Current thread is not owner of the lock! -> " + lockStore.getOwnerInfo(key));
}
if (expired) {
response = false;
} else {
lockStore.removeSignalKey(getWaitKey());
lockStore.removeAwait(key, conditionId, getCallerUuid(), threadId);
response = true;
}
}
@Override
public ConditionKey getWaitKey() {
return new ConditionKey(namespace.getObjectName(), key, conditionId);
}
@Override
public boolean shouldWait() {
LockStoreImpl lockStore = getLockStore();
boolean canAcquireLock = lockStore.canAcquireLock(key, getCallerUuid(), threadId);
ConditionKey signalKey = lockStore.getSignalKey(key);
if (signalKey != null && conditionId.equals(signalKey.getConditionId()) && canAcquireLock) {
return false;
}
boolean shouldWait = firstRun || !canAcquireLock;
firstRun = false;
return shouldWait;
}
@Override
public boolean shouldBackup() {
return true;
}
@Override
public Operation getBackupOperation() {
return new AwaitBackupOperation(namespace, key, threadId, conditionId, getCallerUuid());
}
@Override
public void onWaitExpire() {
expired = true;
LockStoreImpl lockStore = getLockStore();
lockStore.removeSignalKey(getWaitKey());
lockStore.removeAwait(key, conditionId, getCallerUuid(), threadId);
boolean locked = lockStore.lock(key, getCallerUuid(), threadId);
if (locked) {
ResponseHandler responseHandler = getResponseHandler();
// expired & acquired lock, send FALSE
responseHandler.sendResponse(false);
} else {
// expired but could not acquire lock, no response atm
lockStore.registerExpiredAwaitOp(this);
}
}
@Override
public int getId() {
return LockDataSerializerHook.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();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_concurrent_lock_operations_AwaitOperation.java
|
569 |
trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) {
firedEvents.add(event);
}
});
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_index_OCompositeIndexDefinitionTest.java
|
30 |
static final class ThenApply<T,U> extends Completion {
final CompletableFuture<? extends T> src;
final Fun<? super T,? extends U> fn;
final CompletableFuture<U> dst;
final Executor executor;
ThenApply(CompletableFuture<? extends T> src,
Fun<? super T,? extends U> fn,
CompletableFuture<U> dst,
Executor executor) {
this.src = src; this.fn = fn; this.dst = dst;
this.executor = executor;
}
public final void run() {
final CompletableFuture<? extends T> a;
final Fun<? super T,? extends U> fn;
final CompletableFuture<U> dst;
Object r; T t; Throwable ex;
if ((dst = this.dst) != null &&
(fn = this.fn) != null &&
(a = this.src) != null &&
(r = a.result) != null &&
compareAndSet(0, 1)) {
if (r instanceof AltResult) {
ex = ((AltResult)r).ex;
t = null;
}
else {
ex = null;
@SuppressWarnings("unchecked") T tr = (T) r;
t = tr;
}
Executor e = executor;
U u = null;
if (ex == null) {
try {
if (e != null)
e.execute(new AsyncApply<T,U>(t, fn, dst));
else
u = fn.apply(t);
} catch (Throwable rex) {
ex = rex;
}
}
if (e == null || ex != null)
dst.internalComplete(u, ex);
}
}
private static final long serialVersionUID = 5232453952276885070L;
}
| 0true
|
src_main_java_jsr166e_CompletableFuture.java
|
384 |
clusterService.submitStateUpdateTask("cluster_reroute (api)", Priority.URGENT, new AckedClusterStateUpdateTask() {
private volatile ClusterState clusterStateToSend;
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return true;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
listener.onResponse(new ClusterRerouteResponse(true, clusterStateToSend));
}
@Override
public void onAckTimeout() {
listener.onResponse(new ClusterRerouteResponse(false, clusterStateToSend));
}
@Override
public TimeValue ackTimeout() {
return request.timeout();
}
@Override
public TimeValue timeout() {
return request.masterNodeTimeout();
}
@Override
public void onFailure(String source, Throwable t) {
logger.debug("failed to perform [{}]", t, source);
listener.onFailure(t);
}
@Override
public ClusterState execute(ClusterState currentState) {
RoutingAllocation.Result routingResult = allocationService.reroute(currentState, request.commands, true);
ClusterState newState = ClusterState.builder(currentState).routingResult(routingResult).build();
clusterStateToSend = newState;
if (request.dryRun) {
return currentState;
}
return newState;
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
});
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_reroute_TransportClusterRerouteAction.java
|
671 |
public class DeleteWarmerResponse extends AcknowledgedResponse {
DeleteWarmerResponse() {
super();
}
DeleteWarmerResponse(boolean acknowledged) {
super(acknowledged);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
readAcknowledged(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
writeAcknowledged(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_warmer_delete_DeleteWarmerResponse.java
|
236 |
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ClientExecutorServiceInvokeTest {
static HazelcastInstance instance1;
static HazelcastInstance client;
@BeforeClass
public static void init() {
instance1 = Hazelcast.newHazelcastInstance();
client = HazelcastClient.newHazelcastClient();
}
@AfterClass
public static void destroy() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testInvokeAll() throws Throwable {
IExecutorService service = client.getExecutorService(randomString());
String msg = randomString();
Collection c = new ArrayList();
c.add(new AppendCallable(msg));
c.add(new AppendCallable(msg));
List<Future> results = service.invokeAll(c);
for(Future result : results){
assertEquals(msg + AppendCallable.APPENDAGE, result.get() );
}
}
@Test(expected = UnsupportedOperationException.class)
public void testInvokeAll_withTimeOut() throws Throwable {
IExecutorService service = client.getExecutorService(randomString());
Collection c = new ArrayList();
c.add(new AppendCallable());
c.add(new AppendCallable());
service.invokeAll(c, 1, TimeUnit.MINUTES);
}
@Test(expected = UnsupportedOperationException.class)
public void testInvokeAny() throws Throwable, InterruptedException {
IExecutorService service = client.getExecutorService(randomString());
Collection c = new ArrayList();
c.add(new AppendCallable());
c.add(new AppendCallable());
service.invokeAny(c);
}
@Test(expected = UnsupportedOperationException.class)
public void testInvokeAnyTimeOut() throws Throwable, InterruptedException {
IExecutorService service = client.getExecutorService(randomString());
Collection c = new ArrayList();
c.add(new AppendCallable());
c.add(new AppendCallable());
service.invokeAny(c, 1, TimeUnit.MINUTES);
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceInvokeTest.java
|
612 |
public class MemberRemoveOperation extends AbstractClusterOperation {
private Address deadAddress;
public MemberRemoveOperation() {
}
public MemberRemoveOperation(Address deadAddress) {
this.deadAddress = deadAddress;
}
@Override
public void run() {
final ClusterServiceImpl clusterService = getService();
final Address caller = getCallerAddress();
if (caller != null
&& (caller.equals(deadAddress) || caller.equals(clusterService.getMasterAddress()))) {
ILogger logger = getLogger();
if (logger.isFinestEnabled()) {
logger.finest("Removing " + deadAddress + ", called from " + caller);
}
clusterService.removeAddress(deadAddress);
}
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
deadAddress = new Address();
deadAddress.readData(in);
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
deadAddress.writeData(out);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_cluster_MemberRemoveOperation.java
|
1,086 |
executor.submit(new Runnable() {
@Override
public void run() {
assertAcked(admin().indices().prepareAliases().addAlias("test", aliasName));
client().index(indexRequest(aliasName).type("type1").id("1").source(source("1", "test"))).actionGet();
}
});
| 0true
|
src_test_java_org_elasticsearch_aliases_IndexAliasesTests.java
|
34 |
@SuppressWarnings("unchecked")
public abstract class OMVRBTreeEntry<K, V> implements Map.Entry<K, V>, Comparable<OMVRBTreeEntry<K, V>> {
protected OMVRBTree<K, V> tree;
private int pageSplitItems;
public static final int BINARY_SEARCH_THRESHOLD = 10;
/**
* Constructor called on unmarshalling.
*
*/
protected OMVRBTreeEntry(final OMVRBTree<K, V> iTree) {
tree = iTree;
}
public abstract void setLeft(OMVRBTreeEntry<K, V> left);
public abstract OMVRBTreeEntry<K, V> getLeft();
public abstract void setRight(OMVRBTreeEntry<K, V> right);
public abstract OMVRBTreeEntry<K, V> getRight();
public abstract OMVRBTreeEntry<K, V> setParent(OMVRBTreeEntry<K, V> parent);
public abstract OMVRBTreeEntry<K, V> getParent();
protected abstract OMVRBTreeEntry<K, V> getLeftInMemory();
protected abstract OMVRBTreeEntry<K, V> getParentInMemory();
protected abstract OMVRBTreeEntry<K, V> getRightInMemory();
protected abstract OMVRBTreeEntry<K, V> getNextInMemory();
/**
* Returns the first Entry only by traversing the memory, or null if no such.
*/
public OMVRBTreeEntry<K, V> getFirstInMemory() {
OMVRBTreeEntry<K, V> node = this;
OMVRBTreeEntry<K, V> prev = this;
while (node != null) {
prev = node;
node = node.getPreviousInMemory();
}
return prev;
}
/**
* Returns the previous of the current Entry only by traversing the memory, or null if no such.
*/
public OMVRBTreeEntry<K, V> getPreviousInMemory() {
OMVRBTreeEntry<K, V> t = this;
OMVRBTreeEntry<K, V> p = null;
if (t.getLeftInMemory() != null) {
p = t.getLeftInMemory();
while (p.getRightInMemory() != null)
p = p.getRightInMemory();
} else {
p = t.getParentInMemory();
while (p != null && t == p.getLeftInMemory()) {
t = p;
p = p.getParentInMemory();
}
}
return p;
}
protected OMVRBTree<K, V> getTree() {
return tree;
}
public int getDepth() {
int level = 0;
OMVRBTreeEntry<K, V> entry = this;
while (entry.getParent() != null) {
level++;
entry = entry.getParent();
}
return level;
}
/**
* Returns the key.
*
* @return the key
*/
public K getKey() {
return getKey(tree.pageIndex);
}
public K getKey(final int iIndex) {
if (iIndex >= getSize())
throw new IndexOutOfBoundsException("Requested index " + iIndex + " when the range is 0-" + getSize());
tree.pageIndex = iIndex;
return getKeyAt(iIndex);
}
protected abstract K getKeyAt(final int iIndex);
/**
* Returns the value associated with the key.
*
* @return the value associated with the key
*/
public V getValue() {
if (tree.pageIndex == -1)
return getValueAt(0);
return getValueAt(tree.pageIndex);
}
public V getValue(final int iIndex) {
tree.pageIndex = iIndex;
return getValueAt(iIndex);
}
protected abstract V getValueAt(int iIndex);
public int getFreeSpace() {
return getPageSize() - getSize();
}
/**
* Execute a binary search between the keys of the node. The keys are always kept ordered. It update the pageIndex attribute with
* the most closer key found (useful for the next inserting).
*
* @param iKey
* Key to find
* @return The value found if any, otherwise null
*/
protected V search(final K iKey) {
tree.pageItemFound = false;
int size = getSize();
if (size == 0)
return null;
// CHECK THE LOWER LIMIT
if (tree.comparator != null)
tree.pageItemComparator = tree.comparator.compare(iKey, getKeyAt(0));
else
tree.pageItemComparator = ((Comparable<? super K>) iKey).compareTo(getKeyAt(0));
if (tree.pageItemComparator == 0) {
// FOUND: SET THE INDEX AND RETURN THE NODE
tree.pageItemFound = true;
tree.pageIndex = 0;
return getValueAt(tree.pageIndex);
} else if (tree.pageItemComparator < 0) {
// KEY OUT OF FIRST ITEM: AVOID SEARCH AND RETURN THE FIRST POSITION
tree.pageIndex = 0;
return null;
} else {
// CHECK THE UPPER LIMIT
if (tree.comparator != null)
tree.pageItemComparator = tree.comparator.compare((K) iKey, getKeyAt(size - 1));
else
tree.pageItemComparator = ((Comparable<? super K>) iKey).compareTo(getKeyAt(size - 1));
if (tree.pageItemComparator > 0) {
// KEY OUT OF LAST ITEM: AVOID SEARCH AND RETURN THE LAST POSITION
tree.pageIndex = size;
return null;
}
}
if (size < BINARY_SEARCH_THRESHOLD)
return linearSearch(iKey);
else
return binarySearch(iKey);
}
/**
* Linear search inside the node
*
* @param iKey
* Key to search
* @return Value if found, otherwise null and the tree.pageIndex updated with the closest-after-first position valid for further
* inserts.
*/
private V linearSearch(final K iKey) {
V value = null;
int i = 0;
tree.pageItemComparator = -1;
for (int s = getSize(); i < s; ++i) {
if (tree.comparator != null)
tree.pageItemComparator = tree.comparator.compare(getKeyAt(i), iKey);
else
tree.pageItemComparator = ((Comparable<? super K>) getKeyAt(i)).compareTo(iKey);
if (tree.pageItemComparator == 0) {
// FOUND: SET THE INDEX AND RETURN THE NODE
tree.pageItemFound = true;
value = getValueAt(i);
break;
} else if (tree.pageItemComparator > 0)
break;
}
tree.pageIndex = i;
return value;
}
/**
* Binary search inside the node
*
* @param iKey
* Key to search
* @return Value if found, otherwise null and the tree.pageIndex updated with the closest-after-first position valid for further
* inserts.
*/
private V binarySearch(final K iKey) {
int low = 0;
int high = getSize() - 1;
int mid = 0;
while (low <= high) {
mid = (low + high) >>> 1;
Object midVal = getKeyAt(mid);
if (tree.comparator != null)
tree.pageItemComparator = tree.comparator.compare((K) midVal, iKey);
else
tree.pageItemComparator = ((Comparable<? super K>) midVal).compareTo(iKey);
if (tree.pageItemComparator == 0) {
// FOUND: SET THE INDEX AND RETURN THE NODE
tree.pageItemFound = true;
tree.pageIndex = mid;
return getValueAt(tree.pageIndex);
}
if (low == high)
break;
if (tree.pageItemComparator < 0)
low = mid + 1;
else
high = mid;
}
tree.pageIndex = mid;
return null;
}
protected abstract void insert(final int iPosition, final K key, final V value);
protected abstract void remove();
protected abstract void setColor(boolean iColor);
public abstract boolean getColor();
public abstract int getSize();
public K getLastKey() {
return getKey(getSize() - 1);
}
public K getFirstKey() {
return getKey(0);
}
protected abstract void copyFrom(final OMVRBTreeEntry<K, V> iSource);
public int getPageSplitItems() {
return pageSplitItems;
}
protected void init() {
pageSplitItems = (int) (getPageSize() * tree.pageLoadFactor);
}
public abstract int getPageSize();
/**
* Compares two nodes by their first keys.
*/
public int compareTo(final OMVRBTreeEntry<K, V> o) {
if (o == null)
return 1;
if (o == this)
return 0;
if (getSize() == 0)
return -1;
if (o.getSize() == 0)
return 1;
if (tree.comparator != null)
return tree.comparator.compare(getFirstKey(), o.getFirstKey());
return ((Comparable<K>) getFirstKey()).compareTo(o.getFirstKey());
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
int idx = tree.pageIndex;
if (idx > -1 && idx < getSize())
return getKeyAt(idx) + "=" + getValueAt(idx);
return null;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeEntry.java
|
1,077 |
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
shardOperation(request, listener, retryCount + 1);
}
});
| 1no label
|
src_main_java_org_elasticsearch_action_update_TransportUpdateAction.java
|
364 |
@Repository("blTranslationDao")
public class TranslationDaoImpl implements TranslationDao {
@PersistenceContext(unitName = "blPU")
protected EntityManager em;
@Resource(name = "blEntityConfiguration")
protected EntityConfiguration entityConfiguration;
protected DynamicDaoHelper dynamicDaoHelper = new DynamicDaoHelperImpl();
@Override
public Translation save(Translation translation) {
return em.merge(translation);
}
@Override
public Translation create() {
return (Translation) entityConfiguration.createEntityInstance(Translation.class.getName());
}
@Override
public void delete(Translation translation) {
em.remove(translation);
}
@Override
public Map<String, Object> getIdPropertyMetadata(TranslatedEntity entity) {
Class<?> implClass = entityConfiguration.lookupEntityClass(entity.getType());
return dynamicDaoHelper.getIdMetadata(implClass, (HibernateEntityManager) em);
}
@Override
public Translation readTranslationById(Long translationId) {
return em.find(TranslationImpl.class, translationId);
}
@Override
public List<Translation> readTranslations(TranslatedEntity entity, String entityId, String fieldName) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Translation> criteria = builder.createQuery(Translation.class);
Root<TranslationImpl> translation = criteria.from(TranslationImpl.class);
criteria.select(translation);
criteria.where(builder.equal(translation.get("entityType"), entity.getFriendlyType()),
builder.equal(translation.get("entityId"), entityId),
builder.equal(translation.get("fieldName"), fieldName)
);
TypedQuery<Translation> query = em.createQuery(criteria);
query.setHint(QueryHints.HINT_CACHEABLE, true);
try {
return query.getResultList();
} catch (NoResultException e) {
return null;
}
}
@Override
public Translation readTranslation(TranslatedEntity entity, String entityId, String fieldName, String localeCode) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Translation> criteria = builder.createQuery(Translation.class);
Root<TranslationImpl> translation = criteria.from(TranslationImpl.class);
criteria.select(translation);
criteria.where(builder.equal(translation.get("entityType"), entity.getFriendlyType()),
builder.equal(translation.get("entityId"), entityId),
builder.equal(translation.get("fieldName"), fieldName),
builder.equal(translation.get("localeCode"), localeCode)
);
TypedQuery<Translation> query = em.createQuery(criteria);
query.setHint(QueryHints.HINT_CACHEABLE, true);
try {
return query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
public DynamicDaoHelper getDynamicDaoHelper() {
return dynamicDaoHelper;
}
public void setDynamicDaoHelper(DynamicDaoHelper dynamicDaoHelper) {
this.dynamicDaoHelper = dynamicDaoHelper;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_i18n_dao_TranslationDaoImpl.java
|
417 |
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
firedEvents.add(event);
}
});
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java
|
301 |
public class OTraverseRecordSetProcess extends OTraverseAbstractProcess<Iterator<OIdentifiable>> {
protected OIdentifiable record;
protected int index = -1;
public OTraverseRecordSetProcess(final OTraverse iCommand, final Iterator<OIdentifiable> iTarget) {
super(iCommand, iTarget);
}
@SuppressWarnings("unchecked")
public OIdentifiable process() {
while (target.hasNext()) {
record = target.next();
index++;
final ORecord<?> rec = record.getRecord();
if (rec instanceof ODocument) {
ODocument doc = (ODocument) rec;
if (!doc.getIdentity().isPersistent() && doc.fields() == 1) {
// EXTRACT THE FIELD CONTEXT
Object fieldvalue = doc.field(doc.fieldNames()[0]);
if (fieldvalue instanceof Collection<?>) {
final OTraverseRecordSetProcess subProcess = new OTraverseRecordSetProcess(command,
((Collection<OIdentifiable>) fieldvalue).iterator());
final OIdentifiable subValue = subProcess.process();
if (subValue != null)
return subValue;
} else if (fieldvalue instanceof ODocument) {
final OTraverseRecordProcess subProcess = new OTraverseRecordProcess(command, (ODocument) rec);
final OIdentifiable subValue = subProcess.process();
if (subValue != null)
return subValue;
}
} else {
final OTraverseRecordProcess subProcess = new OTraverseRecordProcess(command, (ODocument) rec);
final OIdentifiable subValue = subProcess.process();
if (subValue != null)
return subValue;
}
}
}
return drop();
}
@Override
public String getStatus() {
return null;
}
@Override
public String toString() {
return target != null ? target.toString() : "-";
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_command_traverse_OTraverseRecordSetProcess.java
|
1,244 |
public class NodeClient extends AbstractClient implements InternalClient {
private final Settings settings;
private final ThreadPool threadPool;
private final NodeAdminClient admin;
private final ImmutableMap<Action, TransportAction> actions;
@Inject
public NodeClient(Settings settings, ThreadPool threadPool, NodeAdminClient admin, Map<GenericAction, TransportAction> actions) {
this.settings = settings;
this.threadPool = threadPool;
this.admin = admin;
MapBuilder<Action, TransportAction> actionsBuilder = new MapBuilder<Action, TransportAction>();
for (Map.Entry<GenericAction, TransportAction> entry : actions.entrySet()) {
if (entry.getKey() instanceof Action) {
actionsBuilder.put((Action) entry.getKey(), entry.getValue());
}
}
this.actions = actionsBuilder.immutableMap();
}
@Override
public Settings settings() {
return this.settings;
}
@Override
public ThreadPool threadPool() {
return this.threadPool;
}
@Override
public void close() {
// nothing really to do
}
@Override
public AdminClient admin() {
return this.admin;
}
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute(Action<Request, Response, RequestBuilder> action, Request request) {
TransportAction<Request, Response> transportAction = actions.get(action);
return transportAction.execute(request);
}
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
TransportAction<Request, Response> transportAction = actions.get(action);
transportAction.execute(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_client_node_NodeClient.java
|
102 |
public class ODynamicFactory<K, V> {
protected final Map<K, V> registry = new LinkedHashMap<K, V>();
public V get(final K iKey) {
return registry.get(iKey);
}
public void register(final K iKey, final V iValue) {
registry.put(iKey, iValue);
}
public void unregister(final K iKey) {
registry.remove(iKey);
}
public void unregisterAll() {
registry.clear();
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_factory_ODynamicFactory.java
|
272 |
public interface OCommandRequest {
public <RET> RET execute(Object... iArgs);
/**
* Returns the limit of result set. -1 means no limits.
*
*/
public int getLimit();
/**
* Sets the maximum items the command can returns. -1 means no limits.
*
* @param iLimit
* -1 = no limit. 1 to N to limit the result set.
* @return
*/
public OCommandRequest setLimit(int iLimit);
/**
* Returns the command timeout. 0 means no timeout.
*
* @return
*/
public long getTimeoutTime();
/**
* Returns the command timeout strategy between the defined ones.
*
* @return
*/
public TIMEOUT_STRATEGY getTimeoutStrategy();
/**
* Sets the command timeout. When the command execution time is major than the timeout the command returns
*
* @param timeout
*/
public void setTimeout(long timeout, TIMEOUT_STRATEGY strategy);
/**
* Returns true if the command doesn't change the database, otherwise false.
*/
public boolean isIdempotent();
/**
* Returns the fetch plan if any
*
* @return Fetch plan as unique string or null if it was not defined.
*/
public String getFetchPlan();
/**
* Set the fetch plan. The format is:
*
* <pre>
* <field>:<depth-level>*
* </pre>
*
* Where:
* <ul>
* <li><b>field</b> is the name of the field to specify the depth-level. <b>*</b> wildcard means any fields</li>
* <li><b>depth-level</b> is the depth level to fetch. -1 means infinite, 0 means no fetch at all and 1-N the depth level value.</li>
* </ul>
* Uses the blank spaces to separate the fields strategies.<br/>
* Example:
*
* <pre>
* children:-1 parent:0 sibling:3 *:0
* </pre>
*
* <br/>
*
* @param iFetchPlan
* @return
*/
public <RET extends OCommandRequest> RET setFetchPlan(String iFetchPlan);
public void setUseCache(boolean iUseCache);
public OCommandContext getContext();
public OCommandRequest setContext(final OCommandContext iContext);
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_command_OCommandRequest.java
|
140 |
public abstract class LocalProposal extends AbstractLinkedMode
implements ICompletionProposal, ICompletionProposalExtension6 {
protected int offset;
protected int exitPos;
protected ProducedType type;
protected String initialName;
protected String[] nameProposals;
protected final int currentOffset;
@Override
protected String getHintTemplate() {
return "Enter type and name for new local {0}";
}
@Override
protected final void updatePopupLocation() {
LinkedPosition currentLinkedPosition = getCurrentLinkedPosition();
if (currentLinkedPosition==null) {
getInfoPopup().setHintTemplate(getHintTemplate());
}
else if (currentLinkedPosition.getSequenceNumber()==1) {
getInfoPopup().setHintTemplate("Enter type for new local {0}");
}
else {
getInfoPopup().setHintTemplate("Enter name for new local {0}");
}
}
private void performInitialChange(IDocument document) {
Tree.Statement st = findStatement(rootNode, node);
Node expression;
Node expanse;
ProducedType resultType;
if (st instanceof Tree.ExpressionStatement) {
Tree.Expression e =
((Tree.ExpressionStatement) st).getExpression();
expression = e;
expanse = st;
resultType = e.getTypeModel();
if (e.getTerm() instanceof Tree.InvocationExpression) {
Primary primary =
((Tree.InvocationExpression) e.getTerm()).getPrimary();
if (primary instanceof Tree.QualifiedMemberExpression) {
Tree.QualifiedMemberExpression prim =
(Tree.QualifiedMemberExpression) primary;
if (prim.getMemberOperator().getToken()==null) {
//an expression followed by two annotations
//can look like a named operator expression
//even though that is disallowed as an
//expression statement
Tree.Primary p = prim.getPrimary();
expression = p;
expanse = expression;
resultType = p.getTypeModel();
}
}
}
}
else if (st instanceof Tree.Declaration) {
Tree.Declaration dec = (Tree.Declaration) st;
Declaration d = dec.getDeclarationModel();
if (d==null || d.isToplevel()) {
return;
}
//some expressions get interpreted as annotations
List<Annotation> annotations =
dec.getAnnotationList().getAnnotations();
Tree.AnonymousAnnotation aa =
dec.getAnnotationList().getAnonymousAnnotation();
if (aa!=null && currentOffset<=aa.getStopIndex()+1) {
expression = aa;
expanse = expression;
resultType = aa.getUnit().getStringDeclaration().getType();
}
else if (!annotations.isEmpty() &&
currentOffset<=dec.getAnnotationList().getStopIndex()+1) {
Tree.Annotation a = annotations.get(0);
expression = a;
expanse = expression;
resultType = a.getTypeModel();
}
else if (st instanceof Tree.TypedDeclaration) {
//some expressions look like a type declaration
//when they appear right in front of an annotation
//or function invocations
Tree.Type type = ((Tree.TypedDeclaration) st).getType();
if (type instanceof Tree.SimpleType) {
expression = type;
expanse = expression;
resultType = type.getTypeModel();
}
else if (type instanceof Tree.FunctionType) {
expression = type;
expanse = expression;
resultType = node.getUnit()
.getCallableReturnType(type.getTypeModel());
}
else {
return;
}
}
else {
return;
}
}
else {
return;
}
Integer stopIndex = expanse.getStopIndex();
if (currentOffset<expanse.getStartIndex() ||
currentOffset>stopIndex+1) {
return;
}
nameProposals = computeNameProposals(expression);
initialName = nameProposals[0];
offset = expanse.getStartIndex();
type = resultType==null ?
null : node.getUnit().denotableType(resultType);
DocumentChange change =
createChange(document, expanse, stopIndex);
try {
change.perform(new NullProgressMonitor());
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
String[] computeNameProposals(Node expression) {
return Nodes.nameProposals(expression);
}
protected abstract DocumentChange createChange(IDocument document,
Node expanse, Integer stopIndex);
protected final Node node;
protected final Tree.CompilationUnit rootNode;
@Override
public void apply(IDocument document) {
try {
performInitialChange(document);
CeylonParseController cpc = editor.getParseController();
Unit unit = cpc.getRootNode().getUnit();
addLinkedPositions(document, unit);
enterLinkedMode(document, 2, exitPos + initialName.length() + 9);
openPopup();
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
protected abstract void addLinkedPositions(IDocument document, Unit unit)
throws BadLocationException;
@Override
public StyledString getStyledDisplayString() {
return Highlights.styleProposal(getDisplayString(), false, true);
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public Image getImage() {
return MINOR_CHANGE;
}
@Override
public IContextInformation getContextInformation() {
return null;
}
public LocalProposal(Tree.CompilationUnit cu, Node node,
int currentOffset) {
super((CeylonEditor) EditorUtil.getCurrentEditor());
this.rootNode = cu;
this.node = node;
this.currentOffset = currentOffset;
}
boolean isEnabled(ProducedType resultType) {
return true;
}
boolean isEnabled() {
Tree.Statement st = findStatement(rootNode, node);
if (st instanceof Tree.ExpressionStatement) {
Tree.Expression e =
((Tree.ExpressionStatement) st).getExpression();
ProducedType resultType = e.getTypeModel();
if (e.getTerm() instanceof Tree.InvocationExpression) {
Primary primary =
((Tree.InvocationExpression) e.getTerm()).getPrimary();
if (primary instanceof Tree.QualifiedMemberExpression) {
Tree.QualifiedMemberExpression prim =
(Tree.QualifiedMemberExpression) primary;
if (prim.getMemberOperator().getToken()==null) {
//an expression followed by two annotations
//can look like a named operator expression
//even though that is disallowed as an
//expression statement
Tree.Primary p = prim.getPrimary();
resultType = p.getTypeModel();
}
}
}
return isEnabled(resultType);
}
else if (st instanceof Tree.Declaration) {
Tree.Declaration dec = (Tree.Declaration) st;
Identifier id = dec.getIdentifier();
if (id==null) {
return false;
}
int line = id.getToken().getLine();
Declaration d = dec.getDeclarationModel();
if (d==null || d.isToplevel()) {
return false;
}
//some expressions get interpreted as annotations
List<Annotation> annotations =
dec.getAnnotationList().getAnnotations();
Tree.AnonymousAnnotation aa =
dec.getAnnotationList().getAnonymousAnnotation();
ProducedType resultType;
if (aa!=null && currentOffset<=aa.getStopIndex()+1) {
if (aa.getEndToken().getLine()==line) {
return false;
}
resultType = aa.getUnit().getStringDeclaration().getType();
}
else if (!annotations.isEmpty() &&
currentOffset<=dec.getAnnotationList().getStopIndex()+1) {
Tree.Annotation a = annotations.get(0);
if (a.getEndToken().getLine()==line) {
return false;
}
resultType = a.getTypeModel();
}
else if (st instanceof Tree.TypedDeclaration) {
//some expressions look like a type declaration
//when they appear right in front of an annotation
//or function invocations
Tree.Type type = ((Tree.TypedDeclaration) st).getType();
if (currentOffset<=type.getStopIndex()+1 &&
currentOffset>=type.getStartIndex() &&
type.getEndToken().getLine()!=line) {
resultType = type.getTypeModel();
if (type instanceof Tree.SimpleType) {
//just use that type
}
else if (type instanceof Tree.FunctionType) {
//instantiation expressions look like a
//function type declaration
resultType = node.getUnit()
.getCallableReturnType(resultType);
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
return isEnabled(resultType);
}
return false;
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_LocalProposal.java
|
19 |
public abstract class TypeAwareCommandParser implements CommandParser {
protected final TextCommandConstants.TextCommandType type;
protected TypeAwareCommandParser(TextCommandConstants.TextCommandType type) {
this.type = type;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_ascii_TypeAwareCommandParser.java
|
1,032 |
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response result) {
try {
channel.sendResponse(result);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("failed to send response for get", e1);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_support_single_shard_TransportShardSingleOperationAction.java
|
596 |
public class JoinRequestOperation extends AbstractClusterOperation implements JoinOperation {
private JoinRequest message;
public JoinRequestOperation() {
}
public JoinRequestOperation(JoinRequest message) {
this.message = message;
}
@Override
public void run() {
ClusterServiceImpl cm = getService();
cm.handleJoinRequest(this);
}
public JoinRequest getMessage() {
return message;
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
message = new JoinRequest();
message.readData(in);
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
message.writeData(out);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("JoinRequestOperation");
sb.append("{message=").append(message);
sb.append('}');
return sb.toString();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_cluster_JoinRequestOperation.java
|
809 |
public class GetAndSetRequest extends AtomicLongRequest {
public GetAndSetRequest() {
}
public GetAndSetRequest(String name, long value) {
super(name, value);
}
@Override
protected Operation prepareOperation() {
return new GetAndSetOperation(name, delta);
}
@Override
public int getClassId() {
return AtomicLongPortableHook.GET_AND_SET;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_GetAndSetRequest.java
|
336 |
public class NodesRestartRequestBuilder extends NodesOperationRequestBuilder<NodesRestartRequest, NodesRestartResponse, NodesRestartRequestBuilder> {
public NodesRestartRequestBuilder(ClusterAdminClient clusterClient) {
super((InternalClusterAdminClient) clusterClient, new NodesRestartRequest());
}
/**
* The delay for the restart to occur. Defaults to <tt>1s</tt>.
*/
public NodesRestartRequestBuilder setDelay(TimeValue delay) {
request.delay(delay);
return this;
}
/**
* The delay for the restart to occur. Defaults to <tt>1s</tt>.
*/
public NodesRestartRequestBuilder setDelay(String delay) {
request.delay(delay);
return this;
}
@Override
protected void doExecute(ActionListener<NodesRestartResponse> listener) {
((ClusterAdminClient) client).nodesRestart(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_restart_NodesRestartRequestBuilder.java
|
229 |
public interface SystemPropertiesDao {
public SystemProperty saveSystemProperty(SystemProperty systemProperty);
public void deleteSystemProperty(SystemProperty systemProperty);
public List<SystemProperty> readAllSystemProperties();
public SystemProperty readSystemPropertyByName(String name);
public SystemProperty createNewSystemProperty();
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_config_dao_SystemPropertiesDao.java
|
89 |
private enum Symbol {
LATTER, WS, QT, AP, SEP, EOF
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_console_ODFACommandStream.java
|
983 |
private class TransportHandler extends BaseTransportRequestHandler<Request> {
@Override
public Request newInstance() {
return newRequestInstance();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void messageReceived(final Request request, final TransportChannel channel) throws Exception {
// no need to use threaded listener, since we just send a response
request.listenerThreaded(false);
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response result) {
try {
channel.sendResponse(result);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send error response for action [" + transportAction() + "] and request [" + request + "]", e1);
}
}
});
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_replication_TransportIndexReplicationOperationAction.java
|
82 |
@SuppressWarnings("serial")
static final class MapReduceValuesToDoubleTask<K,V>
extends BulkTask<K,V,Double> {
final ObjectToDouble<? super V> transformer;
final DoubleByDoubleToDouble reducer;
final double basis;
double result;
MapReduceValuesToDoubleTask<K,V> rights, nextRight;
MapReduceValuesToDoubleTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceValuesToDoubleTask<K,V> nextRight,
ObjectToDouble<? super V> transformer,
double basis,
DoubleByDoubleToDouble reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Double getRawResult() { return result; }
public final void compute() {
final ObjectToDouble<? super V> transformer;
final DoubleByDoubleToDouble reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
double r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceValuesToDoubleTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.apply(r, transformer.apply(p.val));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
t = (MapReduceValuesToDoubleTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.apply(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
118 |
public class OSystemVariableResolver implements OVariableParserListener {
public static final String VAR_BEGIN = "${";
public static final String VAR_END = "}";
private static OSystemVariableResolver instance = new OSystemVariableResolver();
public static String resolveSystemVariables(final String iPath) {
if (iPath == null)
return null;
return (String) OVariableParser.resolveVariables(iPath, VAR_BEGIN, VAR_END, instance);
}
public String resolve(final String variable) {
String resolved = System.getProperty(variable);
if (resolved == null)
// TRY TO FIND THE VARIABLE BETWEEN SYSTEM'S ENVIRONMENT PROPERTIES
resolved = System.getenv(variable);
return resolved;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_parser_OSystemVariableResolver.java
|
1,576 |
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, LongWritable> {
private boolean isVertex;
private final LongWritable longWritable = new LongWritable();
private SafeMapperOutputs outputs;
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class);
this.outputs = new SafeMapperOutputs(context);
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, LongWritable>.Context context) throws IOException, InterruptedException {
if (this.isVertex) {
final long pathCount = value.pathCount();
this.longWritable.set(pathCount);
context.write(NullWritable.get(), this.longWritable);
DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_COUNTED, pathCount > 0 ? 1 : 0);
} else {
long edgesCounted = 0;
long pathCount = 0;
for (final Edge e : value.getEdges(Direction.OUT)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
edgesCounted++;
pathCount = pathCount + edge.pathCount();
}
}
this.longWritable.set(pathCount);
context.write(NullWritable.get(), this.longWritable);
DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGES_COUNTED, edgesCounted);
}
this.outputs.write(Tokens.GRAPH, NullWritable.get(), value);
}
@Override
public void cleanup(final Mapper<NullWritable, FaunusVertex, NullWritable, LongWritable>.Context context) throws IOException, InterruptedException {
this.outputs.close();
}
}
| 1no label
|
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_util_CountMapReduce.java
|
727 |
public class OSBTree<K, V> extends ODurableComponent implements OTreeInternal<K, V> {
private static final int MAX_KEY_SIZE = OGlobalConfiguration.SBTREE_MAX_KEY_SIZE
.getValueAsInteger();
private static final int MAX_EMBEDDED_VALUE_SIZE = OGlobalConfiguration.SBTREE_MAX_EMBEDDED_VALUE_SIZE
.getValueAsInteger();
private static final OAlwaysLessKey ALWAYS_LESS_KEY = new OAlwaysLessKey();
private static final OAlwaysGreaterKey ALWAYS_GREATER_KEY = new OAlwaysGreaterKey();
private final static long ROOT_INDEX = 0;
private final Comparator<? super K> comparator = ODefaultComparator.INSTANCE;
private OStorageLocalAbstract storage;
private String name;
private final String dataFileExtension;
private ODiskCache diskCache;
private long fileId;
private int keySize;
private OBinarySerializer<K> keySerializer;
private OType[] keyTypes;
private OBinarySerializer<V> valueSerializer;
private final boolean durableInNonTxMode;
private static final ODurablePage.TrackMode txTrackMode = ODurablePage.TrackMode
.valueOf(OGlobalConfiguration.INDEX_TX_MODE
.getValueAsString().toUpperCase());
public OSBTree(String dataFileExtension, int keySize, boolean durableInNonTxMode) {
super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean());
this.dataFileExtension = dataFileExtension;
this.keySize = keySize;
this.durableInNonTxMode = durableInNonTxMode;
}
public void create(String name, OBinarySerializer<K> keySerializer, OBinarySerializer<V> valueSerializer, OType[] keyTypes,
OStorageLocalAbstract storageLocal) {
acquireExclusiveLock();
try {
this.storage = storageLocal;
this.keyTypes = keyTypes;
this.diskCache = storage.getDiskCache();
this.name = name;
this.keySerializer = keySerializer;
this.valueSerializer = valueSerializer;
fileId = diskCache.openFile(name + dataFileExtension);
initDurableComponent(storageLocal);
OCacheEntry rootCacheEntry = diskCache.load(fileId, ROOT_INDEX, false);
OCachePointer rootPointer = rootCacheEntry.getCachePointer();
rootPointer.acquireExclusiveLock();
try {
super.startDurableOperation(null);
OSBTreeBucket<K, V> rootBucket = new OSBTreeBucket<K, V>(rootPointer.getDataPointer(), true, keySerializer, keyTypes,
valueSerializer, getTrackMode());
rootBucket.setKeySerializerId(keySerializer.getId());
rootBucket.setValueSerializerId(valueSerializer.getId());
rootBucket.setTreeSize(0);
super.logPageChanges(rootBucket, fileId, ROOT_INDEX, true);
rootCacheEntry.markDirty();
} finally {
rootPointer.releaseExclusiveLock();
diskCache.release(rootCacheEntry);
}
super.endDurableOperation(null, false);
} catch (IOException e) {
try {
super.endDurableOperation(null, true);
} catch (IOException e1) {
OLogManager.instance().error(this, "Error during sbtree data rollback", e1);
}
throw new OSBTreeException("Error creation of sbtree with name" + name, e);
} finally {
releaseExclusiveLock();
}
}
private void initDurableComponent(OStorageLocalAbstract storageLocal) {
OWriteAheadLog writeAheadLog = storageLocal.getWALInstance();
init(writeAheadLog);
}
public String getName() {
acquireSharedLock();
try {
return name;
} finally {
releaseSharedLock();
}
}
public V get(K key) {
if (key == null)
return null;
acquireSharedLock();
try {
key = keySerializer.preprocess(key, (Object[]) keyTypes);
BucketSearchResult bucketSearchResult = findBucket(key, PartialSearchMode.NONE);
if (bucketSearchResult.itemIndex < 0)
return null;
long pageIndex = bucketSearchResult.getLastPathItem();
OCacheEntry keyBucketCacheEntry = diskCache.load(fileId, pageIndex, false);
OCachePointer keyBucketPointer = keyBucketCacheEntry.getCachePointer();
try {
OSBTreeBucket<K, V> keyBucket = new OSBTreeBucket<K, V>(keyBucketPointer.getDataPointer(), keySerializer, keyTypes,
valueSerializer, ODurablePage.TrackMode.NONE);
OSBTreeBucket.SBTreeEntry<K, V> treeEntry = keyBucket.getEntry(bucketSearchResult.itemIndex);
return readValue(treeEntry.value);
} finally {
diskCache.release(keyBucketCacheEntry);
}
} catch (IOException e) {
throw new OSBTreeException("Error during retrieving of sbtree with name " + name, e);
} finally {
releaseSharedLock();
}
}
public void put(K key, V value) {
acquireExclusiveLock();
final OStorageTransaction transaction = storage.getStorageTransaction();
try {
final int keySize = keySerializer.getObjectSize(key, (Object[]) keyTypes);
final int valueSize = valueSerializer.getObjectSize(value);
if (keySize > MAX_KEY_SIZE)
throw new OSBTreeException("Key size is more than allowed, operation was canceled. Current key size " + keySize
+ ", allowed " + MAX_KEY_SIZE);
final boolean createLinkToTheValue = valueSize > MAX_EMBEDDED_VALUE_SIZE;
key = keySerializer.preprocess(key, (Object[]) keyTypes);
startDurableOperation(transaction);
long valueLink = -1;
if (createLinkToTheValue)
valueLink = createLinkToTheValue(value);
final OSBTreeValue<V> treeValue = new OSBTreeValue<V>(createLinkToTheValue, valueLink, createLinkToTheValue ? null : value);
BucketSearchResult bucketSearchResult = findBucket(key, PartialSearchMode.NONE);
OCacheEntry keyBucketCacheEntry = diskCache.load(fileId, bucketSearchResult.getLastPathItem(), false);
OCachePointer keyBucketPointer = keyBucketCacheEntry.getCachePointer();
keyBucketPointer.acquireExclusiveLock();
OSBTreeBucket<K, V> keyBucket = new OSBTreeBucket<K, V>(keyBucketPointer.getDataPointer(), keySerializer, keyTypes,
valueSerializer, getTrackMode());
int insertionIndex;
int sizeDiff;
if (bucketSearchResult.itemIndex >= 0) {
int updateResult = keyBucket.updateValue(bucketSearchResult.itemIndex, treeValue);
if (updateResult == 1) {
logPageChanges(keyBucket, fileId, keyBucketCacheEntry.getPageIndex(), false);
keyBucketCacheEntry.markDirty();
}
if (updateResult >= 0) {
keyBucketPointer.releaseExclusiveLock();
diskCache.release(keyBucketCacheEntry);
endDurableOperation(transaction, false);
return;
} else {
assert updateResult == -1;
long removedLinkedValue = keyBucket.remove(bucketSearchResult.itemIndex);
if (removedLinkedValue >= 0)
removeLinkedValue(removedLinkedValue);
insertionIndex = bucketSearchResult.itemIndex;
sizeDiff = 0;
}
} else {
insertionIndex = -bucketSearchResult.itemIndex - 1;
sizeDiff = 1;
}
while (!keyBucket.addEntry(insertionIndex, new OSBTreeBucket.SBTreeEntry<K, V>(-1, -1, key, treeValue), true)) {
logPageChanges(keyBucket, fileId, keyBucketCacheEntry.getPageIndex(), false);
keyBucketPointer.releaseExclusiveLock();
diskCache.release(keyBucketCacheEntry);
bucketSearchResult = splitBucket(bucketSearchResult.path, insertionIndex, key);
insertionIndex = bucketSearchResult.itemIndex;
keyBucketCacheEntry = diskCache.load(fileId, bucketSearchResult.getLastPathItem(), false);
keyBucketPointer = keyBucketCacheEntry.getCachePointer();
keyBucketPointer.acquireExclusiveLock();
keyBucket = new OSBTreeBucket<K, V>(keyBucketPointer.getDataPointer(), keySerializer, keyTypes, valueSerializer,
getTrackMode());
}
logPageChanges(keyBucket, fileId, bucketSearchResult.getLastPathItem(), false);
keyBucketCacheEntry.markDirty();
keyBucketPointer.releaseExclusiveLock();
diskCache.release(keyBucketCacheEntry);
if (sizeDiff != 0)
setSize(size() + sizeDiff);
endDurableOperation(transaction, false);
} catch (IOException e) {
rollback(transaction);
throw new OSBTreeException("Error during index update with key " + key + " and value " + value, e);
} finally {
releaseExclusiveLock();
}
}
private void removeLinkedValue(long removedLink) throws IOException {
long nextPage = removedLink;
do {
removedLink = nextPage;
OCacheEntry valueEntry = diskCache.load(fileId, removedLink, false);
OCachePointer valuePointer = valueEntry.getCachePointer();
try {
OSBTreeValuePage valuePage = new OSBTreeValuePage(valuePointer.getDataPointer(), getTrackMode(), false);
nextPage = valuePage.getNextPage();
} finally {
diskCache.release(valueEntry);
}
removeValuePage(removedLink);
} while (nextPage >= 0);
}
private void removeValuePage(long pageIndex) throws IOException {
long prevFreeListItem;
OCacheEntry rootCacheEntry = diskCache.load(fileId, ROOT_INDEX, false);
OCachePointer rootCachePointer = rootCacheEntry.getCachePointer();
rootCachePointer.acquireExclusiveLock();
OSBTreeBucket<K, V> rootBucket = new OSBTreeBucket<K, V>(rootCachePointer.getDataPointer(), keySerializer, keyTypes,
valueSerializer, getTrackMode());
try {
prevFreeListItem = rootBucket.getValuesFreeListFirstIndex();
rootBucket.setValuesFreeListFirstIndex(pageIndex);
rootCacheEntry.markDirty();
logPageChanges(rootBucket, fileId, ROOT_INDEX, false);
} finally {
rootCachePointer.releaseExclusiveLock();
diskCache.release(rootCacheEntry);
}
OCacheEntry valueEntry = diskCache.load(fileId, pageIndex, false);
OCachePointer valuePointer = valueEntry.getCachePointer();
valuePointer.acquireExclusiveLock();
try {
OSBTreeValuePage valuePage = new OSBTreeValuePage(valuePointer.getDataPointer(), getTrackMode(), false);
valuePage.setNextFreeListPage(prevFreeListItem);
valueEntry.markDirty();
logPageChanges(valuePage, fileId, pageIndex, false);
} finally {
valuePointer.releaseExclusiveLock();
diskCache.release(valueEntry);
}
}
private long createLinkToTheValue(V value) throws IOException {
byte[] serializeValue = new byte[valueSerializer.getObjectSize(value)];
valueSerializer.serializeNative(value, serializeValue, 0);
final int amountOfPages = OSBTreeValuePage.calculateAmountOfPage(serializeValue.length);
int position = 0;
long freeListPageIndex = allocateValuePageFromFreeList();
OCacheEntry cacheEntry;
if (freeListPageIndex < 0)
cacheEntry = diskCache.allocateNewPage(fileId);
else
cacheEntry = diskCache.load(fileId, freeListPageIndex, false);
final long valueLink = cacheEntry.getPageIndex();
OCachePointer cachePointer = cacheEntry.getCachePointer();
cachePointer.acquireExclusiveLock();
try {
OSBTreeValuePage valuePage = new OSBTreeValuePage(cachePointer.getDataPointer(), getTrackMode(), freeListPageIndex >= 0);
position = valuePage.fillBinaryContent(serializeValue, position);
valuePage.setNextFreeListPage(-1);
valuePage.setNextPage(-1);
cacheEntry.markDirty();
if (freeListPageIndex < 0)
logPageChanges(valuePage, fileId, cacheEntry.getPageIndex(), true);
else
logPageChanges(valuePage, fileId, cacheEntry.getPageIndex(), false);
} finally {
cachePointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
long prevPage = valueLink;
for (int i = 1; i < amountOfPages; i++) {
freeListPageIndex = allocateValuePageFromFreeList();
if (freeListPageIndex < 0)
cacheEntry = diskCache.allocateNewPage(fileId);
else
cacheEntry = diskCache.load(fileId, freeListPageIndex, false);
cachePointer = cacheEntry.getCachePointer();
cachePointer.acquireExclusiveLock();
try {
OSBTreeValuePage valuePage = new OSBTreeValuePage(cachePointer.getDataPointer(), getTrackMode(), freeListPageIndex >= 0);
position = valuePage.fillBinaryContent(serializeValue, position);
valuePage.setNextFreeListPage(-1);
valuePage.setNextPage(-1);
cacheEntry.markDirty();
if (freeListPageIndex < 0)
logPageChanges(valuePage, fileId, cacheEntry.getPageIndex(), true);
else
logPageChanges(valuePage, fileId, cacheEntry.getPageIndex(), false);
} finally {
cachePointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
OCacheEntry prevPageCacheEntry = diskCache.load(fileId, prevPage, false);
OCachePointer prevPageCachePointer = prevPageCacheEntry.getCachePointer();
prevPageCachePointer.acquireExclusiveLock();
try {
OSBTreeValuePage valuePage = new OSBTreeValuePage(prevPageCachePointer.getDataPointer(), getTrackMode(),
freeListPageIndex >= 0);
valuePage.setNextPage(cacheEntry.getPageIndex());
prevPageCacheEntry.markDirty();
logPageChanges(valuePage, fileId, prevPage, false);
} finally {
prevPageCachePointer.releaseExclusiveLock();
diskCache.release(prevPageCacheEntry);
}
prevPage = cacheEntry.getPageIndex();
}
return valueLink;
}
private long allocateValuePageFromFreeList() throws IOException {
OCacheEntry rootCacheEntry = diskCache.load(fileId, ROOT_INDEX, false);
OCachePointer rootCachePointer = rootCacheEntry.getCachePointer();
OSBTreeBucket<K, V> rootBucket = new OSBTreeBucket<K, V>(rootCachePointer.getDataPointer(), keySerializer, keyTypes,
valueSerializer, ODurablePage.TrackMode.NONE);
long freeListFirstIndex;
try {
freeListFirstIndex = rootBucket.getValuesFreeListFirstIndex();
} finally {
diskCache.release(rootCacheEntry);
}
if (freeListFirstIndex >= 0) {
OCacheEntry freePageEntry = diskCache.load(fileId, freeListFirstIndex, false);
OCachePointer freePageCachePointer = freePageEntry.getCachePointer();
OSBTreeValuePage valuePage = new OSBTreeValuePage(freePageCachePointer.getDataPointer(), getTrackMode(), false);
freePageCachePointer.acquireExclusiveLock();
try {
long nextFreeListIndex = valuePage.getNextFreeListPage();
rootCacheEntry = diskCache.load(fileId, ROOT_INDEX, false);
rootCachePointer = rootCacheEntry.getCachePointer();
rootCachePointer.acquireExclusiveLock();
rootBucket = new OSBTreeBucket<K, V>(rootCachePointer.getDataPointer(), keySerializer, keyTypes, valueSerializer,
getTrackMode());
try {
rootBucket.setValuesFreeListFirstIndex(nextFreeListIndex);
rootCacheEntry.markDirty();
logPageChanges(rootBucket, fileId, ROOT_INDEX, false);
} finally {
rootCachePointer.releaseExclusiveLock();
diskCache.release(rootCacheEntry);
}
valuePage.setNextFreeListPage(-1);
freePageEntry.markDirty();
logPageChanges(valuePage, fileId, freePageEntry.getPageIndex(), false);
} finally {
freePageCachePointer.releaseExclusiveLock();
diskCache.release(freePageEntry);
}
return freePageEntry.getPageIndex();
}
return -1;
}
private void rollback(OStorageTransaction transaction) {
try {
endDurableOperation(transaction, true);
} catch (IOException e1) {
OLogManager.instance().error(this, "Error during sbtree operation rollback", e1);
}
}
public void close(boolean flush) {
acquireExclusiveLock();
try {
diskCache.closeFile(fileId, flush);
} catch (IOException e) {
throw new OSBTreeException("Error during close of index " + name, e);
} finally {
releaseExclusiveLock();
}
}
public void close() {
close(true);
}
public void clear() {
acquireExclusiveLock();
OStorageTransaction transaction = storage.getStorageTransaction();
try {
startDurableOperation(transaction);
diskCache.truncateFile(fileId);
OCacheEntry cacheEntry = diskCache.load(fileId, ROOT_INDEX, false);
OCachePointer rootPointer = cacheEntry.getCachePointer();
rootPointer.acquireExclusiveLock();
try {
OSBTreeBucket<K, V> rootBucket = new OSBTreeBucket<K, V>(rootPointer.getDataPointer(), true, keySerializer, keyTypes,
valueSerializer, getTrackMode());
rootBucket.setKeySerializerId(keySerializer.getId());
rootBucket.setValueSerializerId(valueSerializer.getId());
rootBucket.setTreeSize(0);
logPageChanges(rootBucket, fileId, ROOT_INDEX, true);
cacheEntry.markDirty();
} finally {
rootPointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
endDurableOperation(transaction, false);
} catch (IOException e) {
rollback(transaction);
throw new OSBTreeException("Error during clear of sbtree with name " + name, e);
} finally {
releaseExclusiveLock();
}
}
public void delete() {
acquireExclusiveLock();
try {
diskCache.deleteFile(fileId);
} catch (IOException e) {
throw new OSBTreeException("Error during delete of sbtree with name " + name, e);
} finally {
releaseExclusiveLock();
}
}
public void deleteWithoutLoad(String name, OStorageLocalAbstract storageLocal) {
acquireExclusiveLock();
try {
final ODiskCache diskCache = storageLocal.getDiskCache();
final long fileId = diskCache.openFile(name + dataFileExtension);
diskCache.deleteFile(fileId);
} catch (IOException ioe) {
throw new OSBTreeException("Exception during deletion of sbtree " + name, ioe);
} finally {
releaseExclusiveLock();
}
}
public void load(String name, OType[] keyTypes, OStorageLocalAbstract storageLocal) {
acquireExclusiveLock();
try {
this.storage = storageLocal;
this.keyTypes = keyTypes;
diskCache = storage.getDiskCache();
this.name = name;
fileId = diskCache.openFile(name + dataFileExtension);
OCacheEntry rootCacheEntry = diskCache.load(fileId, ROOT_INDEX, false);
OCachePointer rootPointer = rootCacheEntry.getCachePointer();
try {
OSBTreeBucket<K, V> rootBucket = new OSBTreeBucket<K, V>(rootPointer.getDataPointer(), keySerializer, keyTypes,
valueSerializer, ODurablePage.TrackMode.NONE);
keySerializer = (OBinarySerializer<K>) OBinarySerializerFactory.INSTANCE.getObjectSerializer(rootBucket
.getKeySerializerId());
valueSerializer = (OBinarySerializer<V>) OBinarySerializerFactory.INSTANCE.getObjectSerializer(rootBucket
.getValueSerializerId());
} finally {
diskCache.release(rootCacheEntry);
}
initDurableComponent(storageLocal);
} catch (IOException e) {
throw new OSBTreeException("Exception during loading of sbtree " + name, e);
} finally {
releaseExclusiveLock();
}
}
private void setSize(long size) throws IOException {
OCacheEntry rootCacheEntry = diskCache.load(fileId, ROOT_INDEX, false);
OCachePointer rootPointer = rootCacheEntry.getCachePointer();
rootPointer.acquireExclusiveLock();
try {
OSBTreeBucket<K, V> rootBucket = new OSBTreeBucket<K, V>(rootPointer.getDataPointer(), keySerializer, keyTypes,
valueSerializer, getTrackMode());
rootBucket.setTreeSize(size);
logPageChanges(rootBucket, fileId, ROOT_INDEX, false);
rootCacheEntry.markDirty();
} finally {
rootPointer.releaseExclusiveLock();
diskCache.release(rootCacheEntry);
}
}
@Override
public long size() {
acquireSharedLock();
try {
OCacheEntry rootCacheEntry = diskCache.load(fileId, ROOT_INDEX, false);
OCachePointer rootPointer = rootCacheEntry.getCachePointer();
try {
OSBTreeBucket<K, V> rootBucket = new OSBTreeBucket<K, V>(rootPointer.getDataPointer(), keySerializer, keyTypes,
valueSerializer, ODurablePage.TrackMode.NONE);
return rootBucket.getTreeSize();
} finally {
diskCache.release(rootCacheEntry);
}
} catch (IOException e) {
throw new OSBTreeException("Error during retrieving of size of index " + name);
} finally {
releaseSharedLock();
}
}
@Override
public V remove(K key) {
acquireExclusiveLock();
OStorageTransaction transaction = storage.getStorageTransaction();
try {
key = keySerializer.preprocess(key, (Object[]) keyTypes);
BucketSearchResult bucketSearchResult = findBucket(key, PartialSearchMode.NONE);
if (bucketSearchResult.itemIndex < 0)
return null;
OCacheEntry keyBucketCacheEntry = diskCache.load(fileId, bucketSearchResult.getLastPathItem(), false);
OCachePointer keyBucketPointer = keyBucketCacheEntry.getCachePointer();
keyBucketPointer.acquireExclusiveLock();
try {
startDurableOperation(transaction);
OSBTreeBucket<K, V> keyBucket = new OSBTreeBucket<K, V>(keyBucketPointer.getDataPointer(), keySerializer, keyTypes,
valueSerializer, getTrackMode());
final OSBTreeValue<V> removed = keyBucket.getEntry(bucketSearchResult.itemIndex).value;
final V value = readValue(removed);
long removedValueLink = keyBucket.remove(bucketSearchResult.itemIndex);
if (removedValueLink >= 0)
removeLinkedValue(removedValueLink);
logPageChanges(keyBucket, fileId, keyBucketCacheEntry.getPageIndex(), false);
keyBucketCacheEntry.markDirty();
setSize(size() - 1);
endDurableOperation(transaction, false);
return value;
} finally {
keyBucketPointer.releaseExclusiveLock();
diskCache.release(keyBucketCacheEntry);
}
} catch (IOException e) {
rollback(transaction);
throw new OSBTreeException("Error during removing key " + key + " from sbtree " + name, e);
} finally {
releaseExclusiveLock();
}
}
@Override
protected void endDurableOperation(OStorageTransaction transaction, boolean rollback) throws IOException {
if (transaction == null && !durableInNonTxMode)
return;
super.endDurableOperation(transaction, rollback);
}
@Override
protected void startDurableOperation(OStorageTransaction transaction) throws IOException {
if (transaction == null && !durableInNonTxMode)
return;
super.startDurableOperation(transaction);
}
@Override
protected void logPageChanges(ODurablePage localPage, long fileId, long pageIndex, boolean isNewPage) throws IOException {
final OStorageTransaction transaction = storage.getStorageTransaction();
if (transaction == null && !durableInNonTxMode)
return;
super.logPageChanges(localPage, fileId, pageIndex, isNewPage);
}
@Override
protected ODurablePage.TrackMode getTrackMode() {
final OStorageTransaction transaction = storage.getStorageTransaction();
if (transaction == null && !durableInNonTxMode)
return ODurablePage.TrackMode.NONE;
final ODurablePage.TrackMode trackMode = super.getTrackMode();
if (!trackMode.equals(ODurablePage.TrackMode.NONE))
return txTrackMode;
return trackMode;
}
public Collection<V> getValuesMinor(K key, boolean inclusive, final int maxValuesToFetch) {
final List<V> result = new ArrayList<V>();
loadEntriesMinor(key, inclusive, new RangeResultListener<K, V>() {
@Override
public boolean addResult(Map.Entry<K, V> entry) {
result.add(entry.getValue());
if (maxValuesToFetch > -1 && result.size() >= maxValuesToFetch)
return false;
return true;
}
});
return result;
}
public void loadEntriesMinor(K key, boolean inclusive, RangeResultListener<K, V> listener) {
acquireSharedLock();
try {
key = keySerializer.preprocess(key, (Object[]) keyTypes);
final PartialSearchMode partialSearchMode;
if (inclusive)
partialSearchMode = PartialSearchMode.HIGHEST_BOUNDARY;
else
partialSearchMode = PartialSearchMode.LOWEST_BOUNDARY;
BucketSearchResult bucketSearchResult = findBucket(key, partialSearchMode);
long pageIndex = bucketSearchResult.getLastPathItem();
int index;
if (bucketSearchResult.itemIndex >= 0) {
index = inclusive ? bucketSearchResult.itemIndex : bucketSearchResult.itemIndex - 1;
} else {
index = -bucketSearchResult.itemIndex - 2;
}
boolean firstBucket = true;
resultsLoop: while (true) {
long nextPageIndex = -1;
OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
final OCachePointer pointer = cacheEntry.getCachePointer();
try {
OSBTreeBucket<K, V> bucket = new OSBTreeBucket<K, V>(pointer.getDataPointer(), keySerializer, keyTypes, valueSerializer,
ODurablePage.TrackMode.NONE);
if (!firstBucket)
index = bucket.size() - 1;
for (int i = index; i >= 0; i--) {
if (!listener.addResult(convertToMapEntry(bucket.getEntry(i))))
break resultsLoop;
}
if (bucket.getLeftSibling() >= 0)
nextPageIndex = bucket.getLeftSibling();
else
break;
} finally {
diskCache.release(cacheEntry);
}
pageIndex = nextPageIndex;
firstBucket = false;
}
} catch (IOException ioe) {
throw new OSBTreeException("Error during fetch of minor values for key " + key + " in sbtree " + name);
} finally {
releaseSharedLock();
}
}
public Collection<V> getValuesMajor(K key, boolean inclusive, final int maxValuesToFetch) {
final List<V> result = new ArrayList<V>();
loadEntriesMajor(key, inclusive, new RangeResultListener<K, V>() {
@Override
public boolean addResult(Map.Entry<K, V> entry) {
result.add(entry.getValue());
if (maxValuesToFetch > -1 && result.size() >= maxValuesToFetch)
return false;
return true;
}
});
return result;
}
public void loadEntriesMajor(K key, boolean inclusive, RangeResultListener<K, V> listener) {
acquireSharedLock();
try {
key = keySerializer.preprocess(key, (Object[]) keyTypes);
final PartialSearchMode partialSearchMode;
if (inclusive)
partialSearchMode = PartialSearchMode.LOWEST_BOUNDARY;
else
partialSearchMode = PartialSearchMode.HIGHEST_BOUNDARY;
BucketSearchResult bucketSearchResult = findBucket(key, partialSearchMode);
long pageIndex = bucketSearchResult.getLastPathItem();
int index;
if (bucketSearchResult.itemIndex >= 0) {
index = inclusive ? bucketSearchResult.itemIndex : bucketSearchResult.itemIndex + 1;
} else {
index = -bucketSearchResult.itemIndex - 1;
}
resultsLoop: while (true) {
long nextPageIndex = -1;
final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
final OCachePointer pointer = cacheEntry.getCachePointer();
try {
OSBTreeBucket<K, V> bucket = new OSBTreeBucket<K, V>(pointer.getDataPointer(), keySerializer, keyTypes, valueSerializer,
ODurablePage.TrackMode.NONE);
int bucketSize = bucket.size();
for (int i = index; i < bucketSize; i++) {
if (!listener.addResult(convertToMapEntry(bucket.getEntry(i))))
break resultsLoop;
}
if (bucket.getRightSibling() >= 0)
nextPageIndex = bucket.getRightSibling();
else
break;
} finally {
diskCache.release(cacheEntry);
}
pageIndex = nextPageIndex;
index = 0;
}
} catch (IOException ioe) {
throw new OSBTreeException("Error during fetch of major values for key " + key + " in sbtree " + name);
} finally {
releaseSharedLock();
}
}
public Collection<V> getValuesBetween(K keyFrom, boolean fromInclusive, K keyTo, boolean toInclusive, final int maxValuesToFetch) {
final List<V> result = new ArrayList<V>();
loadEntriesBetween(keyFrom, fromInclusive, keyTo, toInclusive, new RangeResultListener<K, V>() {
@Override
public boolean addResult(Map.Entry<K, V> entry) {
result.add(entry.getValue());
if (maxValuesToFetch > 0 && result.size() >= maxValuesToFetch)
return false;
return true;
}
});
return result;
}
@Override
public K firstKey() {
acquireSharedLock();
try {
LinkedList<PagePathItemUnit> path = new LinkedList<PagePathItemUnit>();
long bucketIndex = ROOT_INDEX;
OCacheEntry cacheEntry = diskCache.load(fileId, bucketIndex, false);
OCachePointer cachePointer = cacheEntry.getCachePointer();
int itemIndex = 0;
OSBTreeBucket<K, V> bucket = new OSBTreeBucket<K, V>(cachePointer.getDataPointer(), keySerializer, keyTypes, valueSerializer,
ODurablePage.TrackMode.NONE);
try {
while (true) {
if (!bucket.isLeaf()) {
if (bucket.isEmpty() || itemIndex > bucket.size()) {
if (!path.isEmpty()) {
PagePathItemUnit pagePathItemUnit = path.removeLast();
bucketIndex = pagePathItemUnit.pageIndex;
itemIndex = pagePathItemUnit.itemIndex + 1;
} else
return null;
} else {
path.add(new PagePathItemUnit(bucketIndex, itemIndex));
if (itemIndex < bucket.size()) {
OSBTreeBucket.SBTreeEntry<K, V> entry = bucket.getEntry(itemIndex);
bucketIndex = entry.leftChild;
} else {
OSBTreeBucket.SBTreeEntry<K, V> entry = bucket.getEntry(itemIndex - 1);
bucketIndex = entry.rightChild;
}
itemIndex = 0;
}
} else {
if (bucket.isEmpty()) {
if (!path.isEmpty()) {
PagePathItemUnit pagePathItemUnit = path.removeLast();
bucketIndex = pagePathItemUnit.pageIndex;
itemIndex = pagePathItemUnit.itemIndex + 1;
} else
return null;
} else {
return bucket.getKey(0);
}
}
diskCache.release(cacheEntry);
cacheEntry = diskCache.load(fileId, bucketIndex, false);
cachePointer = cacheEntry.getCachePointer();
bucket = new OSBTreeBucket<K, V>(cachePointer.getDataPointer(), keySerializer, keyTypes, valueSerializer,
ODurablePage.TrackMode.NONE);
}
} finally {
diskCache.release(cacheEntry);
}
} catch (IOException e) {
throw new OSBTreeException("Error during finding first key in sbtree [" + name + "]");
} finally {
releaseSharedLock();
}
}
public K lastKey() {
acquireSharedLock();
try {
LinkedList<PagePathItemUnit> path = new LinkedList<PagePathItemUnit>();
long bucketIndex = ROOT_INDEX;
OCacheEntry cacheEntry = diskCache.load(fileId, bucketIndex, false);
OCachePointer cachePointer = cacheEntry.getCachePointer();
OSBTreeBucket<K, V> bucket = new OSBTreeBucket<K, V>(cachePointer.getDataPointer(), keySerializer, keyTypes, valueSerializer,
ODurablePage.TrackMode.NONE);
int itemIndex = bucket.size() - 1;
try {
while (true) {
if (!bucket.isLeaf()) {
if (itemIndex < -1) {
if (!path.isEmpty()) {
PagePathItemUnit pagePathItemUnit = path.removeLast();
bucketIndex = pagePathItemUnit.pageIndex;
itemIndex = pagePathItemUnit.itemIndex - 1;
} else
return null;
} else {
path.add(new PagePathItemUnit(bucketIndex, itemIndex));
if (itemIndex > -1) {
OSBTreeBucket.SBTreeEntry<K, V> entry = bucket.getEntry(itemIndex);
bucketIndex = entry.rightChild;
} else {
OSBTreeBucket.SBTreeEntry<K, V> entry = bucket.getEntry(0);
bucketIndex = entry.leftChild;
}
itemIndex = OSBTreeBucket.MAX_PAGE_SIZE_BYTES + 1;
}
} else {
if (bucket.isEmpty()) {
if (!path.isEmpty()) {
PagePathItemUnit pagePathItemUnit = path.removeLast();
bucketIndex = pagePathItemUnit.pageIndex;
itemIndex = pagePathItemUnit.itemIndex - 1;
} else
return null;
} else {
return bucket.getKey(bucket.size() - 1);
}
}
diskCache.release(cacheEntry);
cacheEntry = diskCache.load(fileId, bucketIndex, false);
cachePointer = cacheEntry.getCachePointer();
bucket = new OSBTreeBucket<K, V>(cachePointer.getDataPointer(), keySerializer, keyTypes, valueSerializer,
ODurablePage.TrackMode.NONE);
if (itemIndex == OSBTreeBucket.MAX_PAGE_SIZE_BYTES + 1)
itemIndex = bucket.size() - 1;
}
} finally {
diskCache.release(cacheEntry);
}
} catch (IOException e) {
throw new OSBTreeException("Error during finding first key in sbtree [" + name + "]");
} finally {
releaseSharedLock();
}
}
public void loadEntriesBetween(K keyFrom, boolean fromInclusive, K keyTo, boolean toInclusive,
OTreeInternal.RangeResultListener<K, V> listener) {
acquireSharedLock();
try {
keyFrom = keySerializer.preprocess(keyFrom, (Object[]) keyTypes);
keyTo = keySerializer.preprocess(keyTo, (Object[]) keyTypes);
PartialSearchMode partialSearchModeFrom;
if (fromInclusive)
partialSearchModeFrom = PartialSearchMode.LOWEST_BOUNDARY;
else
partialSearchModeFrom = PartialSearchMode.HIGHEST_BOUNDARY;
BucketSearchResult bucketSearchResultFrom = findBucket(keyFrom, partialSearchModeFrom);
long pageIndexFrom = bucketSearchResultFrom.getLastPathItem();
int indexFrom;
if (bucketSearchResultFrom.itemIndex >= 0) {
indexFrom = fromInclusive ? bucketSearchResultFrom.itemIndex : bucketSearchResultFrom.itemIndex + 1;
} else {
indexFrom = -bucketSearchResultFrom.itemIndex - 1;
}
PartialSearchMode partialSearchModeTo;
if (toInclusive)
partialSearchModeTo = PartialSearchMode.HIGHEST_BOUNDARY;
else
partialSearchModeTo = PartialSearchMode.LOWEST_BOUNDARY;
BucketSearchResult bucketSearchResultTo = findBucket(keyTo, partialSearchModeTo);
long pageIndexTo = bucketSearchResultTo.getLastPathItem();
int indexTo;
if (bucketSearchResultTo.itemIndex >= 0) {
indexTo = toInclusive ? bucketSearchResultTo.itemIndex : bucketSearchResultTo.itemIndex - 1;
} else {
indexTo = -bucketSearchResultTo.itemIndex - 2;
}
int startIndex = indexFrom;
int endIndex;
long pageIndex = pageIndexFrom;
resultsLoop: while (true) {
long nextPageIndex = -1;
final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
final OCachePointer pointer = cacheEntry.getCachePointer();
try {
OSBTreeBucket<K, V> bucket = new OSBTreeBucket<K, V>(pointer.getDataPointer(), keySerializer, keyTypes, valueSerializer,
ODurablePage.TrackMode.NONE);
if (pageIndex != pageIndexTo)
endIndex = bucket.size() - 1;
else
endIndex = indexTo;
for (int i = startIndex; i <= endIndex; i++) {
if (!listener.addResult(convertToMapEntry(bucket.getEntry(i))))
break resultsLoop;
}
if (pageIndex == pageIndexTo)
break;
if (bucket.getRightSibling() >= 0)
nextPageIndex = bucket.getRightSibling();
else
break;
} finally {
diskCache.release(cacheEntry);
}
pageIndex = nextPageIndex;
startIndex = 0;
}
} catch (IOException ioe) {
throw new OSBTreeException("Error during fetch of values between key " + keyFrom + " and key " + keyTo + " in sbtree " + name);
} finally {
releaseSharedLock();
}
}
public void flush() {
acquireSharedLock();
try {
try {
diskCache.flushBuffer();
} catch (IOException e) {
throw new OSBTreeException("Error during flush of sbtree [" + name + "] data");
}
} finally {
releaseSharedLock();
}
}
private BucketSearchResult splitBucket(List<Long> path, int keyIndex, K keyToInsert) throws IOException {
long pageIndex = path.get(path.size() - 1);
OCacheEntry bucketEntry = diskCache.load(fileId, pageIndex, false);
OCachePointer bucketPointer = bucketEntry.getCachePointer();
bucketPointer.acquireExclusiveLock();
try {
OSBTreeBucket<K, V> bucketToSplit = new OSBTreeBucket<K, V>(bucketPointer.getDataPointer(), keySerializer, keyTypes,
valueSerializer, getTrackMode());
final boolean splitLeaf = bucketToSplit.isLeaf();
final int bucketSize = bucketToSplit.size();
int indexToSplit = bucketSize >>> 1;
final K separationKey = bucketToSplit.getKey(indexToSplit);
final List<OSBTreeBucket.SBTreeEntry<K, V>> rightEntries = new ArrayList<OSBTreeBucket.SBTreeEntry<K, V>>(indexToSplit);
final int startRightIndex = splitLeaf ? indexToSplit : indexToSplit + 1;
for (int i = startRightIndex; i < bucketSize; i++)
rightEntries.add(bucketToSplit.getEntry(i));
if (pageIndex != ROOT_INDEX) {
OCacheEntry rightBucketEntry = diskCache.allocateNewPage(fileId);
OCachePointer rightBucketPointer = rightBucketEntry.getCachePointer();
rightBucketPointer.acquireExclusiveLock();
try {
OSBTreeBucket<K, V> newRightBucket = new OSBTreeBucket<K, V>(rightBucketPointer.getDataPointer(), splitLeaf,
keySerializer, keyTypes, valueSerializer, getTrackMode());
newRightBucket.addAll(rightEntries);
bucketToSplit.shrink(indexToSplit);
if (splitLeaf) {
long rightSiblingPageIndex = bucketToSplit.getRightSibling();
newRightBucket.setRightSibling(rightSiblingPageIndex);
newRightBucket.setLeftSibling(pageIndex);
bucketToSplit.setRightSibling(rightBucketEntry.getPageIndex());
if (rightSiblingPageIndex >= 0) {
final OCacheEntry rightSiblingBucketEntry = diskCache.load(fileId, rightSiblingPageIndex, false);
final OCachePointer rightSiblingPointer = rightSiblingBucketEntry.getCachePointer();
rightSiblingPointer.acquireExclusiveLock();
OSBTreeBucket<K, V> rightSiblingBucket = new OSBTreeBucket<K, V>(rightSiblingPointer.getDataPointer(), keySerializer,
keyTypes, valueSerializer, getTrackMode());
try {
rightSiblingBucket.setLeftSibling(rightBucketEntry.getPageIndex());
logPageChanges(rightSiblingBucket, fileId, rightSiblingPageIndex, false);
rightSiblingBucketEntry.markDirty();
} finally {
rightSiblingPointer.releaseExclusiveLock();
diskCache.release(rightSiblingBucketEntry);
}
}
}
long parentIndex = path.get(path.size() - 2);
OCacheEntry parentCacheEntry = diskCache.load(fileId, parentIndex, false);
OCachePointer parentPointer = parentCacheEntry.getCachePointer();
parentPointer.acquireExclusiveLock();
try {
OSBTreeBucket<K, V> parentBucket = new OSBTreeBucket<K, V>(parentPointer.getDataPointer(), keySerializer, keyTypes,
valueSerializer, getTrackMode());
OSBTreeBucket.SBTreeEntry<K, V> parentEntry = new OSBTreeBucket.SBTreeEntry<K, V>(pageIndex,
rightBucketEntry.getPageIndex(), separationKey, null);
int insertionIndex = parentBucket.find(separationKey);
assert insertionIndex < 0;
insertionIndex = -insertionIndex - 1;
while (!parentBucket.addEntry(insertionIndex, parentEntry, true)) {
parentPointer.releaseExclusiveLock();
diskCache.release(parentCacheEntry);
BucketSearchResult bucketSearchResult = splitBucket(path.subList(0, path.size() - 1), insertionIndex, separationKey);
parentIndex = bucketSearchResult.getLastPathItem();
parentCacheEntry = diskCache.load(fileId, parentIndex, false);
parentPointer = parentCacheEntry.getCachePointer();
parentPointer.acquireExclusiveLock();
insertionIndex = bucketSearchResult.itemIndex;
parentBucket = new OSBTreeBucket<K, V>(parentPointer.getDataPointer(), keySerializer, keyTypes, valueSerializer,
getTrackMode());
}
logPageChanges(parentBucket, fileId, parentIndex, false);
} finally {
parentCacheEntry.markDirty();
parentPointer.releaseExclusiveLock();
diskCache.release(parentCacheEntry);
}
logPageChanges(newRightBucket, fileId, rightBucketEntry.getPageIndex(), true);
} finally {
rightBucketEntry.markDirty();
rightBucketPointer.releaseExclusiveLock();
diskCache.release(rightBucketEntry);
}
logPageChanges(bucketToSplit, fileId, pageIndex, false);
ArrayList<Long> resultPath = new ArrayList<Long>(path.subList(0, path.size() - 1));
if (comparator.compare(keyToInsert, separationKey) < 0) {
resultPath.add(pageIndex);
return new BucketSearchResult(keyIndex, resultPath);
}
resultPath.add(rightBucketEntry.getPageIndex());
if (splitLeaf) {
return new BucketSearchResult(keyIndex - indexToSplit, resultPath);
}
resultPath.add(rightBucketEntry.getPageIndex());
return new BucketSearchResult(keyIndex - indexToSplit - 1, resultPath);
} else {
final long freeListPage = bucketToSplit.getValuesFreeListFirstIndex();
final long treeSize = bucketToSplit.getTreeSize();
final byte keySerializeId = bucketToSplit.getKeySerializerId();
final byte valueSerializerId = bucketToSplit.getValueSerializerId();
final List<OSBTreeBucket.SBTreeEntry<K, V>> leftEntries = new ArrayList<OSBTreeBucket.SBTreeEntry<K, V>>(indexToSplit);
for (int i = 0; i < indexToSplit; i++)
leftEntries.add(bucketToSplit.getEntry(i));
OCacheEntry leftBucketEntry = diskCache.allocateNewPage(fileId);
OCachePointer leftBucketPointer = leftBucketEntry.getCachePointer();
OCacheEntry rightBucketEntry = diskCache.allocateNewPage(fileId);
leftBucketPointer.acquireExclusiveLock();
try {
OSBTreeBucket<K, V> newLeftBucket = new OSBTreeBucket<K, V>(leftBucketPointer.getDataPointer(), splitLeaf, keySerializer,
keyTypes, valueSerializer, getTrackMode());
newLeftBucket.addAll(leftEntries);
if (splitLeaf)
newLeftBucket.setRightSibling(rightBucketEntry.getPageIndex());
logPageChanges(newLeftBucket, fileId, leftBucketEntry.getPageIndex(), true);
leftBucketEntry.markDirty();
} finally {
leftBucketPointer.releaseExclusiveLock();
diskCache.release(leftBucketEntry);
}
OCachePointer rightBucketPointer = rightBucketEntry.getCachePointer();
rightBucketPointer.acquireExclusiveLock();
try {
OSBTreeBucket<K, V> newRightBucket = new OSBTreeBucket<K, V>(rightBucketPointer.getDataPointer(), splitLeaf,
keySerializer, keyTypes, valueSerializer, getTrackMode());
newRightBucket.addAll(rightEntries);
if (splitLeaf)
newRightBucket.setLeftSibling(leftBucketEntry.getPageIndex());
logPageChanges(newRightBucket, fileId, rightBucketEntry.getPageIndex(), true);
rightBucketEntry.markDirty();
} finally {
rightBucketPointer.releaseExclusiveLock();
diskCache.release(rightBucketEntry);
}
bucketToSplit = new OSBTreeBucket<K, V>(bucketPointer.getDataPointer(), false, keySerializer, keyTypes, valueSerializer,
getTrackMode());
bucketToSplit.setTreeSize(treeSize);
bucketToSplit.setKeySerializerId(keySerializeId);
bucketToSplit.setValueSerializerId(valueSerializerId);
bucketToSplit.setValuesFreeListFirstIndex(freeListPage);
bucketToSplit.addEntry(0,
new OSBTreeBucket.SBTreeEntry<K, V>(leftBucketEntry.getPageIndex(), rightBucketEntry.getPageIndex(), separationKey,
null), true);
logPageChanges(bucketToSplit, fileId, pageIndex, false);
ArrayList<Long> resultPath = new ArrayList<Long>(path.subList(0, path.size() - 1));
if (comparator.compare(keyToInsert, separationKey) < 0) {
resultPath.add(leftBucketEntry.getPageIndex());
return new BucketSearchResult(keyIndex, resultPath);
}
resultPath.add(rightBucketEntry.getPageIndex());
if (splitLeaf)
return new BucketSearchResult(keyIndex - indexToSplit, resultPath);
return new BucketSearchResult(keyIndex - indexToSplit - 1, resultPath);
}
} finally {
bucketEntry.markDirty();
bucketPointer.releaseExclusiveLock();
diskCache.release(bucketEntry);
}
}
private BucketSearchResult findBucket(K key, PartialSearchMode partialSearchMode) throws IOException {
long pageIndex = ROOT_INDEX;
final ArrayList<Long> path = new ArrayList<Long>();
if (!(keySize == 1 || ((OCompositeKey) key).getKeys().size() == keySize || partialSearchMode.equals(PartialSearchMode.NONE))) {
final OCompositeKey fullKey = new OCompositeKey((Comparable<? super K>) key);
int itemsToAdd = keySize - fullKey.getKeys().size();
final Comparable<?> keyItem;
if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY))
keyItem = ALWAYS_GREATER_KEY;
else
keyItem = ALWAYS_LESS_KEY;
for (int i = 0; i < itemsToAdd; i++)
fullKey.addKey(keyItem);
key = (K) fullKey;
}
while (true) {
path.add(pageIndex);
final OCacheEntry bucketEntry = diskCache.load(fileId, pageIndex, false);
final OCachePointer bucketPointer = bucketEntry.getCachePointer();
final OSBTreeBucket.SBTreeEntry<K, V> entry;
try {
final OSBTreeBucket<K, V> keyBucket = new OSBTreeBucket<K, V>(bucketPointer.getDataPointer(), keySerializer, keyTypes,
valueSerializer, ODurablePage.TrackMode.NONE);
final int index = keyBucket.find(key);
if (keyBucket.isLeaf())
return new BucketSearchResult(index, path);
if (index >= 0)
entry = keyBucket.getEntry(index);
else {
final int insertionIndex = -index - 1;
if (insertionIndex >= keyBucket.size())
entry = keyBucket.getEntry(insertionIndex - 1);
else
entry = keyBucket.getEntry(insertionIndex);
}
} finally {
diskCache.release(bucketEntry);
}
if (comparator.compare(key, entry.key) >= 0)
pageIndex = entry.rightChild;
else
pageIndex = entry.leftChild;
}
}
private V readValue(OSBTreeValue<V> sbTreeValue) throws IOException {
if (!sbTreeValue.isLink())
return sbTreeValue.getValue();
OCacheEntry cacheEntry = diskCache.load(fileId, sbTreeValue.getLink(), false);
OCachePointer cachePointer = cacheEntry.getCachePointer();
OSBTreeValuePage valuePage = new OSBTreeValuePage(cachePointer.getDataPointer(), ODurablePage.TrackMode.NONE, false);
int totalSize = valuePage.getSize();
int currentSize = 0;
byte[] value = new byte[totalSize];
while (currentSize < totalSize) {
currentSize = valuePage.readBinaryContent(value, currentSize);
long nextPage = valuePage.getNextPage();
if (nextPage >= 0) {
diskCache.release(cacheEntry);
cacheEntry = diskCache.load(fileId, nextPage, false);
cachePointer = cacheEntry.getCachePointer();
valuePage = new OSBTreeValuePage(cachePointer.getDataPointer(), ODurablePage.TrackMode.NONE, false);
}
}
diskCache.release(cacheEntry);
return valueSerializer.deserializeNative(value, 0);
}
private Map.Entry<K, V> convertToMapEntry(OSBTreeBucket.SBTreeEntry<K, V> treeEntry) throws IOException {
final K key = treeEntry.key;
final V value = readValue(treeEntry.value);
return new Map.Entry<K, V>() {
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
throw new UnsupportedOperationException("setValue");
}
};
}
private static class BucketSearchResult {
private final int itemIndex;
private final ArrayList<Long> path;
private BucketSearchResult(int itemIndex, ArrayList<Long> path) {
this.itemIndex = itemIndex;
this.path = path;
}
public long getLastPathItem() {
return path.get(path.size() - 1);
}
}
/**
* Indicates search behavior in case of {@link OCompositeKey} keys that have less amount of internal keys are used, whether lowest
* or highest partially matched key should be used.
*/
private static enum PartialSearchMode {
/**
* Any partially matched key will be used as search result.
*/
NONE,
/**
* The biggest partially matched key will be used as search result.
*/
HIGHEST_BOUNDARY,
/**
* The smallest partially matched key will be used as search result.
*/
LOWEST_BOUNDARY
}
private static final class PagePathItemUnit {
private final long pageIndex;
private final int itemIndex;
private PagePathItemUnit(long pageIndex, int itemIndex) {
this.pageIndex = pageIndex;
this.itemIndex = itemIndex;
}
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_index_sbtree_local_OSBTree.java
|
33 |
public class ThriftBlueprintsTest extends AbstractCassandraBlueprintsTest {
@Override
public void beforeSuite() {
CassandraStorageSetup.startCleanEmbedded();
}
@Override
protected WriteConfiguration getGraphConfig() {
return CassandraStorageSetup.getCassandraGraphConfiguration(getClass().getSimpleName());
}
@Override
public void extraCleanUp(String uid) throws BackendException {
ModifiableConfiguration mc =
new ModifiableConfiguration(GraphDatabaseConfiguration.ROOT_NS, getGraphConfig(), Restriction.NONE);
StoreManager m = new CassandraThriftStoreManager(mc);
m.clearStorage();
m.close();
}
}
| 0true
|
titan-cassandra_src_test_java_com_thinkaurelius_titan_blueprints_ThriftBlueprintsTest.java
|
1,455 |
public class OCommandExecutorSQLCreateEdge extends OCommandExecutorSQLSetAware {
public static final String NAME = "CREATE EDGE";
private String from;
private String to;
private OClass clazz;
private String clusterName;
private LinkedHashMap<String, Object> fields;
@SuppressWarnings("unchecked")
public OCommandExecutorSQLCreateEdge parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
init((OCommandRequestText) iRequest);
parserRequiredKeyword("CREATE");
parserRequiredKeyword("EDGE");
String className = null;
String temp = parseOptionalWord(true);
while (temp != null) {
if (temp.equals("CLUSTER")) {
clusterName = parserRequiredWord(false);
} else if (temp.equals(KEYWORD_FROM)) {
from = parserRequiredWord(false, "Syntax error", " =><,\r\n");
} else if (temp.equals("TO")) {
to = parserRequiredWord(false, "Syntax error", " =><,\r\n");
} else if (temp.equals(KEYWORD_SET)) {
fields = new LinkedHashMap<String, Object>();
parseSetFields(fields);
} else if (temp.equals(KEYWORD_CONTENT)) {
parseContent();
} else if (className == null && temp.length() > 0)
className = temp;
temp = parseOptionalWord(true);
if (parserIsEnded())
break;
}
if (className == null)
// ASSIGN DEFAULT CLASS
className = "E";
// GET/CHECK CLASS NAME
clazz = database.getMetadata().getSchema().getClass(className);
if (clazz == null)
throw new OCommandSQLParsingException("Class " + className + " was not found");
return this;
}
/**
* Execute the command and return the ODocument object created.
*/
public Object execute(final Map<Object, Object> iArgs) {
if (clazz == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph();
final Set<ORID> fromIds = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), from);
final Set<ORID> toIds = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), to);
// CREATE EDGES
final List<Object> edges = new ArrayList<Object>();
for (ORID from : fromIds) {
final OrientVertex fromVertex = graph.getVertex(from);
if (fromVertex == null)
throw new OCommandExecutionException("Source vertex '" + from + "' not exists");
for (ORID to : toIds) {
final OrientVertex toVertex;
if (from.equals(to)) {
toVertex = fromVertex;
} else {
toVertex = graph.getVertex(to);
}
final String clsName = clazz.getName();
if (fields != null)
// EVALUATE FIELDS
for (Entry<String, Object> f : fields.entrySet()) {
if (f.getValue() instanceof OSQLFunctionRuntime)
fields.put(f.getKey(), ((OSQLFunctionRuntime) f.getValue()).getValue(to, context));
}
final OrientEdge edge = fromVertex.addEdge(null, toVertex, clsName, clusterName, fields);
if (fields != null && !fields.isEmpty()) {
if (!edge.getRecord().getIdentity().isValid())
edge.convertToDocument();
OSQLHelper.bindParameters(edge.getRecord(), fields, new OCommandParameters(iArgs), context);
}
if (content != null) {
if (!edge.getRecord().getIdentity().isValid())
// LIGHTWEIGHT EDGE, TRANSFORM IT BEFORE
edge.convertToDocument();
edge.getRecord().merge(content, true, false);
}
edge.save(clusterName);
edges.add(edge);
}
}
return edges;
}
@Override
public String getSyntax() {
return "CREATE EDGE [<class>] [CLUSTER <cluster>] FROM <rid>|(<query>|[<rid>]*) TO <rid>|(<query>|[<rid>]*) [SET <field> = <expression>[,]*]|CONTENT {<JSON>}";
}
}
| 1no label
|
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_OCommandExecutorSQLCreateEdge.java
|
385 |
static abstract class MyEntryListener implements EntryListener {
final public CountDownLatch addLatch;
final public CountDownLatch removeLatch;
final public CountDownLatch updateLatch;
final public CountDownLatch evictLatch;
public MyEntryListener(int latchCount){
addLatch = new CountDownLatch(latchCount);
removeLatch = new CountDownLatch(latchCount);
updateLatch = new CountDownLatch(1);
evictLatch = new CountDownLatch(1);
}
public MyEntryListener(int addlatchCount, int removeLatchCount){
addLatch = new CountDownLatch(addlatchCount);
removeLatch = new CountDownLatch(removeLatchCount);
updateLatch = new CountDownLatch(1);
evictLatch = new CountDownLatch(1);
}
};
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_multimap_ClientMultiMapListenersTest.java
|
453 |
public static class AdminPresentationCollection {
public static final String FRIENDLYNAME = "friendlyName";
public static final String SECURITYLEVEL = "securityLevel";
public static final String EXCLUDED = "excluded";
public static final String READONLY = "readOnly";
public static final String USESERVERSIDEINSPECTIONCACHE = "useServerSideInspectionCache";
public static final String ADDTYPE = "addType";
public static final String MANYTOFIELD = "manyToField";
public static final String ORDER = "order";
public static final String TAB = "tab";
public static final String TABORDER = "tabOrder";
public static final String CUSTOMCRITERIA = "customCriteria";
public static final String OPERATIONTYPES = "operationTypes";
public static final String SHOWIFPROPERTY = "showIfProperty";
public static final String CURRENCYCODEFIELD = "currencyCodeField";
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_presentation_override_PropertyType.java
|
160 |
private final class MultiTargetCallback {
final Collection<Address> targets;
final ConcurrentMap<Address, Object> results;
private MultiTargetCallback(Collection<Address> targets) {
this.targets = synchronizedSet(new HashSet<Address>(targets));
this.results = new ConcurrentHashMap<Address, Object>(targets.size());
}
public void notify(Address target, Object result) {
if (targets.remove(target)) {
results.put(target, result);
} else {
if (results.containsKey(target)) {
throw new IllegalArgumentException("Duplicate response from -> " + target);
}
throw new IllegalArgumentException("Unknown target! -> " + target);
}
if (targets.isEmpty()) {
Object response = reduce(results);
endpoint.sendResponse(response, getCallId());
}
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_MultiTargetClientRequest.java
|
436 |
public class ClusterStatsNodeResponse extends NodeOperationResponse {
private NodeInfo nodeInfo;
private NodeStats nodeStats;
private ShardStats[] shardsStats;
private ClusterHealthStatus clusterStatus;
ClusterStatsNodeResponse() {
}
public ClusterStatsNodeResponse(DiscoveryNode node, @Nullable ClusterHealthStatus clusterStatus, NodeInfo nodeInfo, NodeStats nodeStats, ShardStats[] shardsStats) {
super(node);
this.nodeInfo = nodeInfo;
this.nodeStats = nodeStats;
this.shardsStats = shardsStats;
this.clusterStatus = clusterStatus;
}
public NodeInfo nodeInfo() {
return this.nodeInfo;
}
public NodeStats nodeStats() {
return this.nodeStats;
}
/**
* Cluster Health Status, only populated on master nodes.
*/
@Nullable
public ClusterHealthStatus clusterStatus() {
return clusterStatus;
}
public ShardStats[] shardsStats() {
return this.shardsStats;
}
public static ClusterStatsNodeResponse readNodeResponse(StreamInput in) throws IOException {
ClusterStatsNodeResponse nodeResponse = new ClusterStatsNodeResponse();
nodeResponse.readFrom(in);
return nodeResponse;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
clusterStatus = null;
if (in.readBoolean()) {
clusterStatus = ClusterHealthStatus.fromValue(in.readByte());
}
this.nodeInfo = NodeInfo.readNodeInfo(in);
this.nodeStats = NodeStats.readNodeStats(in);
int size = in.readVInt();
shardsStats = new ShardStats[size];
for (size--; size >= 0; size--) {
shardsStats[size] = ShardStats.readShardStats(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
if (clusterStatus == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
out.writeByte(clusterStatus.value());
}
nodeInfo.writeTo(out);
nodeStats.writeTo(out);
out.writeVInt(shardsStats.length);
for (ShardStats ss : shardsStats) {
ss.writeTo(out);
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsNodeResponse.java
|
490 |
public class PasswordReset implements Serializable {
private static final long serialVersionUID = 1L;
private String username;
private String email;
private boolean passwordChangeRequired = false;
private int passwordLength = 22;
private boolean sendResetEmailReliableAsync = false;
public PasswordReset() {
}
public PasswordReset(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean getPasswordChangeRequired() {
return passwordChangeRequired;
}
public void setPasswordChangeRequired(boolean passwordChangeRequired) {
this.passwordChangeRequired = passwordChangeRequired;
}
public int getPasswordLength() {
return passwordLength;
}
public void setPasswordLength(int passwordLength) {
this.passwordLength = passwordLength;
}
public boolean isSendResetEmailReliableAsync() {
return sendResetEmailReliableAsync;
}
public void setSendResetEmailReliableAsync(boolean sendResetEmailReliableAsync) {
this.sendResetEmailReliableAsync = sendResetEmailReliableAsync;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_security_util_PasswordReset.java
|
526 |
public class FlushRequestBuilder extends BroadcastOperationRequestBuilder<FlushRequest, FlushResponse, FlushRequestBuilder> {
public FlushRequestBuilder(IndicesAdminClient indicesClient) {
super((InternalIndicesAdminClient) indicesClient, new FlushRequest());
}
public FlushRequestBuilder setFull(boolean full) {
request.full(full);
return this;
}
@Override
protected void doExecute(ActionListener<FlushResponse> listener) {
((IndicesAdminClient) client).flush(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_flush_FlushRequestBuilder.java
|
4,755 |
Arrays.sort(copy, new Comparator<RestFilter>() {
@Override
public int compare(RestFilter o1, RestFilter o2) {
return o2.order() - o1.order();
}
});
| 1no label
|
src_main_java_org_elasticsearch_rest_RestController.java
|
1,709 |
public class PermissionType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, PermissionType> TYPES = new LinkedHashMap<String, PermissionType>();
public static final PermissionType READ = new PermissionType("READ", "Read");
public static final PermissionType CREATE = new PermissionType("CREATE", "Create");
public static final PermissionType UPDATE = new PermissionType("UPDATE", "Update");
public static final PermissionType DELETE = new PermissionType("DELETE", "Delete");
public static final PermissionType ALL = new PermissionType("ALL", "All");
public static final PermissionType OTHER = new PermissionType("OTHER", "Other");
public static PermissionType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public PermissionType() {
//do nothing
}
public PermissionType(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;
PermissionType other = (PermissionType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_security_service_type_PermissionType.java
|
678 |
public class TransportGetWarmersAction extends TransportClusterInfoAction<GetWarmersRequest, GetWarmersResponse> {
@Inject
public TransportGetWarmersAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool) {
super(settings, transportService, clusterService, threadPool);
}
@Override
protected String transportAction() {
return GetWarmersAction.NAME;
}
@Override
protected GetWarmersRequest newRequest() {
return new GetWarmersRequest();
}
@Override
protected GetWarmersResponse newResponse() {
return new GetWarmersResponse();
}
@Override
protected void doMasterOperation(final GetWarmersRequest request, final ClusterState state, final ActionListener<GetWarmersResponse> listener) throws ElasticsearchException {
ImmutableOpenMap<String, ImmutableList<IndexWarmersMetaData.Entry>> result = state.metaData().findWarmers(
request.indices(), request.types(), request.warmers()
);
listener.onResponse(new GetWarmersResponse(result));
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_admin_indices_warmer_get_TransportGetWarmersAction.java
|
509 |
public class OEntityManager {
private static Map<String, OEntityManager> databaseInstances = new HashMap<String, OEntityManager>();
private OEntityManagerClassHandler classHandler = new OEntityManagerClassHandler();
protected OEntityManager() {
OLogManager.instance().debug(this, "Registering entity manager");
classHandler.registerEntityClass(OUser.class);
classHandler.registerEntityClass(ORole.class);
}
public static synchronized OEntityManager getEntityManagerByDatabaseURL(final String iURL) {
OEntityManager instance = databaseInstances.get(iURL);
if (instance == null) {
instance = new OEntityManager();
databaseInstances.put(iURL, instance);
}
return instance;
}
/**
* Create a POJO by its class name.
*
* @see #registerEntityClasses(String)
*/
public synchronized Object createPojo(final String iClassName) throws OConfigurationException {
if (iClassName == null)
throw new IllegalArgumentException("Cannot create the object: class name is empty");
final Class<?> entityClass = classHandler.getEntityClass(iClassName);
try {
if (entityClass != null)
return createInstance(entityClass);
} catch (Exception e) {
throw new OConfigurationException("Error while creating new pojo of class '" + iClassName + "'", e);
}
try {
// TRY TO INSTANTIATE THE CLASS DIRECTLY BY ITS NAME
return createInstance(Class.forName(iClassName));
} catch (Exception e) {
throw new OConfigurationException("The class '" + iClassName
+ "' was not found between the entity classes. Ensure registerEntityClasses(package) has been called first.", e);
}
}
/**
* Returns the Java class by its name
*
* @param iClassName
* Simple class name without the package
* @return Returns the Java class by its name
*/
public synchronized Class<?> getEntityClass(final String iClassName) {
return classHandler.getEntityClass(iClassName);
}
public synchronized void deregisterEntityClass(final Class<?> iClass) {
classHandler.deregisterEntityClass(iClass);
}
public synchronized void deregisterEntityClasses(final String iPackageName) {
deregisterEntityClasses(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 deregisterEntityClasses(final String iPackageName, final ClassLoader iClassLoader) {
OLogManager.instance().debug(this, "Discovering entity classes 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) {
deregisterEntityClass(c);
}
if (OLogManager.instance().isDebugEnabled()) {
for (Entry<String, Class<?>> entry : classHandler.getClassesEntrySet()) {
OLogManager.instance().debug(this, "Unloaded entity class '%s' from: %s", entry.getKey(), entry.getValue());
}
}
}
public synchronized void registerEntityClass(final Class<?> iClass) {
classHandler.registerEntityClass(iClass);
}
/**
* Registers provided classes
*
* @param iClassNames
* to be registered
*/
public synchronized void registerEntityClasses(final Collection<String> iClassNames) {
registerEntityClasses(iClassNames, Thread.currentThread().getContextClassLoader());
}
/**
* Registers provided classes
*
* @param iClassNames
* to be registered
* @param iClassLoader
*/
public synchronized void registerEntityClasses(final Collection<String> iClassNames, final ClassLoader iClassLoader) {
OLogManager.instance().debug(this, "Discovering entity classes for class names: %s", iClassNames);
try {
registerEntityClasses(OReflectionHelper.getClassesFor(iClassNames, iClassLoader));
} catch (ClassNotFoundException e) {
throw new OException(e);
}
}
/**
* 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 registerEntityClasses(final String iPackageName) {
registerEntityClasses(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
* @param iClassLoader
*/
public synchronized void registerEntityClasses(final String iPackageName, final ClassLoader iClassLoader) {
OLogManager.instance().debug(this, "Discovering entity classes inside package: %s", iPackageName);
try {
registerEntityClasses(OReflectionHelper.getClassesFor(iPackageName, iClassLoader));
} catch (ClassNotFoundException e) {
throw new OException(e);
}
}
protected synchronized void registerEntityClasses(final List<Class<?>> classes) {
for (Class<?> c : classes) {
if (!classHandler.containsEntityClass(c)) {
if (c.isAnonymousClass()) {
OLogManager.instance().debug(this, "Skip registration of anonymous class '%s'.", c.getName());
continue;
}
classHandler.registerEntityClass(c);
}
}
if (OLogManager.instance().isDebugEnabled()) {
for (Entry<String, Class<?>> entry : classHandler.getClassesEntrySet()) {
OLogManager.instance().debug(this, "Loaded entity class '%s' from: %s", entry.getKey(), entry.getValue());
}
}
}
/**
* Sets the received handler as default and merges the classes all together.
*
* @param iClassHandler
*/
public synchronized void setClassHandler(final OEntityManagerClassHandler iClassHandler) {
for (Entry<String, Class<?>> entry : classHandler.getClassesEntrySet()) {
iClassHandler.registerEntityClass(entry.getValue());
}
this.classHandler = iClassHandler;
}
public synchronized Collection<Class<?>> getRegisteredEntities() {
return classHandler.getRegisteredEntities();
}
protected Object createInstance(final Class<?> iClass) throws InstantiationException, IllegalAccessException,
InvocationTargetException {
return classHandler.createInstance(iClass);
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_entity_OEntityManager.java
|
630 |
public static enum Stage {
NONE((byte) 0),
INDEX((byte) 1),
TRANSLOG((byte) 2),
FINALIZE((byte) 3),
DONE((byte) 4),
FAILURE((byte) 5);
private final byte value;
Stage(byte value) {
this.value = value;
}
public byte value() {
return this.value;
}
public static Stage fromValue(byte value) {
if (value == 0) {
return Stage.NONE;
} else if (value == 1) {
return Stage.INDEX;
} else if (value == 2) {
return Stage.TRANSLOG;
} else if (value == 3) {
return Stage.FINALIZE;
} else if (value == 4) {
return Stage.DONE;
} else if (value == 5) {
return Stage.FAILURE;
}
throw new ElasticsearchIllegalArgumentException("No stage found for [" + value + "]");
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_status_GatewaySnapshotStatus.java
|
4,476 |
public class RecoverySource extends AbstractComponent {
public static class Actions {
public static final String START_RECOVERY = "index/shard/recovery/startRecovery";
}
private final TransportService transportService;
private final IndicesService indicesService;
private final RecoverySettings recoverySettings;
private final ClusterService clusterService;
private final TimeValue internalActionTimeout;
private final TimeValue internalActionLongTimeout;
@Inject
public RecoverySource(Settings settings, TransportService transportService, IndicesService indicesService,
RecoverySettings recoverySettings, ClusterService clusterService) {
super(settings);
this.transportService = transportService;
this.indicesService = indicesService;
this.clusterService = clusterService;
this.recoverySettings = recoverySettings;
transportService.registerHandler(Actions.START_RECOVERY, new StartRecoveryTransportRequestHandler());
this.internalActionTimeout = componentSettings.getAsTime("internal_action_timeout", TimeValue.timeValueMinutes(15));
this.internalActionLongTimeout = new TimeValue(internalActionTimeout.millis() * 2);
}
private RecoveryResponse recover(final StartRecoveryRequest request) {
final InternalIndexShard shard = (InternalIndexShard) indicesService.indexServiceSafe(request.shardId().index().name()).shardSafe(request.shardId().id());
// verify that our (the source) shard state is marking the shard to be in recovery mode as well, otherwise
// the index operations will not be routed to it properly
RoutingNode node = clusterService.state().readOnlyRoutingNodes().node(request.targetNode().id());
if (node == null) {
throw new DelayRecoveryException("source node does not have the node [" + request.targetNode() + "] in its state yet..");
}
ShardRouting targetShardRouting = null;
for (ShardRouting shardRouting : node) {
if (shardRouting.shardId().equals(request.shardId())) {
targetShardRouting = shardRouting;
break;
}
}
if (targetShardRouting == null) {
throw new DelayRecoveryException("source node does not have the shard listed in its state as allocated on the node");
}
if (!targetShardRouting.initializing()) {
throw new DelayRecoveryException("source node has the state of the target shard to be [" + targetShardRouting.state() + "], expecting to be [initializing]");
}
logger.trace("[{}][{}] starting recovery to {}, mark_as_relocated {}", request.shardId().index().name(), request.shardId().id(), request.targetNode(), request.markAsRelocated());
final RecoveryResponse response = new RecoveryResponse();
shard.recover(new Engine.RecoveryHandler() {
@Override
public void phase1(final SnapshotIndexCommit snapshot) throws ElasticsearchException {
long totalSize = 0;
long existingTotalSize = 0;
try {
StopWatch stopWatch = new StopWatch().start();
for (String name : snapshot.getFiles()) {
StoreFileMetaData md = shard.store().metaData(name);
boolean useExisting = false;
if (request.existingFiles().containsKey(name)) {
// we don't compute checksum for segments, so always recover them
if (!name.startsWith("segments") && md.isSame(request.existingFiles().get(name))) {
response.phase1ExistingFileNames.add(name);
response.phase1ExistingFileSizes.add(md.length());
existingTotalSize += md.length();
useExisting = true;
if (logger.isTraceEnabled()) {
logger.trace("[{}][{}] recovery [phase1] to {}: not recovering [{}], exists in local store and has checksum [{}], size [{}]", request.shardId().index().name(), request.shardId().id(), request.targetNode(), name, md.checksum(), md.length());
}
}
}
if (!useExisting) {
if (request.existingFiles().containsKey(name)) {
logger.trace("[{}][{}] recovery [phase1] to {}: recovering [{}], exists in local store, but is different: remote [{}], local [{}]", request.shardId().index().name(), request.shardId().id(), request.targetNode(), name, request.existingFiles().get(name), md);
} else {
logger.trace("[{}][{}] recovery [phase1] to {}: recovering [{}], does not exists in remote", request.shardId().index().name(), request.shardId().id(), request.targetNode(), name);
}
response.phase1FileNames.add(name);
response.phase1FileSizes.add(md.length());
}
totalSize += md.length();
}
response.phase1TotalSize = totalSize;
response.phase1ExistingTotalSize = existingTotalSize;
logger.trace("[{}][{}] recovery [phase1] to {}: recovering_files [{}] with total_size [{}], reusing_files [{}] with total_size [{}]", request.shardId().index().name(), request.shardId().id(), request.targetNode(), response.phase1FileNames.size(), new ByteSizeValue(totalSize), response.phase1ExistingFileNames.size(), new ByteSizeValue(existingTotalSize));
RecoveryFilesInfoRequest recoveryInfoFilesRequest = new RecoveryFilesInfoRequest(request.recoveryId(), request.shardId(), response.phase1FileNames, response.phase1FileSizes,
response.phase1ExistingFileNames, response.phase1ExistingFileSizes, response.phase1TotalSize, response.phase1ExistingTotalSize);
transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.FILES_INFO, recoveryInfoFilesRequest, TransportRequestOptions.options().withTimeout(internalActionTimeout), EmptyTransportResponseHandler.INSTANCE_SAME).txGet();
final CountDownLatch latch = new CountDownLatch(response.phase1FileNames.size());
final AtomicReference<Throwable> lastException = new AtomicReference<Throwable>();
int fileIndex = 0;
for (final String name : response.phase1FileNames) {
ThreadPoolExecutor pool;
long fileSize = response.phase1FileSizes.get(fileIndex);
if (fileSize > recoverySettings.SMALL_FILE_CUTOFF_BYTES) {
pool = recoverySettings.concurrentStreamPool();
} else {
pool = recoverySettings.concurrentSmallFileStreamPool();
}
pool.execute(new Runnable() {
@Override
public void run() {
IndexInput indexInput = null;
try {
final int BUFFER_SIZE = (int) recoverySettings.fileChunkSize().bytes();
byte[] buf = new byte[BUFFER_SIZE];
StoreFileMetaData md = shard.store().metaData(name);
// TODO: maybe use IOContext.READONCE?
indexInput = shard.store().openInputRaw(name, IOContext.READ);
boolean shouldCompressRequest = recoverySettings.compress();
if (CompressorFactory.isCompressed(indexInput)) {
shouldCompressRequest = false;
}
long len = indexInput.length();
long readCount = 0;
while (readCount < len) {
if (shard.state() == IndexShardState.CLOSED) { // check if the shard got closed on us
throw new IndexShardClosedException(shard.shardId());
}
int toRead = readCount + BUFFER_SIZE > len ? (int) (len - readCount) : BUFFER_SIZE;
long position = indexInput.getFilePointer();
if (recoverySettings.rateLimiter() != null) {
recoverySettings.rateLimiter().pause(toRead);
}
indexInput.readBytes(buf, 0, toRead, false);
BytesArray content = new BytesArray(buf, 0, toRead);
transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.FILE_CHUNK, new RecoveryFileChunkRequest(request.recoveryId(), request.shardId(), name, position, len, md.checksum(), content),
TransportRequestOptions.options().withCompress(shouldCompressRequest).withType(TransportRequestOptions.Type.RECOVERY).withTimeout(internalActionTimeout), EmptyTransportResponseHandler.INSTANCE_SAME).txGet();
readCount += toRead;
}
} catch (Throwable e) {
lastException.set(e);
} finally {
IOUtils.closeWhileHandlingException(indexInput);
latch.countDown();
}
}
});
fileIndex++;
}
latch.await();
if (lastException.get() != null) {
throw lastException.get();
}
// now, set the clean files request
Set<String> snapshotFiles = Sets.newHashSet(snapshot.getFiles());
transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.CLEAN_FILES, new RecoveryCleanFilesRequest(request.recoveryId(), shard.shardId(), snapshotFiles), TransportRequestOptions.options().withTimeout(internalActionTimeout), EmptyTransportResponseHandler.INSTANCE_SAME).txGet();
stopWatch.stop();
logger.trace("[{}][{}] recovery [phase1] to {}: took [{}]", request.shardId().index().name(), request.shardId().id(), request.targetNode(), stopWatch.totalTime());
response.phase1Time = stopWatch.totalTime().millis();
} catch (Throwable e) {
throw new RecoverFilesRecoveryException(request.shardId(), response.phase1FileNames.size(), new ByteSizeValue(totalSize), e);
}
}
@Override
public void phase2(Translog.Snapshot snapshot) throws ElasticsearchException {
if (shard.state() == IndexShardState.CLOSED) {
throw new IndexShardClosedException(request.shardId());
}
logger.trace("[{}][{}] recovery [phase2] to {}: start", request.shardId().index().name(), request.shardId().id(), request.targetNode());
StopWatch stopWatch = new StopWatch().start();
transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.PREPARE_TRANSLOG, new RecoveryPrepareForTranslogOperationsRequest(request.recoveryId(), request.shardId()), TransportRequestOptions.options().withTimeout(internalActionTimeout), EmptyTransportResponseHandler.INSTANCE_SAME).txGet();
stopWatch.stop();
response.startTime = stopWatch.totalTime().millis();
logger.trace("[{}][{}] recovery [phase2] to {}: start took [{}]", request.shardId().index().name(), request.shardId().id(), request.targetNode(), stopWatch.totalTime());
logger.trace("[{}][{}] recovery [phase2] to {}: sending transaction log operations", request.shardId().index().name(), request.shardId().id(), request.targetNode());
stopWatch = new StopWatch().start();
int totalOperations = sendSnapshot(snapshot);
stopWatch.stop();
logger.trace("[{}][{}] recovery [phase2] to {}: took [{}]", request.shardId().index().name(), request.shardId().id(), request.targetNode(), stopWatch.totalTime());
response.phase2Time = stopWatch.totalTime().millis();
response.phase2Operations = totalOperations;
}
@Override
public void phase3(Translog.Snapshot snapshot) throws ElasticsearchException {
if (shard.state() == IndexShardState.CLOSED) {
throw new IndexShardClosedException(request.shardId());
}
logger.trace("[{}][{}] recovery [phase3] to {}: sending transaction log operations", request.shardId().index().name(), request.shardId().id(), request.targetNode());
StopWatch stopWatch = new StopWatch().start();
int totalOperations = sendSnapshot(snapshot);
transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.FINALIZE, new RecoveryFinalizeRecoveryRequest(request.recoveryId(), request.shardId()), TransportRequestOptions.options().withTimeout(internalActionLongTimeout), EmptyTransportResponseHandler.INSTANCE_SAME).txGet();
if (request.markAsRelocated()) {
// TODO what happens if the recovery process fails afterwards, we need to mark this back to started
try {
shard.relocated("to " + request.targetNode());
} catch (IllegalIndexShardStateException e) {
// we can ignore this exception since, on the other node, when it moved to phase3
// it will also send shard started, which might cause the index shard we work against
// to move be closed by the time we get to the the relocated method
}
}
stopWatch.stop();
logger.trace("[{}][{}] recovery [phase3] to {}: took [{}]", request.shardId().index().name(), request.shardId().id(), request.targetNode(), stopWatch.totalTime());
response.phase3Time = stopWatch.totalTime().millis();
response.phase3Operations = totalOperations;
}
private int sendSnapshot(Translog.Snapshot snapshot) throws ElasticsearchException {
int ops = 0;
long size = 0;
int totalOperations = 0;
List<Translog.Operation> operations = Lists.newArrayList();
while (snapshot.hasNext()) {
if (shard.state() == IndexShardState.CLOSED) {
throw new IndexShardClosedException(request.shardId());
}
Translog.Operation operation = snapshot.next();
operations.add(operation);
ops += 1;
size += operation.estimateSize();
totalOperations++;
if (ops >= recoverySettings.translogOps() || size >= recoverySettings.translogSize().bytes()) {
// don't throttle translog, since we lock for phase3 indexing, so we need to move it as
// fast as possible. Note, sine we index docs to replicas while the index files are recovered
// the lock can potentially be removed, in which case, it might make sense to re-enable
// throttling in this phase
// if (recoverySettings.rateLimiter() != null) {
// recoverySettings.rateLimiter().pause(size);
// }
RecoveryTranslogOperationsRequest translogOperationsRequest = new RecoveryTranslogOperationsRequest(request.recoveryId(), request.shardId(), operations);
transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.TRANSLOG_OPS, translogOperationsRequest, TransportRequestOptions.options().withCompress(recoverySettings.compress()).withType(TransportRequestOptions.Type.RECOVERY).withTimeout(internalActionLongTimeout), EmptyTransportResponseHandler.INSTANCE_SAME).txGet();
ops = 0;
size = 0;
operations.clear();
}
}
// send the leftover
if (!operations.isEmpty()) {
RecoveryTranslogOperationsRequest translogOperationsRequest = new RecoveryTranslogOperationsRequest(request.recoveryId(), request.shardId(), operations);
transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.TRANSLOG_OPS, translogOperationsRequest, TransportRequestOptions.options().withCompress(recoverySettings.compress()).withType(TransportRequestOptions.Type.RECOVERY).withTimeout(internalActionLongTimeout), EmptyTransportResponseHandler.INSTANCE_SAME).txGet();
}
return totalOperations;
}
});
return response;
}
class StartRecoveryTransportRequestHandler extends BaseTransportRequestHandler<StartRecoveryRequest> {
@Override
public StartRecoveryRequest newInstance() {
return new StartRecoveryRequest();
}
@Override
public String executor() {
return ThreadPool.Names.GENERIC;
}
@Override
public void messageReceived(final StartRecoveryRequest request, final TransportChannel channel) throws Exception {
RecoveryResponse response = recover(request);
channel.sendResponse(response);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_indices_recovery_RecoverySource.java
|
1,021 |
class TransportHandler extends BaseTransportRequestHandler<Request> {
@Override
public Request newInstance() {
return newRequest();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void messageReceived(Request request, final TransportChannel channel) throws Exception {
// no need to have a threaded listener since we just send back a response
request.listenerThreaded(false);
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response result) {
try {
channel.sendResponse(result);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response for get", e1);
}
}
});
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_single_instance_TransportInstanceSingleOperationAction.java
|
450 |
public class PropertyType {
public static class AdminPresentation {
public static final String FRIENDLYNAME = "friendlyName";
public static final String SECURITYLEVEL = "securityLevel";
public static final String ORDER = "order";
public static final String GRIDORDER = "gridOrder";
public static final String VISIBILITY = "visibility";
public static final String FIELDTYPE = "fieldType";
public static final String GROUP = "group";
public static final String GROUPORDER = "groupOrder";
public static final String GROUPCOLLAPSED = "groupCollapsed";
public static final String TAB = "tab";
public static final String TABORDER = "tabOrder";
public static final String LARGEENTRY = "largeEntry";
public static final String PROMINENT = "prominent";
public static final String COLUMNWIDTH = "columnWidth";
public static final String BROADLEAFENUMERATION = "broadleafEnumeration";
public static final String REQUIREDOVERRIDE = "requiredOverride";
public static final String EXCLUDED = "excluded";
public static final String TOOLTIP = "tooltip";
public static final String HELPTEXT = "helpText";
public static final String HINT = "hint";
public static final String SHOWIFPROPERTY = "showIfProperty";
public static final String CURRENCYCODEFIELD = "currencyCodeField";
public static final String RULEIDENTIFIER = "ruleIdentifier";
public static final String READONLY = "readOnly";
public static final String VALIDATIONCONFIGURATIONS = "validationConfigurations";
}
public static class AdminPresentationToOneLookup {
public static final String LOOKUPDISPLAYPROPERTY = "lookupDisplayProperty";
public static final String USESERVERSIDEINSPECTIONCACHE = "useServerSideInspectionCache";
public static final String LOOKUPTYPE = "lookupType";
public static final String CUSTOMCRITERIA = "customCriteria";
public static final String FORCEPOPULATECHILDPROPERTIES = "forcePopulateChildProperties";
}
public static class AdminPresentationDataDrivenEnumeration {
public static final String OPTIONLISTENTITY = "optionListEntity";
public static final String OPTIONVALUEFIELDNAME = "optionValueFieldName";
public static final String OPTIONDISPLAYFIELDNAME = "optionDisplayFieldName";
public static final String OPTIONCANEDITVALUES = "optionCanEditValues";
public static final String OPTIONFILTERPARAMS = "optionFilterParams";
}
public static class AdminPresentationAdornedTargetCollection {
public static final String FRIENDLYNAME = "friendlyName";
public static final String SECURITYLEVEL = "securityLevel";
public static final String EXCLUDED = "excluded";
public static final String SHOWIFPROPERTY = "showIfProperty";
public static final String READONLY = "readOnly";
public static final String USESERVERSIDEINSPECTIONCACHE = "useServerSideInspectionCache";
public static final String PARENTOBJECTPROPERTY = "parentObjectProperty";
public static final String PARENTOBJECTIDPROPERTY = "parentObjectIdProperty";
public static final String TARGETOBJECTPROPERTY = "targetObjectProperty";
public static final String MAINTAINEDADORNEDTARGETFIELDS = "maintainedAdornedTargetFields";
public static final String GRIDVISIBLEFIELDS = "gridVisibleFields";
public static final String TARGETOBJECTIDPROPERTY = "targetObjectIdProperty";
public static final String JOINENTITYCLASS = "joinEntityClass";
public static final String SORTPROPERTY = "sortProperty";
public static final String SORTASCENDING = "sortAscending";
public static final String IGNOREADORNEDPROPERTIES = "ignoreAdornedProperties";
public static final String ORDER = "order";
public static final String TAB = "tab";
public static final String TABORDER = "tabOrder";
public static final String CUSTOMCRITERIA = "customCriteria";
public static final String CURRENCYCODEFIELD = "currencyCodeField";
public static final String OPERATIONTYPES = "operationTypes";
}
public static class AdminPresentationCollection {
public static final String FRIENDLYNAME = "friendlyName";
public static final String SECURITYLEVEL = "securityLevel";
public static final String EXCLUDED = "excluded";
public static final String READONLY = "readOnly";
public static final String USESERVERSIDEINSPECTIONCACHE = "useServerSideInspectionCache";
public static final String ADDTYPE = "addType";
public static final String MANYTOFIELD = "manyToField";
public static final String ORDER = "order";
public static final String TAB = "tab";
public static final String TABORDER = "tabOrder";
public static final String CUSTOMCRITERIA = "customCriteria";
public static final String OPERATIONTYPES = "operationTypes";
public static final String SHOWIFPROPERTY = "showIfProperty";
public static final String CURRENCYCODEFIELD = "currencyCodeField";
}
public static class AdminPresentationMap {
public static final String FRIENDLYNAME = "friendlyName";
public static final String SECURITYLEVEL = "securityLevel";
public static final String EXCLUDED = "excluded";
public static final String READONLY = "readOnly";
public static final String USESERVERSIDEINSPECTIONCACHE = "useServerSideInspectionCache";
public static final String ORDER = "order";
public static final String TAB = "tab";
public static final String TABORDER = "tabOrder";
public static final String KEYCLASS = "keyClass";
public static final String MAPKEYVALUEPROPERTY = "mapKeyValueProperty";
public static final String KEYPROPERTYFRIENDLYNAME = "keyPropertyFriendlyName";
public static final String VALUECLASS = "valueClass";
public static final String DELETEENTITYUPONREMOVE = "deleteEntityUponRemove";
public static final String VALUEPROPERTYFRIENDLYNAME = "valuePropertyFriendlyName";
public static final String ISSIMPLEVALUE = "isSimpleValue";
public static final String MEDIAFIELD = "mediaField";
public static final String KEYS = "keys";
public static final String FORCEFREEFORMKEYS = "forceFreeFormKeys";
public static final String MANYTOFIELD = "manyToField";
public static final String MAPKEYOPTIONENTITYCLASS = "mapKeyOptionEntityClass";
public static final String MAPKEYOPTIONENTITYDISPLAYFIELD = "mapKeyOptionEntityDisplayField";
public static final String MAPKEYOPTIONENTITYVALUEFIELD = "mapKeyOptionEntityValueField";
public static final String CUSTOMCRITERIA = "customCriteria";
public static final String OPERATIONTYPES = "operationTypes";
public static final String SHOWIFPROPERTY = "showIfProperty";
public static final String CURRENCYCODEFIELD = "currencyCodeField";
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_presentation_override_PropertyType.java
|
230 |
PostingsHighlighter highlighter = new PostingsHighlighter() {
@Override
protected PassageFormatter getFormatter(String field) {
return new DefaultPassageFormatter("<b>", "</b>", "... ", true);
}
};
| 0true
|
src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java
|
1,812 |
public abstract class AbstractMoneyFieldPersistenceProvider extends FieldPersistenceProviderAdapter {
@Override
public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException {
if (!canHandleExtraction(extractValueRequest, property)) {
return FieldProviderResponse.NOT_HANDLED;
}
if (extractValueRequest.getRequestedValue() == null) {
return FieldProviderResponse.NOT_HANDLED;
}
property.setValue(formatValue((BigDecimal)extractValueRequest.getRequestedValue(), extractValueRequest, property));
property.setDisplayValue(formatDisplayValue((BigDecimal)extractValueRequest.getRequestedValue(), extractValueRequest, property));
return FieldProviderResponse.HANDLED_BREAK;
}
protected String formatValue(BigDecimal value, ExtractValueRequest extractValueRequest, Property property) {
NumberFormat format = NumberFormat.getInstance();
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(2);
format.setGroupingUsed(false);
return format.format(value);
}
protected String formatDisplayValue(BigDecimal value, ExtractValueRequest extractValueRequest, Property property) {
Locale locale = getLocale(extractValueRequest, property);
Currency currency = getCurrency(extractValueRequest, property);
NumberFormat format = NumberFormat.getCurrencyInstance(locale);
format.setCurrency(currency);
return format.format(value);
}
protected abstract boolean canHandleExtraction(ExtractValueRequest extractValueRequest, Property property);
protected abstract Locale getLocale(ExtractValueRequest extractValueRequest, Property property);
protected abstract Currency getCurrency(ExtractValueRequest extractValueRequest, Property property);
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_provider_AbstractMoneyFieldPersistenceProvider.java
|
126 |
class FixMultilineStringIndentationProposal
extends CorrectionProposal {
public static void addFixMultilineStringIndentation(
Collection<ICompletionProposal> proposals,
IFile file, Tree.CompilationUnit cu, Node node) {
if (node instanceof Tree.StringLiteral) {
TextFileChange change =
new TextFileChange("Fix Multiline String", file);
IDocument doc = EditorUtil.getDocument(change);
Tree.StringLiteral literal = (Tree.StringLiteral) node;
int offset = literal.getStartIndex();
int length = literal.getStopIndex() -
literal.getStartIndex() + 1;
Token token = literal.getToken();
int indentation = token.getCharPositionInLine() +
getStartQuoteLength(token.getType());
String text = getFixedText(token.getText(), indentation, doc);
if (text!=null) {
change.setEdit(new ReplaceEdit(offset, length, text));
FixMultilineStringIndentationProposal proposal =
new FixMultilineStringIndentationProposal(change);
if (!proposals.contains(proposal)) {
proposals.add(proposal);
}
}
}
}
private static String getFixedText(String text,
int indentation, IDocument doc) {
StringBuilder result = new StringBuilder();
for (String line: text.split("\n|\r\n?")) {
if (result.length() == 0) {
//the first line of the string
result.append(line);
}
else {
for (int i = 0; i<indentation; i++) {
//fix the indentation
result.append(" ");
if (line.startsWith(" ")) {
line = line.substring(1);
}
}
//the non-whitespace content
result.append(line);
}
result.append(Indents.getDefaultLineDelimiter(doc));
}
result.setLength(result.length()-1);
return result.toString();
}
private static int getStartQuoteLength(int type) {
int startQuoteLength = -1;
if (type == STRING_LITERAL ||
type== ASTRING_LITERAL ||
type == STRING_START) {
startQuoteLength = 1;
}
else if (type == STRING_MID ||
type == STRING_END) {
startQuoteLength = 2;
}
else if (type == VERBATIM_STRING ||
type == AVERBATIM_STRING) {
startQuoteLength = 3;
}
return startQuoteLength;
}
private FixMultilineStringIndentationProposal(TextFileChange change) {
super("Fix multiline string indentation", change, null);
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ChangeMultilineStringIndentionProposal.java
|
117 |
public static final class ClientHelper {
private ClientHelper() {
}
public static void cleanResources(HazelcastClient client) {
closeSockets(client);
tryStopThreads(client);
tryShutdown(client);
}
private static void closeSockets(HazelcastClient client) {
final ClientConnectionManager connectionManager = client.getConnectionManager();
if (connectionManager != null) {
try {
connectionManager.shutdown();
} catch (Throwable ignored) {
}
}
}
private static void tryShutdown(HazelcastClient client) {
if (client == null) {
return;
}
try {
client.doShutdown();
} catch (Throwable ignored) {
}
}
public static void tryStopThreads(HazelcastClient client) {
if (client == null) {
return;
}
try {
client.getThreadGroup().interrupt();
} catch (Throwable ignored) {
}
}
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_ClientOutOfMemoryHandler.java
|
270 |
public class EmailInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String emailType;
private String emailTemplate;
private String subject;
private String fromAddress;
private String messageBody;
private List<Attachment> attachments = new ArrayList<Attachment>();
private String sendEmailReliableAsync;
private String sendAsyncPriority;
/**
* @return the emailType
*/
public String getEmailType() {
return emailType;
}
/**
* @param emailType the emailType to set
*/
public void setEmailType(String emailType) {
this.emailType = emailType;
}
/**
* @return the emailTemplate
*/
public String getEmailTemplate() {
return emailTemplate;
}
/**
* @param emailTemplate the emailTemplate to set
*/
public void setEmailTemplate(String emailTemplate) {
this.emailTemplate = emailTemplate;
}
/**
* @return the subject
*/
public String getSubject() {
return subject;
}
/**
* @param subject the subject to set
*/
public void setSubject(String subject) {
this.subject = subject;
}
/**
* @return the fromAddress
*/
public String getFromAddress() {
return fromAddress;
}
/**
* @param fromAddress the fromAddress to set
*/
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
/**
* @return the sendEmailReliableAsync
*/
public String getSendEmailReliableAsync() {
return sendEmailReliableAsync;
}
/**
* @param sendEmailReliableAsync the sendEmailReliableAsync to set
*/
public void setSendEmailReliableAsync(String sendEmailReliableAsync) {
this.sendEmailReliableAsync = sendEmailReliableAsync;
}
/**
* @return the sendAsyncPriority
*/
public String getSendAsyncPriority() {
return sendAsyncPriority;
}
/**
* @param sendAsyncPriority the sendAsyncPriority to set
*/
public void setSendAsyncPriority(String sendAsyncPriority) {
this.sendAsyncPriority = sendAsyncPriority;
}
public String getMessageBody() {
return messageBody;
}
public void setMessageBody(String messageBody) {
this.messageBody = messageBody;
}
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public synchronized EmailInfo clone() {
EmailInfo info = new EmailInfo();
info.setAttachments(attachments);
info.setEmailTemplate(emailTemplate);
info.setEmailType(emailType);
info.setFromAddress(fromAddress);
info.setMessageBody(messageBody);
info.setSendAsyncPriority(sendAsyncPriority);
info.setSendEmailReliableAsync(sendEmailReliableAsync);
info.setSubject(subject);
return info;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_email_service_info_EmailInfo.java
|
415 |
public class GetSnapshotsResponse extends ActionResponse implements ToXContent {
private ImmutableList<SnapshotInfo> snapshots = ImmutableList.of();
GetSnapshotsResponse() {
}
GetSnapshotsResponse(ImmutableList<SnapshotInfo> snapshots) {
this.snapshots = snapshots;
}
/**
* Returns the list of snapshots
*
* @return the list of snapshots
*/
public ImmutableList<SnapshotInfo> getSnapshots() {
return snapshots;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
int size = in.readVInt();
ImmutableList.Builder<SnapshotInfo> builder = ImmutableList.builder();
for (int i = 0; i < size; i++) {
builder.add(SnapshotInfo.readSnapshotInfo(in));
}
snapshots = builder.build();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(snapshots.size());
for (SnapshotInfo snapshotInfo : snapshots) {
snapshotInfo.writeTo(out);
}
}
static final class Fields {
static final XContentBuilderString SNAPSHOTS = new XContentBuilderString("snapshots");
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startArray(Fields.SNAPSHOTS);
for (SnapshotInfo snapshotInfo : snapshots) {
snapshotInfo.toXContent(builder, params);
}
builder.endArray();
return builder;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_get_GetSnapshotsResponse.java
|
108 |
class CreateParameterProposal extends InitializerProposal {
CreateParameterProposal(String def, String desc,
Declaration dec, ProducedType type,
Image image, int offset, TextFileChange change,
int exitPos) {
super(desc, change, dec, type,
computeSelection(offset,def),
image, exitPos, null);
}
private static void addCreateParameterProposal(Collection<ICompletionProposal> proposals,
String def, String desc, Image image, Declaration dec, PhasedUnit unit,
Tree.Declaration decNode, Tree.ParameterList paramList,
ProducedType returnType, Set<Declaration> imports, Node node) {
IFile file = getFile(unit);
TextFileChange change =
new TextFileChange("Add Parameter", file);
change.setEdit(new MultiTextEdit());
IDocument doc = EditorUtil.getDocument(change);
int offset = paramList.getStopIndex();
int il = applyImports(change, imports,
unit.getCompilationUnit(), doc);
change.addEdit(new InsertEdit(offset, def));
int exitPos = node.getStopIndex()+1;
proposals.add(new CreateParameterProposal(def,
"Add " + desc + " to '" + dec.getName() + "'",
dec, returnType, image, offset+il, change, exitPos));
}
private static void addCreateParameterAndAttributeProposal(Collection<ICompletionProposal> proposals,
String pdef, String adef, String desc, Image image, Declaration dec, PhasedUnit unit,
Tree.Declaration decNode, Tree.ParameterList paramList, Tree.Body body,
ProducedType returnType, Node node) {
IFile file = getFile(unit);
TextFileChange change =
new TextFileChange("Add Attribute", file);
change.setEdit(new MultiTextEdit());
int offset = paramList.getStopIndex();
IDocument doc = EditorUtil.getDocument(change);
String indent;
String indentAfter;
int offset2;
List<Tree.Statement> statements = body.getStatements();
if (statements.isEmpty()) {
indentAfter = getDefaultLineDelimiter(doc) + getIndent(decNode, doc);
indent = indentAfter + getDefaultIndent();
offset2 = body.getStartIndex()+1;
}
else {
Tree.Statement statement = statements.get(statements.size()-1);
indent = getDefaultLineDelimiter(doc) + getIndent(statement, doc);
offset2 = statement.getStopIndex()+1;
indentAfter = "";
}
HashSet<Declaration> decs = new HashSet<Declaration>();
Tree.CompilationUnit cu = unit.getCompilationUnit();
importType(decs, returnType, cu);
int il = applyImports(change, decs, cu, doc);
change.addEdit(new InsertEdit(offset, pdef));
change.addEdit(new InsertEdit(offset2, indent+adef+indentAfter));
int exitPos = node.getStopIndex()+1;
proposals.add(new CreateParameterProposal(pdef,
"Add " + desc + " to '" + dec.getName() + "'",
dec, returnType, image, offset+il, change, exitPos));
}
static void addCreateParameterProposal(Collection<ICompletionProposal> proposals,
IProject project, ValueFunctionDefinitionGenerator dg) {
if (Character.isLowerCase(dg.getBrokenName().charAt(0))) {
Tree.Declaration decl =
findDeclarationWithBody(dg.getRootNode(), dg.getNode());
if (decl == null ||
decl.getDeclarationModel() == null ||
decl.getDeclarationModel().isActual()) {
return;
}
Tree.ParameterList paramList = getParameters(decl);
if (paramList != null) {
String def = dg.generate("", "");
//TODO: really ugly and fragile way to strip off the trailing ;
String paramDef = (paramList.getParameters().isEmpty() ? "" : ", ") +
def.substring(0, def.length() - (def.endsWith("{}")?3:1));
String paramDesc = "parameter '" + dg.getBrokenName() + "'";
for (PhasedUnit unit: getUnits(project)) {
if (unit.getUnit().equals(dg.getRootNode().getUnit())) {
addCreateParameterProposal(proposals, paramDef, paramDesc, ADD_CORR,
decl.getDeclarationModel(), unit, decl, paramList, dg.getReturnType(),
dg.getImports(), dg.getNode());
break;
}
}
}
}
}
static void addCreateParameterProposals(Tree.CompilationUnit cu, Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project, TypeChecker tc, IFile file) {
FindInvocationVisitor fav = new FindInvocationVisitor(node);
fav.visit(cu);
if (fav.result==null) return;
Tree.Primary prim = fav.result.getPrimary();
if (prim instanceof Tree.MemberOrTypeExpression) {
ProducedReference pr = ((Tree.MemberOrTypeExpression) prim).getTarget();
if (pr!=null) {
Declaration d = pr.getDeclaration();
ProducedType t=null;
String parameterName=null;
if (node instanceof Tree.Term) {
t = ((Tree.Term) node).getTypeModel();
parameterName = t.getDeclaration().getName();
if (parameterName!=null) {
parameterName =
Character.toLowerCase(parameterName.charAt(0)) +
parameterName.substring(1)
.replace("?", "").replace("[]", "");
if ("string".equals(parameterName)) {
parameterName = "text";
}
}
}
else if (node instanceof Tree.SpecifiedArgument) {
Tree.SpecifiedArgument sa = (Tree.SpecifiedArgument) node;
Tree.SpecifierExpression se = sa.getSpecifierExpression();
if (se!=null && se.getExpression()!=null) {
t = se.getExpression().getTypeModel();
}
parameterName = sa.getIdentifier().getText();
}
else if (node instanceof Tree.TypedArgument) {
Tree.TypedArgument ta = (Tree.TypedArgument) node;
t = ta.getType().getTypeModel();
parameterName = ta.getIdentifier().getText();
}
if (t!=null && parameterName!=null) {
t = node.getUnit().denotableType(t);
String defaultValue = defaultValue(prim.getUnit(), t);
String parameterType = t.getProducedTypeName();
String def = parameterType + " " + parameterName + " = " + defaultValue;
String desc = "parameter '" + parameterName +"'";
addCreateParameterProposals(proposals, project, def, desc, d, t, node);
String pdef = parameterName + " = " + defaultValue;
String adef = parameterType + " " + parameterName + ";";
String padesc = "attribute '" + parameterName +"'";
addCreateParameterAndAttributeProposals(proposals, project,
pdef, adef, padesc, d, t, node);
}
}
}
}
private static Tree.ParameterList getParameters(Tree.Declaration decNode) {
if (decNode instanceof Tree.AnyClass) {
return ((Tree.AnyClass) decNode).getParameterList();
}
else if (decNode instanceof Tree.AnyMethod){
List<Tree.ParameterList> pls = ((Tree.AnyMethod) decNode).getParameterLists();
return pls.isEmpty() ? null : pls.get(0);
}
return null;
}
private static void addCreateParameterProposals(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Declaration typeDec, ProducedType t,
Node node) {
if (typeDec!=null && typeDec instanceof Functional) {
for (PhasedUnit unit: getUnits(project)) {
if (typeDec.getUnit().equals(unit.getUnit())) {
FindDeclarationNodeVisitor fdv =
new FindDeclarationNodeVisitor(typeDec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode =
(Tree.Declaration) fdv.getDeclarationNode();
Tree.ParameterList paramList = getParameters(decNode);
if (paramList!=null) {
if (!paramList.getParameters().isEmpty()) {
def = ", " + def;
}
Set<Declaration> imports = new HashSet<Declaration>();
importType(imports, t, unit.getCompilationUnit());
addCreateParameterProposal(proposals, def, desc, ADD_CORR,
typeDec, unit, decNode, paramList, t, imports, node);
break;
}
}
}
}
}
private static void addCreateParameterAndAttributeProposals(Collection<ICompletionProposal> proposals,
IProject project, String pdef, String adef, String desc, Declaration typeDec, ProducedType t,
Node node) {
if (typeDec!=null && typeDec instanceof ClassOrInterface) {
for (PhasedUnit unit: getUnits(project)) {
if (typeDec.getUnit().equals(unit.getUnit())) {
FindDeclarationNodeVisitor fdv =
new FindDeclarationNodeVisitor(typeDec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode =
(Tree.Declaration) fdv.getDeclarationNode();
Tree.ParameterList paramList = getParameters(decNode);
Tree.Body body = getClassOrInterfaceBody(decNode);
if (body!=null && paramList!=null) {
if (!paramList.getParameters().isEmpty()) {
pdef = ", " + pdef;
}
addCreateParameterAndAttributeProposal(proposals, pdef,
adef, desc, ADD_CORR, typeDec, unit, decNode,
paramList, body, t, node);
}
}
}
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CreateParameterProposal.java
|
2,574 |
clusterService.submitStateUpdateTask("zen-disco-minimum_master_nodes_changed", Priority.URGENT, new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
final int prevMinimumMasterNode = ZenDiscovery.this.electMaster.minimumMasterNodes();
ZenDiscovery.this.electMaster.minimumMasterNodes(minimumMasterNodes);
// check if we have enough master nodes, if not, we need to move into joining the cluster again
if (!electMaster.hasEnoughMasterNodes(currentState.nodes())) {
return rejoin(currentState, "not enough master nodes on change of minimum_master_nodes from [" + prevMinimumMasterNode + "] to [" + minimumMasterNodes + "]");
}
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
sendInitialStateEventIfNeeded();
}
});
| 1no label
|
src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java
|
1,261 |
new FutureTransportResponseHandler<NodesInfoResponse>() {
@Override
public NodesInfoResponse newInstance() {
return new NodesInfoResponse();
}
}).txGet();
| 0true
|
src_main_java_org_elasticsearch_client_transport_TransportClientNodesService.java
|
4,520 |
class ApplySettings implements NodeSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
TimeValue interval = settings.getAsTime(INDICES_TTL_INTERVAL, IndicesTTLService.this.interval);
if (!interval.equals(IndicesTTLService.this.interval)) {
logger.info("updating indices.ttl.interval from [{}] to [{}]", IndicesTTLService.this.interval, interval);
IndicesTTLService.this.interval = interval;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_indices_ttl_IndicesTTLService.java
|
242 |
public class OCacheLevelTwoLocatorLocal implements OCacheLevelTwoLocator {
@Override
public OCache primaryCache(final String storageName) {
String cacheClassName = CACHE_LEVEL2_IMPL.getValueAsString();
try {
Class<?> cacheClass = findByCanonicalName(cacheClassName);
checkThatImplementsCacheInterface(cacheClass);
Constructor<?> cons = getPublicConstructorWithLimitParameter(cacheClass);
return (OCache) cons.newInstance(storageName, CACHE_LEVEL2_SIZE.getValueAsInteger());
} catch (Exception e) {
OLogManager.instance().error(this,
"Cannot initialize cache with implementation class [%s]. %s. Using default implementation [%s]", cacheClassName,
e.getMessage(), ODefaultCache.class.getCanonicalName());
}
return new ODefaultCache(null, CACHE_LEVEL2_SIZE.getValueAsInteger());
}
private void checkThatImplementsCacheInterface(final Class<?> cacheClass) {
if (!OCache.class.isAssignableFrom(cacheClass))
throw new IllegalArgumentException("Class " + cacheClass.getCanonicalName() + " doesn't implement "
+ OCache.class.getCanonicalName() + " interface");
}
private Class<?> findByCanonicalName(final String cacheClassName) {
try {
return Class.forName(cacheClassName);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Class not found", e);
}
}
private Constructor<?> getPublicConstructorWithLimitParameter(final Class<?> cacheClass) {
try {
return cacheClass.getConstructor(String.class, int.class);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Class has no public constructor with parameter of type [" + String.class + ","
+ int.class + "]", e);
}
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_cache_OCacheLevelTwoLocatorLocal.java
|
483 |
public class CleanStringException extends ServiceException {
public CleanStringException(CleanResults cleanResults) {
this.cleanResults = cleanResults;
}
protected CleanResults cleanResults;
public CleanResults getCleanResults() {
return cleanResults;
}
public void setCleanResults(CleanResults cleanResults) {
this.cleanResults = cleanResults;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_security_service_CleanStringException.java
|
74 |
public class OSharedResourceAdaptive {
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private final AtomicInteger users = new AtomicInteger(0);
private final boolean concurrent;
private final int timeout;
private final boolean ignoreThreadInterruption;
protected OSharedResourceAdaptive() {
this.concurrent = true;
this.timeout = 0;
this.ignoreThreadInterruption = false;
}
protected OSharedResourceAdaptive(final int iTimeout) {
this.concurrent = true;
this.timeout = iTimeout;
this.ignoreThreadInterruption = false;
}
protected OSharedResourceAdaptive(final boolean iConcurrent) {
this.concurrent = iConcurrent;
this.timeout = 0;
this.ignoreThreadInterruption = false;
}
protected OSharedResourceAdaptive(final boolean iConcurrent, final int iTimeout, boolean ignoreThreadInterruption) {
this.concurrent = iConcurrent;
this.timeout = iTimeout;
this.ignoreThreadInterruption = ignoreThreadInterruption;
}
protected void acquireExclusiveLock() {
if (concurrent)
if (timeout > 0) {
try {
if (lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS))
// OK
return;
} catch (InterruptedException e) {
if (ignoreThreadInterruption) {
// IGNORE THE THREAD IS INTERRUPTED: TRY TO RE-LOCK AGAIN
try {
if (lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS)) {
// OK, RESET THE INTERRUPTED STATE
Thread.currentThread().interrupt();
return;
}
} catch (InterruptedException e2) {
Thread.currentThread().interrupt();
}
}
throw new OLockException("Thread interrupted while waiting for resource of class '" + getClass() + "' with timeout="
+ timeout);
}
throw new OTimeoutException("Timeout on acquiring exclusive lock against resource of class: " + getClass()
+ " with timeout=" + timeout);
} else
lock.writeLock().lock();
}
protected boolean tryAcquireExclusiveLock() {
return !concurrent || lock.writeLock().tryLock();
}
protected void acquireSharedLock() {
if (concurrent)
if (timeout > 0) {
try {
if (lock.readLock().tryLock(timeout, TimeUnit.MILLISECONDS))
// OK
return;
} catch (InterruptedException e) {
if (ignoreThreadInterruption) {
// IGNORE THE THREAD IS INTERRUPTED: TRY TO RE-LOCK AGAIN
try {
if (lock.readLock().tryLock(timeout, TimeUnit.MILLISECONDS)) {
// OK, RESET THE INTERRUPTED STATE
Thread.currentThread().interrupt();
return;
}
} catch (InterruptedException e2) {
Thread.currentThread().interrupt();
}
}
throw new OLockException("Thread interrupted while waiting for resource of class '" + getClass() + "' with timeout="
+ timeout);
}
throw new OTimeoutException("Timeout on acquiring shared lock against resource of class : " + getClass() + " with timeout="
+ timeout);
} else
lock.readLock().lock();
}
protected boolean tryAcquireSharedLock() {
return !concurrent || lock.readLock().tryLock();
}
protected void releaseExclusiveLock() {
if (concurrent)
lock.writeLock().unlock();
}
protected void releaseSharedLock() {
if (concurrent)
lock.readLock().unlock();
}
public int getUsers() {
return users.get();
}
public int addUser() {
return users.incrementAndGet();
}
public int removeUser() {
if (users.get() < 1)
throw new IllegalStateException("Cannot remove user of the shared resource " + toString() + " because no user is using it");
return users.decrementAndGet();
}
public boolean isConcurrent() {
return concurrent;
}
/** To use in assert block. */
public boolean assertExclusiveLockHold() {
return lock.getWriteHoldCount() > 0;
}
/** To use in assert block. */
public boolean assertSharedLockHold() {
return lock.getReadHoldCount() > 0;
}
}
| 1no label
|
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceAdaptive.java
|
414 |
public class GetSnapshotsRequestBuilder extends MasterNodeOperationRequestBuilder<GetSnapshotsRequest, GetSnapshotsResponse, GetSnapshotsRequestBuilder> {
/**
* Constructs the new get snapshot request
*
* @param clusterAdminClient cluster admin client
*/
public GetSnapshotsRequestBuilder(ClusterAdminClient clusterAdminClient) {
super((InternalClusterAdminClient) clusterAdminClient, new GetSnapshotsRequest());
}
/**
* Constructs the new get snapshot request with specified repository
*
* @param clusterAdminClient cluster admin client
* @param repository repository name
*/
public GetSnapshotsRequestBuilder(ClusterAdminClient clusterAdminClient, String repository) {
super((InternalClusterAdminClient) clusterAdminClient, new GetSnapshotsRequest(repository));
}
/**
* Sets the repository name
*
* @param repository repository name
* @return this builder
*/
public GetSnapshotsRequestBuilder setRepository(String repository) {
request.repository(repository);
return this;
}
/**
* Sets list of snapshots to return
*
* @param snapshots list of snapshots
* @return this builder
*/
public GetSnapshotsRequestBuilder setSnapshots(String... snapshots) {
request.snapshots(snapshots);
return this;
}
/**
* Adds additional snapshots to the list of snapshots to return
*
* @param snapshots additional snapshots
* @return this builder
*/
public GetSnapshotsRequestBuilder addSnapshots(String... snapshots) {
request.snapshots(ObjectArrays.concat(request.snapshots(), snapshots, String.class));
return this;
}
@Override
protected void doExecute(ActionListener<GetSnapshotsResponse> listener) {
((ClusterAdminClient) client).getSnapshots(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_get_GetSnapshotsRequestBuilder.java
|
606 |
updateSettingsService.updateSettings(clusterStateUpdateRequest, new ClusterStateUpdateListener() {
@Override
public void onResponse(ClusterStateUpdateResponse response) {
listener.onResponse(new UpdateSettingsResponse(response.isAcknowledged()));
}
@Override
public void onFailure(Throwable t) {
logger.debug("failed to update settings on indices [{}]", t, request.indices());
listener.onFailure(t);
}
});
| 1no label
|
src_main_java_org_elasticsearch_action_admin_indices_settings_put_TransportUpdateSettingsAction.java
|
140 |
abstract class Striped64 extends Number {
/*
* This class maintains a lazily-initialized table of atomically
* updated variables, plus an extra "base" field. The table size
* is a power of two. Indexing uses masked per-thread hash codes.
* Nearly all declarations in this class are package-private,
* accessed directly by subclasses.
*
* Table entries are of class Cell; a variant of AtomicLong padded
* to reduce cache contention on most processors. Padding is
* overkill for most Atomics because they are usually irregularly
* scattered in memory and thus don't interfere much with each
* other. But Atomic objects residing in arrays will tend to be
* placed adjacent to each other, and so will most often share
* cache lines (with a huge negative performance impact) without
* this precaution.
*
* In part because Cells are relatively large, we avoid creating
* them until they are needed. When there is no contention, all
* updates are made to the base field. Upon first contention (a
* failed CAS on base update), the table is initialized to size 2.
* The table size is doubled upon further contention until
* reaching the nearest power of two greater than or equal to the
* number of CPUS. Table slots remain empty (null) until they are
* needed.
*
* A single spinlock ("busy") is used for initializing and
* resizing the table, as well as populating slots with new Cells.
* There is no need for a blocking lock; when the lock is not
* available, threads try other slots (or the base). During these
* retries, there is increased contention and reduced locality,
* which is still better than alternatives.
*
* Per-thread hash codes are initialized to random values.
* Contention and/or table collisions are indicated by failed
* CASes when performing an update operation (see method
* retryUpdate). Upon a collision, if the table size is less than
* the capacity, it is doubled in size unless some other thread
* holds the lock. If a hashed slot is empty, and lock is
* available, a new Cell is created. Otherwise, if the slot
* exists, a CAS is tried. Retries proceed by "double hashing",
* using a secondary hash (Marsaglia XorShift) to try to find a
* free slot.
*
* The table size is capped because, when there are more threads
* than CPUs, supposing that each thread were bound to a CPU,
* there would exist a perfect hash function mapping threads to
* slots that eliminates collisions. When we reach capacity, we
* search for this mapping by randomly varying the hash codes of
* colliding threads. Because search is random, and collisions
* only become known via CAS failures, convergence can be slow,
* and because threads are typically not bound to CPUS forever,
* may not occur at all. However, despite these limitations,
* observed contention rates are typically low in these cases.
*
* It is possible for a Cell to become unused when threads that
* once hashed to it terminate, as well as in the case where
* doubling the table causes no thread to hash to it under
* expanded mask. We do not try to detect or remove such cells,
* under the assumption that for long-running instances, observed
* contention levels will recur, so the cells will eventually be
* needed again; and for short-lived ones, it does not matter.
*/
/**
* Padded variant of AtomicLong supporting only raw accesses plus CAS.
* The value field is placed between pads, hoping that the JVM doesn't
* reorder them.
*
* JVM intrinsics note: It would be possible to use a release-only
* form of CAS here, if it were provided.
*/
static final class Cell {
volatile long p0, p1, p2, p3, p4, p5, p6;
volatile long value;
volatile long q0, q1, q2, q3, q4, q5, q6;
Cell(long x) { value = x; }
final boolean cas(long cmp, long val) {
return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val);
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long valueOffset;
static {
try {
UNSAFE = getUnsafe();
Class<?> ak = Cell.class;
valueOffset = UNSAFE.objectFieldOffset
(ak.getDeclaredField("value"));
} catch (Exception e) {
throw new Error(e);
}
}
}
/**
* Holder for the thread-local hash code. The code is initially
* random, but may be set to a different value upon collisions.
*/
static final class HashCode {
static final Random rng = new Random();
int code;
HashCode() {
int h = rng.nextInt(); // Avoid zero to allow xorShift rehash
code = (h == 0) ? 1 : h;
}
}
/**
* The corresponding ThreadLocal class
*/
static final class ThreadHashCode extends ThreadLocal<HashCode> {
public HashCode initialValue() { return new HashCode(); }
}
/**
* Static per-thread hash codes. Shared across all instances to
* reduce ThreadLocal pollution and because adjustments due to
* collisions in one table are likely to be appropriate for
* others.
*/
static final ThreadHashCode threadHashCode = new ThreadHashCode();
/** Number of CPUS, to place bound on table size */
static final int NCPU = Runtime.getRuntime().availableProcessors();
/**
* Table of cells. When non-null, size is a power of 2.
*/
transient volatile Cell[] cells;
/**
* Base value, used mainly when there is no contention, but also as
* a fallback during table initialization races. Updated via CAS.
*/
transient volatile long base;
/**
* Spinlock (locked via CAS) used when resizing and/or creating Cells.
*/
transient volatile int busy;
/**
* Package-private default constructor
*/
Striped64() {
}
/**
* CASes the base field.
*/
final boolean casBase(long cmp, long val) {
return UNSAFE.compareAndSwapLong(this, baseOffset, cmp, val);
}
/**
* CASes the busy field from 0 to 1 to acquire lock.
*/
final boolean casBusy() {
return UNSAFE.compareAndSwapInt(this, busyOffset, 0, 1);
}
/**
* Computes the function of current and new value. Subclasses
* should open-code this update function for most uses, but the
* virtualized form is needed within retryUpdate.
*
* @param currentValue the current value (of either base or a cell)
* @param newValue the argument from a user update call
* @return result of the update function
*/
abstract long fn(long currentValue, long newValue);
/**
* Handles cases of updates involving initialization, resizing,
* creating new Cells, and/or contention. See above for
* explanation. This method suffers the usual non-modularity
* problems of optimistic retry code, relying on rechecked sets of
* reads.
*
* @param x the value
* @param hc the hash code holder
* @param wasUncontended false if CAS failed before call
*/
final void retryUpdate(long x, HashCode hc, boolean wasUncontended) {
int h = hc.code;
boolean collide = false; // True if last slot nonempty
for (;;) {
Cell[] as; Cell a; int n; long v;
if ((as = cells) != null && (n = as.length) > 0) {
if ((a = as[(n - 1) & h]) == null) {
if (busy == 0) { // Try to attach new Cell
Cell r = new Cell(x); // Optimistically create
if (busy == 0 && casBusy()) {
boolean created = false;
try { // Recheck under lock
Cell[] rs; int m, j;
if ((rs = cells) != null &&
(m = rs.length) > 0 &&
rs[j = (m - 1) & h] == null) {
rs[j] = r;
created = true;
}
} finally {
busy = 0;
}
if (created)
break;
continue; // Slot is now non-empty
}
}
collide = false;
}
else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash
else if (a.cas(v = a.value, fn(v, x)))
break;
else if (n >= NCPU || cells != as)
collide = false; // At max size or stale
else if (!collide)
collide = true;
else if (busy == 0 && casBusy()) {
try {
if (cells == as) { // Expand table unless stale
Cell[] rs = new Cell[n << 1];
for (int i = 0; i < n; ++i)
rs[i] = as[i];
cells = rs;
}
} finally {
busy = 0;
}
collide = false;
continue; // Retry with expanded table
}
h ^= h << 13; // Rehash
h ^= h >>> 17;
h ^= h << 5;
}
else if (busy == 0 && cells == as && casBusy()) {
boolean init = false;
try { // Initialize table
if (cells == as) {
Cell[] rs = new Cell[2];
rs[h & 1] = new Cell(x);
cells = rs;
init = true;
}
} finally {
busy = 0;
}
if (init)
break;
}
else if (casBase(v = base, fn(v, x)))
break; // Fall back on using base
}
hc.code = h; // Record index for next time
}
/**
* Sets base and all cells to the given value.
*/
final void internalReset(long initialValue) {
Cell[] as = cells;
base = initialValue;
if (as != null) {
int n = as.length;
for (int i = 0; i < n; ++i) {
Cell a = as[i];
if (a != null)
a.value = initialValue;
}
}
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long baseOffset;
private static final long busyOffset;
static {
try {
UNSAFE = getUnsafe();
Class<?> sk = Striped64.class;
baseOffset = UNSAFE.objectFieldOffset
(sk.getDeclaredField("base"));
busyOffset = UNSAFE.objectFieldOffset
(sk.getDeclaredField("busy"));
} catch (Exception e) {
throw new Error(e);
}
}
/**
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
* Replace with a simple call to Unsafe.getUnsafe when integrating
* into a jdk.
*
* @return a sun.misc.Unsafe
*/
private static sun.misc.Unsafe getUnsafe() {
try {
return sun.misc.Unsafe.getUnsafe();
} catch (SecurityException tryReflectionInstead) {}
try {
return java.security.AccessController.doPrivileged
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
public sun.misc.Unsafe run() throws Exception {
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
for (java.lang.reflect.Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x))
return k.cast(x);
}
throw new NoSuchFieldError("the Unsafe");
}});
} catch (java.security.PrivilegedActionException e) {
throw new RuntimeException("Could not initialize intrinsics",
e.getCause());
}
}
}
| 0true
|
src_main_java_jsr166e_Striped64.java
|
595 |
public class IndicesSegmentsRequest extends BroadcastOperationRequest<IndicesSegmentsRequest> {
public IndicesSegmentsRequest() {
this(Strings.EMPTY_ARRAY);
}
public IndicesSegmentsRequest(String... indices) {
super(indices);
indicesOptions(IndicesOptions.fromOptions(false, false, true, false));
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_segments_IndicesSegmentsRequest.java
|
457 |
public class GeneratedResource extends AbstractResource implements Serializable {
private static final long serialVersionUID = 7044543270746433688L;
protected long timeGenerated;
protected String hashRepresentation;
protected final byte[] source;
protected final String description;
/**
* <b>Note: This constructor should not be explicitly used</b>
*
* To properly allow for serialization, we must provide this no-arg constructor that will
* create a "dummy" GeneratedResource. The appropriate fields will be set during deserialization.
*/
public GeneratedResource() {
this(new byte[]{}, null);
}
public GeneratedResource(byte[] source, String description) {
Assert.notNull(source);
this.source = source;
this.description = description;
timeGenerated = System.currentTimeMillis();
}
@Override
public String getFilename() {
return getDescription();
}
@Override
public long lastModified() throws IOException {
return timeGenerated;
}
public String getHashRepresentation() {
return StringUtils.isBlank(hashRepresentation) ? String.valueOf(timeGenerated) : hashRepresentation;
}
public void setHashRepresentation(String hashRepresentation) {
this.hashRepresentation = hashRepresentation;
}
@Override
public String getDescription() {
return description;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(source);
}
@Override
public int hashCode() {
return 1;
}
@Override
public boolean equals(Object res) {
if (!(res instanceof InMemoryResource)) {
return false;
}
return Arrays.equals(source, ((GeneratedResource)res).source);
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_resource_GeneratedResource.java
|
4,242 |
public class ShardTermVectorService extends AbstractIndexShardComponent {
private IndexShard indexShard;
private MapperService mapperService;
@Inject
public ShardTermVectorService(ShardId shardId, @IndexSettings Settings indexSettings, MapperService mapperService) {
super(shardId, indexSettings);
}
// sadly, to overcome cyclic dep, we need to do this and inject it ourselves...
public ShardTermVectorService setIndexShard(IndexShard indexShard) {
this.indexShard = indexShard;
return this;
}
public TermVectorResponse getTermVector(TermVectorRequest request) {
final Engine.Searcher searcher = indexShard.acquireSearcher("term_vector");
IndexReader topLevelReader = searcher.reader();
final TermVectorResponse termVectorResponse = new TermVectorResponse(request.index(), request.type(), request.id());
final Term uidTerm = new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(request.type(), request.id()));
try {
Fields topLevelFields = MultiFields.getFields(topLevelReader);
Versions.DocIdAndVersion docIdAndVersion = Versions.loadDocIdAndVersion(topLevelReader, uidTerm);
if (docIdAndVersion != null) {
Fields termVectorsByField = docIdAndVersion.context.reader().getTermVectors(docIdAndVersion.docId);
termVectorResponse.setFields(termVectorsByField, request.selectedFields(), request.getFlags(), topLevelFields);
termVectorResponse.setExists(true);
termVectorResponse.setDocVersion(docIdAndVersion.version);
} else {
termVectorResponse.setExists(false);
}
} catch (Throwable ex) {
throw new ElasticsearchException("failed to execute term vector request", ex);
} finally {
searcher.release();
}
return termVectorResponse;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_termvectors_ShardTermVectorService.java
|
220 |
public class OConstants {
public static final String ORIENT_VERSION = "1.6.2";
public static final String ORIENT_URL = "www.orientechnologies.com";
public static String getVersion() {
final StringBuilder buffer = new StringBuilder();
buffer.append(OConstants.ORIENT_VERSION);
final String buildNumber = System.getProperty("orientdb.build.number");
if (buildNumber != null) {
buffer.append(" (build ");
buffer.append(buildNumber);
buffer.append(")");
}
return buffer.toString();
}
public static String getBuildNumber() {
final String buildNumber = System.getProperty("orientdb.build.number");
if (buildNumber == null)
return null;
return buildNumber;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_OConstants.java
|
353 |
public class OScenarioThreadLocal extends ThreadLocal<RUN_MODE> {
public static OScenarioThreadLocal INSTANCE = new OScenarioThreadLocal();
public enum RUN_MODE {
DEFAULT, RUNNING_DISTRIBUTED
}
public OScenarioThreadLocal() {
set(RUN_MODE.DEFAULT);
}
@Override
public void set(final RUN_MODE value) {
super.set(value);
}
@Override
public RUN_MODE get() {
RUN_MODE result = super.get();
if (result == null)
result = RUN_MODE.DEFAULT;
return result;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_OScenarioThreadLocal.java
|
640 |
public class CollectionAddAllOperation extends CollectionBackupAwareOperation {
protected List<Data> valueList;
protected Map<Long, Data> valueMap;
public CollectionAddAllOperation() {
}
public CollectionAddAllOperation(String name, List<Data> valueList) {
super(name);
this.valueList = valueList;
}
@Override
public boolean shouldBackup() {
return valueMap != null && !valueMap.isEmpty();
}
@Override
public Operation getBackupOperation() {
return new CollectionAddAllBackupOperation(name, valueMap);
}
@Override
public int getId() {
return CollectionDataSerializerHook.COLLECTION_ADD_ALL;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
if (!hasEnoughCapacity(valueList.size())) {
response = false;
return;
}
valueMap = getOrCreateContainer().addAll(valueList);
response = !valueMap.isEmpty();
}
@Override
public void afterRun() throws Exception {
if (valueMap == null) {
return;
}
for (Data value : valueMap.values()) {
publishEvent(ItemEventType.ADDED, value);
}
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeInt(valueList.size());
for (Data value : valueList) {
value.writeData(out);
}
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
final int size = in.readInt();
valueList = new ArrayList<Data>(size);
for (int i = 0; i < size; i++) {
final Data value = new Data();
value.readData(in);
valueList.add(value);
}
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionAddAllOperation.java
|
613 |
public interface BroadleafThemeResolver {
/**
*
* @deprecated Use {@link #resolveTheme(WebRequest)} instead
*/
@Deprecated
public Theme resolveTheme(HttpServletRequest request, Site site);
public Theme resolveTheme(WebRequest request);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_web_BroadleafThemeResolver.java
|
661 |
class ShardValidateQueryRequest extends BroadcastShardOperationRequest {
private BytesReference source;
private String[] types = Strings.EMPTY_ARRAY;
private boolean explain;
private long nowInMillis;
@Nullable
private String[] filteringAliases;
ShardValidateQueryRequest() {
}
public ShardValidateQueryRequest(String index, int shardId, @Nullable String[] filteringAliases, ValidateQueryRequest request) {
super(index, shardId, request);
this.source = request.source();
this.types = request.types();
this.explain = request.explain();
this.filteringAliases = filteringAliases;
this.nowInMillis = request.nowInMillis;
}
public BytesReference source() {
return source;
}
public String[] types() {
return this.types;
}
public boolean explain() {
return this.explain;
}
public String[] filteringAliases() {
return filteringAliases;
}
public long nowInMillis() {
return this.nowInMillis;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
source = in.readBytesReference();
int typesSize = in.readVInt();
if (typesSize > 0) {
types = new String[typesSize];
for (int i = 0; i < typesSize; i++) {
types[i] = in.readString();
}
}
int aliasesSize = in.readVInt();
if (aliasesSize > 0) {
filteringAliases = new String[aliasesSize];
for (int i = 0; i < aliasesSize; i++) {
filteringAliases[i] = in.readString();
}
}
explain = in.readBoolean();
nowInMillis = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBytesReference(source);
out.writeVInt(types.length);
for (String type : types) {
out.writeString(type);
}
if (filteringAliases != null) {
out.writeVInt(filteringAliases.length);
for (String alias : filteringAliases) {
out.writeString(alias);
}
} else {
out.writeVInt(0);
}
out.writeBoolean(explain);
out.writeVLong(nowInMillis);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_validate_query_ShardValidateQueryRequest.java
|
4,939 |
public class RestClearScrollAction extends BaseRestHandler {
@Inject
public RestClearScrollAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(DELETE, "/_search/scroll", this);
controller.registerHandler(DELETE, "/_search/scroll/{scroll_id}", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
String scrollIds = request.param("scroll_id");
ClearScrollRequest clearRequest = new ClearScrollRequest();
clearRequest.setScrollIds(Arrays.asList(splitScrollIds(scrollIds)));
client.clearScroll(clearRequest, new ActionListener<ClearScrollResponse>() {
@Override
public void onResponse(ClearScrollResponse response) {
try {
XContentBuilder builder = restContentBuilder(request);
builder.startObject();
builder.endObject();
channel.sendResponse(new XContentRestResponse(request, OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new XContentThrowableRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}
public static String[] splitScrollIds(String scrollIds) {
if (scrollIds == null) {
return Strings.EMPTY_ARRAY;
}
return Strings.splitStringByCommaToArray(scrollIds);
}
}
| 1no label
|
src_main_java_org_elasticsearch_rest_action_search_RestClearScrollAction.java
|
159 |
private class MockedLogLoader implements LogLoader
{
private long version;
private long tx;
private final File baseFile;
private final ByteBuffer activeBuffer;
private final int identifier = 1;
private final LogPruneStrategy pruning;
private final Map<Long, Long> lastCommittedTxs = new HashMap<Long, Long>();
private final Map<Long, Long> timestamps = new HashMap<Long, Long>();
private final int logSize;
MockedLogLoader( LogPruneStrategy pruning )
{
this( MAX_LOG_SIZE, pruning );
}
MockedLogLoader( int logSize, LogPruneStrategy pruning )
{
this.logSize = logSize;
this.pruning = pruning;
activeBuffer = ByteBuffer.allocate( logSize*10 );
baseFile = new File( directory, "log" );
clearAndWriteHeader();
}
public int getLogSize()
{
return logSize;
}
private void clearAndWriteHeader()
{
activeBuffer.clear();
LogIoUtils.writeLogHeader( activeBuffer, version, tx );
// Because writeLogHeader does flip()
activeBuffer.limit( activeBuffer.capacity() );
activeBuffer.position( LogIoUtils.LOG_HEADER_SIZE );
}
@Override
public ReadableByteChannel getLogicalLogOrMyselfCommitted( long version, long position )
throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public long getHighestLogVersion()
{
return version;
}
@Override
public File getFileName( long version )
{
File file = new File( baseFile + ".v" + version );
return file;
}
/**
* @param date start record date.
* @return whether or not this caused a rotation to happen.
* @throws IOException
*/
public boolean addTransaction( int commandSize, long date ) throws IOException
{
InMemoryLogBuffer tempLogBuffer = new InMemoryLogBuffer();
XidImpl xid = new XidImpl( getNewGlobalId( DEFAULT_SEED, 0 ), RESOURCE_XID );
LogIoUtils.writeStart( tempLogBuffer, identifier, xid, -1, -1, date, Long.MAX_VALUE );
LogIoUtils.writeCommand( tempLogBuffer, identifier, new TestXaCommand( commandSize ) );
LogIoUtils.writeCommit( false, tempLogBuffer, identifier, ++tx, date );
LogIoUtils.writeDone( tempLogBuffer, identifier );
tempLogBuffer.read( activeBuffer );
if ( !timestamps.containsKey( version ) )
{
timestamps.put( version, date ); // The first tx timestamp for this version
}
boolean rotate = (activeBuffer.capacity() - activeBuffer.remaining()) >= logSize;
if ( rotate )
{
rotate();
}
return rotate;
}
/**
* @return the total size of the previous log (currently {@link #getHighestLogVersion()}-1
*/
public void addTransactionsUntilRotationHappens() throws IOException
{
int size = 10;
while ( true )
{
if ( addTransaction( size, System.currentTimeMillis() ) )
{
return;
}
size = Math.max( 10, (size + 7)%100 );
}
}
public void rotate() throws IOException
{
lastCommittedTxs.put( version, tx );
writeBufferToFile( activeBuffer, getFileName( version++ ) );
pruning.prune( this );
clearAndWriteHeader();
}
private void writeBufferToFile( ByteBuffer buffer, File fileName ) throws IOException
{
StoreChannel channel = null;
try
{
buffer.flip();
channel = FS.open( fileName, "rw" );
channel.write( buffer );
}
finally
{
if ( channel != null )
{
channel.close();
}
}
}
public int getTotalSizeOfAllExistingLogFiles()
{
int size = 0;
for ( long version = getHighestLogVersion()-1; version >= 0; version-- )
{
File file = getFileName( version );
if ( FS.fileExists( file ) )
{
size += FS.getFileSize( file );
}
else
{
break;
}
}
return size;
}
public int getTotalTransactionCountOfAllExistingLogFiles()
{
if ( getHighestLogVersion() == 0 )
{
return 0;
}
long upper = getHighestLogVersion()-1;
long lower = upper;
while ( lower >= 0 )
{
File file = getFileName( lower-1 );
if ( !FS.fileExists( file ) )
{
break;
}
else
{
lower--;
}
}
return (int) (getLastCommittedTxId() - getFirstCommittedTxId( lower ));
}
@Override
public Long getFirstCommittedTxId( long version )
{
return lastCommittedTxs.get( version );
}
@Override
public Long getFirstStartRecordTimestamp( long version )
{
return timestamps.get( version );
}
@Override
public long getLastCommittedTxId()
{
return tx;
}
}
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestLogPruneStrategy.java
|
119 |
public class ExtractParameterProposal implements ICompletionProposal {
private CeylonEditor editor;
public ExtractParameterProposal(CeylonEditor editor) {
this.editor = editor;
}
@Override
public Point getSelection(IDocument doc) {
return null;
}
@Override
public Image getImage() {
return CHANGE;
}
@Override
public String getDisplayString() {
return "Extract parameter";
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument doc) {
if (useLinkedMode()) {
new ExtractParameterLinkedMode(editor).start();
}
else {
new ExtractParameterRefactoringAction(editor).run();
}
}
public static void add(Collection<ICompletionProposal> proposals,
CeylonEditor editor, Node node) {
if (node instanceof Tree.BaseMemberExpression) {
Tree.Identifier id = ((Tree.BaseMemberExpression) node).getIdentifier();
if (id==null || id.getToken().getType()==CeylonLexer.AIDENTIFIER) {
return;
}
}
ExtractParameterRefactoring epr = new ExtractParameterRefactoring(editor);
if (epr.isEnabled()) {
proposals.add(new ExtractParameterProposal(editor));
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ExtractParameterProposal.java
|
659 |
constructors[LIST_SUB] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new ListSubOperation();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
|
1,084 |
public class UpdateResponse extends ActionResponse {
private String index;
private String id;
private String type;
private long version;
private boolean created;
private GetResult getResult;
public UpdateResponse() {
}
public UpdateResponse(String index, String type, String id, long version, boolean created) {
this.index = index;
this.id = id;
this.type = type;
this.version = version;
this.created = created;
}
/**
* The index the document was indexed into.
*/
public String getIndex() {
return this.index;
}
/**
* The type of the document indexed.
*/
public String getType() {
return this.type;
}
/**
* The id of the document indexed.
*/
public String getId() {
return this.id;
}
/**
* Returns the current version of the doc indexed.
*/
public long getVersion() {
return this.version;
}
public void setGetResult(GetResult getResult) {
this.getResult = getResult;
}
public GetResult getGetResult() {
return this.getResult;
}
/**
* Returns true if document was created due to an UPSERT operation
*/
public boolean isCreated() {
return this.created;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
index = in.readSharedString();
type = in.readSharedString();
id = in.readString();
version = in.readLong();
created = in.readBoolean();
if (in.readBoolean()) {
getResult = GetResult.readGetResult(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeSharedString(index);
out.writeSharedString(type);
out.writeString(id);
out.writeLong(version);
out.writeBoolean(created);
if (getResult == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
getResult.writeTo(out);
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_update_UpdateResponse.java
|
1,105 |
SINGLE_VALUED_DENSE_DATE {
public int numValues() {
return 1;
}
@Override
public long nextValue() {
// somewhere in-between 2010 and 2012
return 1000L * (40L * SECONDS_PER_YEAR + RANDOM.nextInt(2 * SECONDS_PER_YEAR));
}
},
| 0true
|
src_test_java_org_elasticsearch_benchmark_fielddata_LongFieldDataBenchmark.java
|
592 |
public interface OIndexDefinition extends OIndexCallback {
/**
* @return Names of fields which given index is used to calculate key value. Order of fields is important.
*/
public List<String> getFields();
/**
* @return Names of fields and their index modifiers (like "by value" for fields that hold <code>Map</code> values) which given
* index is used to calculate key value. Order of fields is important.
*/
public List<String> getFieldsToIndex();
/**
* @return Name of the class which this index belongs to.
*/
public String getClassName();
/**
* {@inheritDoc}
*/
public boolean equals(Object index);
/**
* {@inheritDoc}
*/
public int hashCode();
/**
* {@inheritDoc}
*/
public String toString();
/**
* Calculates key value by passed in parameters.
*
* If it is impossible to calculate key value by given parameters <code>null</code> will be returned.
*
* @param params
* Parameters from which index key will be calculated.
*
* @return Key value or null if calculation is impossible.
*/
public Object createValue(List<?> params);
/**
* Calculates key value by passed in parameters.
*
* If it is impossible to calculate key value by given parameters <code>null</code> will be returned.
*
*
* @param params
* Parameters from which index key will be calculated.
*
* @return Key value or null if calculation is impossible.
*/
public Object createValue(Object... params);
/**
* Returns amount of parameters that are used to calculate key value. It does not mean that all parameters should be supplied. It
* only means that if you provide more parameters they will be ignored and will not participate in index key calculation.
*
* @return Amount of that are used to calculate key value. Call result should be equals to {@code getTypes().length}.
*/
public int getParamCount();
/**
* Return types of values from which index key consist. In case of index that is built on single document property value single
* array that contains property type will be returned. In case of composite indexes result will contain several key types.
*
* @return Types of values from which index key consist.
*/
public OType[] getTypes();
/**
* Serializes internal index state to document.
*
* @return Document that contains internal index state.
*/
public ODocument toStream();
/**
* Deserialize internal index state from document.
*
* @param document
* Serialized index presentation.
*/
public void fromStream(ODocument document);
public String toCreateIndexDDL(String indexName, String indexType);
public boolean isAutomatic();
public OCollate getCollate();
public void setCollate(OCollate iCollate);
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_index_OIndexDefinition.java
|
954 |
private class TransportHandler extends BaseTransportRequestHandler<Request> {
@Override
public Request newInstance() {
return newRequest();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void messageReceived(final Request request, final TransportChannel channel) throws Exception {
// we just send back a response, no need to fork a listener
request.listenerThreaded(false);
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response response) {
try {
channel.sendResponse(response);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response", e1);
}
}
});
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_master_TransportMasterNodeOperationAction.java
|
560 |
public class TypedQueryBuilderTest extends TestCase {
public void testNoParameters() {
TypedQueryBuilder<String> q = new TypedQueryBuilder<String>(String.class, "test");
StringBuilder expected = new StringBuilder("SELECT test FROM " + String.class.getName() + " test");
assertEquals(q.toQueryString(), expected.toString());
}
public void testSingleParameter() {
TypedQueryBuilder<String> q = new TypedQueryBuilder<String>(String.class, "test");
q.addRestriction("test.attr", "=", "sample");
StringBuilder expected = new StringBuilder("SELECT test FROM " + String.class.getName() + " test")
.append(" WHERE (test.attr = :p0)");
assertEquals(q.toQueryString(), expected.toString());
assertEquals(q.getParamMap().get("p0"), "sample");
assertEquals(q.getParamMap().size(), 1);
}
public void testTwoParameters() {
TypedQueryBuilder<String> q = new TypedQueryBuilder<String>(String.class, "test");
q.addRestriction("test.attr", "=", "sample");
q.addRestriction("test.attr2", "=", "sample2");
StringBuilder expected = new StringBuilder("SELECT test FROM " + String.class.getName() + " test")
.append(" WHERE (test.attr = :p0) AND (test.attr2 = :p1)");
assertEquals(q.toQueryString(), expected.toString());
assertEquals(q.getParamMap().get("p0"), "sample");
assertEquals(q.getParamMap().get("p1"), "sample2");
assertEquals(q.getParamMap().size(), 2);
}
public void testThreeParameters() {
TypedQueryBuilder<String> q = new TypedQueryBuilder<String>(String.class, "test");
q.addRestriction("test.attr", "=", "sample");
q.addRestriction("test.attr2", "=", "sample2");
q.addRestriction("test.attr3", "=", "sample3");
StringBuilder expected = new StringBuilder("SELECT test FROM " + String.class.getName() + " test")
.append(" WHERE (test.attr = :p0) AND (test.attr2 = :p1) AND (test.attr3 = :p2)");
assertEquals(q.toQueryString(), expected.toString());
assertEquals(q.getParamMap().get("p0"), "sample");
assertEquals(q.getParamMap().get("p1"), "sample2");
assertEquals(q.getParamMap().get("p2"), "sample3");
assertEquals(q.getParamMap().size(), 3);
}
public void testOneNested() {
TypedQueryBuilder<String> q = new TypedQueryBuilder<String>(String.class, "test");
TQRestriction r = new TQRestriction(TQRestriction.Mode.AND)
.addChildRestriction(new TQRestriction("test.startDate", "<", "123"))
.addChildRestriction(new TQRestriction(TQRestriction.Mode.OR)
.addChildRestriction(new TQRestriction("test.endDate", "is null"))
.addChildRestriction(new TQRestriction("test.endDate", ">", "456")));
q.addRestriction("test.attr", "=", "sample");
q.addRestriction(r);
StringBuilder expected = new StringBuilder("SELECT test FROM " + String.class.getName() + " test")
.append(" WHERE (test.attr = :p0)")
.append(" AND ((test.startDate < :p1_0) AND ((test.endDate is null) OR (test.endDate > :p1_1_1)))");
assertEquals(q.toQueryString(), expected.toString());
assertEquals(q.getParamMap().get("p0"), "sample");
assertEquals(q.getParamMap().get("p1_0"), "123");
assertEquals(q.getParamMap().get("p1_1"), null);
assertEquals(q.getParamMap().get("p1_1_0"), null);
assertEquals(q.getParamMap().get("p1_1_1"), "456");
assertEquals(q.getParamMap().size(), 5);
}
public void testTwoNested() {
TypedQueryBuilder<String> q = new TypedQueryBuilder<String>(String.class, "test");
TQRestriction r = new TQRestriction(TQRestriction.Mode.AND)
.addChildRestriction(new TQRestriction("test.startDate", "<", "123"))
.addChildRestriction(new TQRestriction(TQRestriction.Mode.OR)
.addChildRestriction(new TQRestriction("test.endDate", "is null"))
.addChildRestriction(new TQRestriction("test.endDate", ">", "456")));
TQRestriction r2 = new TQRestriction(TQRestriction.Mode.OR)
.addChildRestriction(new TQRestriction("test.res1", "=", "333"))
.addChildRestriction(new TQRestriction(TQRestriction.Mode.AND)
.addChildRestriction(new TQRestriction("test.res2", "is null"))
.addChildRestriction(new TQRestriction("test.res3", ">", "456")));
q.addRestriction("test.attr", "=", "sample");
q.addRestriction(r);
q.addRestriction(r2);
System.out.println(q.toQueryString());
StringBuilder expected = new StringBuilder("SELECT test FROM " + String.class.getName() + " test")
.append(" WHERE (test.attr = :p0)")
.append(" AND ((test.startDate < :p1_0) AND ((test.endDate is null) OR (test.endDate > :p1_1_1)))")
.append(" AND ((test.res1 = :p2_0) OR ((test.res2 is null) AND (test.res3 > :p2_1_1)))");
assertEquals(q.toQueryString(), expected.toString());
assertEquals(q.getParamMap().get("p0"), "sample");
assertEquals(q.getParamMap().get("p1_0"), "123");
assertEquals(q.getParamMap().get("p1_1"), null);
assertEquals(q.getParamMap().get("p1_1_0"), null);
assertEquals(q.getParamMap().get("p1_1_1"), "456");
assertEquals(q.getParamMap().get("p2_0"), "333");
assertEquals(q.getParamMap().get("p2_1"), null);
assertEquals(q.getParamMap().get("p2_1_0"), null);
assertEquals(q.getParamMap().get("p2_1_1"), "456");
assertEquals(q.getParamMap().size(), 9);
}
public void testCountQuery() {
TypedQueryBuilder<String> q = new TypedQueryBuilder<String>(String.class, "test");
StringBuilder expected = new StringBuilder("SELECT COUNT(*) FROM " + String.class.getName() + " test");
assertEquals(q.toQueryString(true), expected.toString());
}
}
| 0true
|
common_src_test_java_org_broadleafcommerce_common_util_dao_TypedQueryBuilderTest.java
|
94 |
class ReadOnlyTransactionImpl implements Transaction
{
private static final int RS_ENLISTED = 0;
private static final int RS_SUSPENDED = 1;
private static final int RS_DELISTED = 2;
private static final int RS_READONLY = 3; // set in prepare
private final byte globalId[];
private int status = Status.STATUS_ACTIVE;
private boolean active = true;
private final LinkedList<ResourceElement> resourceList =
new LinkedList<>();
private List<Synchronization> syncHooks =
new ArrayList<>();
private final int eventIdentifier;
private final ReadOnlyTxManager txManager;
private final StringLogger logger;
ReadOnlyTransactionImpl( byte[] xidGlobalId, ReadOnlyTxManager txManager, StringLogger logger )
{
this.txManager = txManager;
this.logger = logger;
globalId = xidGlobalId;
eventIdentifier = txManager.getNextEventIdentifier();
}
@Override
public synchronized String toString()
{
StringBuilder txString = new StringBuilder( "Transaction[Status="
+ txManager.getTxStatusAsString( status ) + ",ResourceList=" );
Iterator<ResourceElement> itr = resourceList.iterator();
while ( itr.hasNext() )
{
txString.append( itr.next().toString() );
if ( itr.hasNext() )
{
txString.append( "," );
}
}
return txString.toString();
}
@Override
public synchronized void commit() throws RollbackException,
HeuristicMixedException, IllegalStateException
{
// make sure tx not suspended
txManager.commit();
}
@Override
public synchronized void rollback() throws IllegalStateException,
SystemException
{
// make sure tx not suspended
txManager.rollback();
}
@Override
public synchronized boolean enlistResource( XAResource xaRes )
throws RollbackException, IllegalStateException
{
if ( xaRes == null )
{
throw new IllegalArgumentException( "Null xa resource" );
}
if ( status == Status.STATUS_ACTIVE ||
status == Status.STATUS_PREPARING )
{
try
{
if ( resourceList.size() == 0 )
{
//
byte branchId[] = txManager.getBranchId( xaRes );
Xid xid = new XidImpl( globalId, branchId );
resourceList.add( new ResourceElement( xid, xaRes ) );
xaRes.start( xid, XAResource.TMNOFLAGS );
return true;
}
Xid sameRmXid = null;
for ( ResourceElement re : resourceList )
{
if ( sameRmXid == null && re.getResource().isSameRM( xaRes ) )
{
sameRmXid = re.getXid();
}
if ( xaRes == re.getResource() )
{
if ( re.getStatus() == RS_SUSPENDED )
{
xaRes.start( re.getXid(), XAResource.TMRESUME );
}
else
{
// either enlisted or delisted
// is TMJOIN correct then?
xaRes.start( re.getXid(), XAResource.TMJOIN );
}
re.setStatus( RS_ENLISTED );
return true;
}
}
if ( sameRmXid != null ) // should we join?
{
resourceList.add( new ResourceElement( sameRmXid, xaRes ) );
xaRes.start( sameRmXid, XAResource.TMJOIN );
}
else
// new branch
{
// ResourceElement re = resourceList.getFirst();
byte branchId[] = txManager.getBranchId( xaRes );
Xid xid = new XidImpl( globalId, branchId );
resourceList.add( new ResourceElement( xid, xaRes ) );
xaRes.start( xid, XAResource.TMNOFLAGS );
}
return true;
}
catch ( XAException e )
{
logger.error( "Unable to enlist resource[" + xaRes + "]", e );
status = Status.STATUS_MARKED_ROLLBACK;
return false;
}
}
else if ( status == Status.STATUS_ROLLING_BACK ||
status == Status.STATUS_ROLLEDBACK ||
status == Status.STATUS_MARKED_ROLLBACK )
{
throw new RollbackException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
throw new IllegalStateException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
@Override
public synchronized boolean delistResource( XAResource xaRes, int flag )
throws IllegalStateException
{
if ( xaRes == null )
{
throw new IllegalArgumentException( "Null xa resource" );
}
if ( flag != XAResource.TMSUCCESS && flag != XAResource.TMSUSPEND &&
flag != XAResource.TMFAIL )
{
throw new IllegalArgumentException( "Illegal flag: " + flag );
}
ResourceElement re = null;
for ( ResourceElement reMatch : resourceList )
{
if ( reMatch.getResource() == xaRes )
{
re = reMatch;
break;
}
}
if ( re == null )
{
return false;
}
if ( status == Status.STATUS_ACTIVE ||
status == Status.STATUS_MARKED_ROLLBACK )
{
try
{
xaRes.end( re.getXid(), flag );
if ( flag == XAResource.TMSUSPEND || flag == XAResource.TMFAIL )
{
re.setStatus( RS_SUSPENDED );
}
else
{
re.setStatus( RS_DELISTED );
}
return true;
}
catch ( XAException e )
{
logger.error("Unable to delist resource[" + xaRes + "]", e );
status = Status.STATUS_MARKED_ROLLBACK;
return false;
}
}
throw new IllegalStateException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
// TODO: figure out if this needs synchronization or make status volatile
public int getStatus()
{
return status;
}
void setStatus( int status )
{
this.status = status;
}
private boolean beforeCompletionRunning = false;
private List<Synchronization> syncHooksAdded = new ArrayList<>();
@Override
public synchronized void registerSynchronization( Synchronization s )
throws RollbackException, IllegalStateException
{
if ( s == null )
{
throw new IllegalArgumentException( "Null parameter" );
}
if ( status == Status.STATUS_ACTIVE ||
status == Status.STATUS_PREPARING ||
status == Status.STATUS_MARKED_ROLLBACK )
{
if ( !beforeCompletionRunning )
{
syncHooks.add( s );
}
else
{
// avoid CME if synchronization is added in before completion
syncHooksAdded.add( s );
}
}
else if ( status == Status.STATUS_ROLLING_BACK ||
status == Status.STATUS_ROLLEDBACK )
{
throw new RollbackException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
else
{
throw new IllegalStateException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
}
synchronized void doBeforeCompletion()
{
beforeCompletionRunning = true;
try
{
for ( Synchronization s : syncHooks )
{
try
{
s.beforeCompletion();
}
catch ( Throwable t )
{
logger.warn( "Caught exception from tx syncronization[" + s
+ "] beforeCompletion()", t );
}
}
// execute any hooks added since we entered doBeforeCompletion
while ( !syncHooksAdded.isEmpty() )
{
List<Synchronization> addedHooks = syncHooksAdded;
syncHooksAdded = new ArrayList<>();
for ( Synchronization s : addedHooks )
{
s.beforeCompletion();
syncHooks.add( s );
}
}
}
finally
{
beforeCompletionRunning = false;
}
}
synchronized void doAfterCompletion()
{
for ( Synchronization s : syncHooks )
{
try
{
s.afterCompletion( status );
}
catch ( Throwable t )
{
logger.warn( "Caught exception from tx syncronization[" + s
+ "] afterCompletion()", t );
}
}
syncHooks = null; // help gc
}
@Override
public void setRollbackOnly() throws IllegalStateException
{
if ( status == Status.STATUS_ACTIVE ||
status == Status.STATUS_PREPARING ||
status == Status.STATUS_PREPARED ||
status == Status.STATUS_MARKED_ROLLBACK ||
status == Status.STATUS_ROLLING_BACK )
{
status = Status.STATUS_MARKED_ROLLBACK;
}
else
{
throw new IllegalStateException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
}
@Override
public boolean equals( Object o )
{
if ( !(o instanceof ReadOnlyTransactionImpl) )
{
return false;
}
ReadOnlyTransactionImpl other = (ReadOnlyTransactionImpl) o;
return this.eventIdentifier == other.eventIdentifier;
}
private volatile int hashCode = 0;
@Override
public int hashCode()
{
if ( hashCode == 0 )
{
hashCode = 3217 * eventIdentifier;
}
return hashCode;
}
int getResourceCount()
{
return resourceList.size();
}
void doRollback() throws XAException
{
status = Status.STATUS_ROLLING_BACK;
LinkedList<Xid> rolledBackXids = new LinkedList<>();
for ( ResourceElement re : resourceList )
{
if ( !rolledBackXids.contains( re.getXid() ) )
{
rolledBackXids.add( re.getXid() );
re.getResource().rollback( re.getXid() );
}
}
status = Status.STATUS_ROLLEDBACK;
}
private static class ResourceElement
{
private Xid xid = null;
private XAResource resource = null;
private int status;
ResourceElement( Xid xid, XAResource resource )
{
this.xid = xid;
this.resource = resource;
status = RS_ENLISTED;
}
Xid getXid()
{
return xid;
}
XAResource getResource()
{
return resource;
}
int getStatus()
{
return status;
}
void setStatus( int status )
{
this.status = status;
}
@Override
public String toString()
{
String statusString;
switch ( status )
{
case RS_ENLISTED:
statusString = "ENLISTED";
break;
case RS_DELISTED:
statusString = "DELISTED";
break;
case RS_SUSPENDED:
statusString = "SUSPENDED";
break;
case RS_READONLY:
statusString = "READONLY";
break;
default:
statusString = "UNKNOWN";
}
return "Xid[" + xid + "] XAResource[" + resource + "] Status["
+ statusString + "]";
}
}
synchronized void markAsActive()
{
if ( active )
{
throw new IllegalStateException( "Transaction[" + this
+ "] already active" );
}
active = true;
}
synchronized void markAsSuspended()
{
if ( !active )
{
throw new IllegalStateException( "Transaction[" + this
+ "] already suspended" );
}
active = false;
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_ReadOnlyTransactionImpl.java
|
1,070 |
public class TransportUpdateAction extends TransportInstanceSingleOperationAction<UpdateRequest, UpdateResponse> {
private final TransportDeleteAction deleteAction;
private final TransportIndexAction indexAction;
private final AutoCreateIndex autoCreateIndex;
private final TransportCreateIndexAction createIndexAction;
private final UpdateHelper updateHelper;
@Inject
public TransportUpdateAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService,
TransportIndexAction indexAction, TransportDeleteAction deleteAction, TransportCreateIndexAction createIndexAction,
UpdateHelper updateHelper) {
super(settings, threadPool, clusterService, transportService);
this.indexAction = indexAction;
this.deleteAction = deleteAction;
this.createIndexAction = createIndexAction;
this.updateHelper = updateHelper;
this.autoCreateIndex = new AutoCreateIndex(settings);
}
@Override
protected String transportAction() {
return UpdateAction.NAME;
}
@Override
protected String executor() {
return ThreadPool.Names.INDEX;
}
@Override
protected UpdateRequest newRequest() {
return new UpdateRequest();
}
@Override
protected UpdateResponse newResponse() {
return new UpdateResponse();
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, UpdateRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.WRITE);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, UpdateRequest request) {
return state.blocks().indexBlockedException(ClusterBlockLevel.WRITE, request.index());
}
@Override
protected boolean retryOnFailure(Throwable e) {
return TransportActions.isShardNotAvailableException(e);
}
@Override
protected boolean resolveRequest(ClusterState state, UpdateRequest request, ActionListener<UpdateResponse> listener) {
MetaData metaData = clusterService.state().metaData();
String aliasOrIndex = request.index();
request.routing((metaData.resolveIndexRouting(request.routing(), aliasOrIndex)));
request.index(metaData.concreteIndex(request.index()));
// Fail fast on the node that received the request, rather than failing when translating on the index or delete request.
if (request.routing() == null && state.getMetaData().routingRequired(request.index(), request.type())) {
throw new RoutingMissingException(request.index(), request.type(), request.id());
}
return true;
}
@Override
protected void doExecute(final UpdateRequest request, final ActionListener<UpdateResponse> listener) {
// if we don't have a master, we don't have metadata, that's fine, let it find a master using create index API
if (autoCreateIndex.shouldAutoCreate(request.index(), clusterService.state())) {
request.beforeLocalFork(); // we fork on another thread...
createIndexAction.execute(new CreateIndexRequest(request.index()).cause("auto(update api)").masterNodeTimeout(request.timeout()), new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse result) {
innerExecute(request, listener);
}
@Override
public void onFailure(Throwable e) {
if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) {
// we have the index, do it
try {
innerExecute(request, listener);
} catch (Throwable e1) {
listener.onFailure(e1);
}
} else {
listener.onFailure(e);
}
}
});
} else {
innerExecute(request, listener);
}
}
private void innerExecute(final UpdateRequest request, final ActionListener<UpdateResponse> listener) {
super.doExecute(request, listener);
}
@Override
protected ShardIterator shards(ClusterState clusterState, UpdateRequest request) throws ElasticsearchException {
if (request.shardId() != -1) {
return clusterState.routingTable().index(request.index()).shard(request.shardId()).primaryShardIt();
}
ShardIterator shardIterator = clusterService.operationRouting()
.indexShards(clusterService.state(), request.index(), request.type(), request.id(), request.routing());
ShardRouting shard;
while ((shard = shardIterator.nextOrNull()) != null) {
if (shard.primary()) {
return new PlainShardIterator(shardIterator.shardId(), ImmutableList.of(shard));
}
}
return new PlainShardIterator(shardIterator.shardId(), ImmutableList.<ShardRouting>of());
}
@Override
protected void shardOperation(final UpdateRequest request, final ActionListener<UpdateResponse> listener) throws ElasticsearchException {
shardOperation(request, listener, 0);
}
protected void shardOperation(final UpdateRequest request, final ActionListener<UpdateResponse> listener, final int retryCount) throws ElasticsearchException {
final UpdateHelper.Result result = updateHelper.prepare(request);
switch (result.operation()) {
case UPSERT:
IndexRequest upsertRequest = result.action();
// we fetch it from the index request so we don't generate the bytes twice, its already done in the index request
final BytesReference upsertSourceBytes = upsertRequest.source();
indexAction.execute(upsertRequest, new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse response) {
UpdateResponse update = new UpdateResponse(response.getIndex(), response.getType(), response.getId(), response.getVersion(), response.isCreated());
if (request.fields() != null && request.fields().length > 0) {
Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(upsertSourceBytes, true);
update.setGetResult(updateHelper.extractGetResult(request, response.getVersion(), sourceAndContent.v2(), sourceAndContent.v1(), upsertSourceBytes));
} else {
update.setGetResult(null);
}
listener.onResponse(update);
}
@Override
public void onFailure(Throwable e) {
e = ExceptionsHelper.unwrapCause(e);
if (e instanceof VersionConflictEngineException || e instanceof DocumentAlreadyExistsException) {
if (retryCount < request.retryOnConflict()) {
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
shardOperation(request, listener, retryCount + 1);
}
});
return;
}
}
listener.onFailure(e);
}
});
break;
case INDEX:
IndexRequest indexRequest = result.action();
// we fetch it from the index request so we don't generate the bytes twice, its already done in the index request
final BytesReference indexSourceBytes = indexRequest.source();
indexAction.execute(indexRequest, new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse response) {
UpdateResponse update = new UpdateResponse(response.getIndex(), response.getType(), response.getId(), response.getVersion(), response.isCreated());
update.setGetResult(updateHelper.extractGetResult(request, response.getVersion(), result.updatedSourceAsMap(), result.updateSourceContentType(), indexSourceBytes));
listener.onResponse(update);
}
@Override
public void onFailure(Throwable e) {
e = ExceptionsHelper.unwrapCause(e);
if (e instanceof VersionConflictEngineException) {
if (retryCount < request.retryOnConflict()) {
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
shardOperation(request, listener, retryCount + 1);
}
});
return;
}
}
listener.onFailure(e);
}
});
break;
case DELETE:
DeleteRequest deleteRequest = result.action();
deleteAction.execute(deleteRequest, new ActionListener<DeleteResponse>() {
@Override
public void onResponse(DeleteResponse response) {
UpdateResponse update = new UpdateResponse(response.getIndex(), response.getType(), response.getId(), response.getVersion(), false);
update.setGetResult(updateHelper.extractGetResult(request, response.getVersion(), result.updatedSourceAsMap(), result.updateSourceContentType(), null));
listener.onResponse(update);
}
@Override
public void onFailure(Throwable e) {
e = ExceptionsHelper.unwrapCause(e);
if (e instanceof VersionConflictEngineException) {
if (retryCount < request.retryOnConflict()) {
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
shardOperation(request, listener, retryCount + 1);
}
});
return;
}
}
listener.onFailure(e);
}
});
break;
case NONE:
UpdateResponse update = result.action();
listener.onResponse(update);
break;
default:
throw new ElasticsearchIllegalStateException("Illegal operation " + result.operation());
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_update_TransportUpdateAction.java
|
1,506 |
public class DisableAllocationTests extends ElasticsearchAllocationTestCase {
private final ESLogger logger = Loggers.getLogger(DisableAllocationTests.class);
@Test
public void testClusterDisableAllocation() {
AllocationService strategy = createAllocationService(settingsBuilder()
.put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_NEW_ALLOCATION, true)
.put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_ALLOCATION, true)
.build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").numberOfShards(1).numberOfReplicas(1))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
logger.info("--> adding two nodes and do rerouting");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("node1"))
.put(newNode("node2"))
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(clusterState.routingNodes().shardsWithState(INITIALIZING).size(), equalTo(0));
}
@Test
public void testClusterDisableReplicaAllocation() {
AllocationService strategy = createAllocationService(settingsBuilder()
.put("cluster.routing.allocation.disable_replica_allocation", true)
.build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").numberOfShards(1).numberOfReplicas(1))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
logger.info("--> adding two nodes do rerouting");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("node1"))
.put(newNode("node2"))
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(clusterState.routingNodes().shardsWithState(INITIALIZING).size(), equalTo(1));
logger.info("--> start the shards (primaries)");
routingTable = strategy.applyStartedShards(clusterState, clusterState.routingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(clusterState.routingNodes().shardsWithState(INITIALIZING).size(), equalTo(0));
}
@Test
public void testIndexDisableAllocation() {
AllocationService strategy = createAllocationService(settingsBuilder()
.build());
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("disabled").settings(ImmutableSettings.builder().put(DisableAllocationDecider.INDEX_ROUTING_ALLOCATION_DISABLE_ALLOCATION, true).put(DisableAllocationDecider.INDEX_ROUTING_ALLOCATION_DISABLE_NEW_ALLOCATION, true)).numberOfShards(1).numberOfReplicas(1))
.put(IndexMetaData.builder("enabled").numberOfShards(1).numberOfReplicas(1))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("disabled"))
.addAsNew(metaData.index("enabled"))
.build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
logger.info("--> adding two nodes and do rerouting");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("node1"))
.put(newNode("node2"))
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(clusterState.routingNodes().shardsWithState(INITIALIZING).size(), equalTo(1));
logger.info("--> start the shards (primaries)");
routingTable = strategy.applyStartedShards(clusterState, clusterState.routingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logger.info("--> start the shards (replicas)");
routingTable = strategy.applyStartedShards(clusterState, clusterState.routingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logger.info("--> verify only enabled index has been routed");
assertThat(clusterState.readOnlyRoutingNodes().shardsWithState("enabled", STARTED).size(), equalTo(2));
assertThat(clusterState.readOnlyRoutingNodes().shardsWithState("disabled", STARTED).size(), equalTo(0));
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_routing_allocation_DisableAllocationTests.java
|
677 |
constructors[TX_COLLECTION_ITEM] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new TxCollectionItem();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
|
1,949 |
@Repository("blCustomerDao")
public class CustomerDaoImpl implements CustomerDao {
@PersistenceContext(unitName="blPU")
protected EntityManager em;
@Resource(name="blEntityConfiguration")
protected EntityConfiguration entityConfiguration;
public Customer readCustomerById(Long id) {
return em.find(CustomerImpl.class, id);
}
public Customer readCustomerByUsername(String username) {
List<Customer> customers = readCustomersByUsername(username);
return customers == null || customers.isEmpty() ? null : customers.get(0);
}
@SuppressWarnings("unchecked")
public List<Customer> readCustomersByUsername(String username) {
Query query = em.createNamedQuery("BC_READ_CUSTOMER_BY_USER_NAME");
query.setParameter("username", username);
return query.getResultList();
}
public Customer readCustomerByEmail(String emailAddress) {
List<Customer> customers = readCustomersByEmail(emailAddress);
return customers == null || customers.isEmpty() ? null : customers.get(0);
}
@SuppressWarnings("unchecked")
public List<Customer> readCustomersByEmail(String emailAddress) {
Query query = em.createNamedQuery("BC_READ_CUSTOMER_BY_EMAIL");
query.setParameter("email", emailAddress);
return query.getResultList();
}
public Customer save(Customer customer) {
return em.merge(customer);
}
public Customer create() {
Customer customer = (Customer) entityConfiguration.createEntityInstance(Customer.class.getName());
return customer;
}
}
| 1no label
|
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_dao_CustomerDaoImpl.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.