Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
619
public interface BroadleafWebRequestProcessor { /** * Process the current request. Examples would be setting the currently logged in customer on the request or handling * anonymous customers in session * * @param request */ public void process(WebRequest request); /** * Should be called if work needs to be done after the request has been processed. * * @param request */ public void postProcess(WebRequest request); }
0true
common_src_main_java_org_broadleafcommerce_common_web_BroadleafWebRequestProcessor.java
22
private static enum STATE { unInitialized, initializing, initialized; }
0true
timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_config_FastDiskBufferEnv.java
3,385
private final static class Empty extends PagedBytesAtomicFieldData { Empty(int numDocs) { super(emptyBytes(), 0, new MonotonicAppendingLongBuffer(), new EmptyOrdinals(numDocs)); } static PagedBytes.Reader emptyBytes() { PagedBytes bytes = new PagedBytes(1); bytes.copyUsingLengthPrefix(new BytesRef()); return bytes.freeze(true); } @Override public boolean isMultiValued() { return false; } @Override public int getNumDocs() { return ordinals.getNumDocs(); } @Override public long getNumberUniqueValues() { return 0; } @Override public boolean isValuesOrdered() { return true; } @Override public BytesValues.WithOrdinals getBytesValues(boolean needsHashes) { return new EmptyByteValuesWithOrdinals(ordinals.ordinals()); } @Override public ScriptDocValues.Strings getScriptValues() { return ScriptDocValues.EMPTY_STRINGS; } }
0true
src_main_java_org_elasticsearch_index_fielddata_plain_PagedBytesAtomicFieldData.java
1,289
public class LaunchHelper { static void addFiles(List<IFile> files, IResource resource) { switch (resource.getType()) { case IResource.FILE: IFile file = (IFile) resource; IPath path = file.getFullPath(); //getProjectRelativePath(); if (path!=null && "ceylon".equals(path.getFileExtension()) ) { files.add(file); } break; case IResource.FOLDER: case IResource.PROJECT: IContainer folder = (IContainer) resource; try { for (IResource child: folder.members()) { addFiles(files, child); } } catch (CoreException e) { e.printStackTrace(); } break; } } static Object[] findDeclarationFromFiles(List<IFile> files) { List<Declaration> topLevelDeclarations = new LinkedList<Declaration>(); List<IFile> correspondingfiles = new LinkedList<IFile>(); for (IFile file : files) { IProject project = file.getProject(); TypeChecker typeChecker = getProjectTypeChecker(project); if (typeChecker != null) { PhasedUnit phasedUnit = typeChecker.getPhasedUnits() .getPhasedUnit(createResourceVirtualFile(file)); if (phasedUnit!=null) { List<Declaration> declarations = phasedUnit.getDeclarations(); for (Declaration d : declarations) { if (isRunnable(d)) { topLevelDeclarations.add(d); correspondingfiles.add(file); } } } } } Declaration declarationToRun = null; IFile fileToRun = null; if (topLevelDeclarations.size() == 0) { MessageDialog.openError(EditorUtil.getShell(), "Ceylon Launcher", "No ceylon runnable element"); } else if (topLevelDeclarations.size() > 1) { declarationToRun = chooseDeclaration(topLevelDeclarations); if (declarationToRun!=null) { fileToRun = correspondingfiles.get(topLevelDeclarations.indexOf(declarationToRun)); } } else { declarationToRun = topLevelDeclarations.get(0); fileToRun = correspondingfiles.get(0); } return new Object[] {declarationToRun, fileToRun}; } private static boolean isRunnable(Declaration d) { boolean candidateDeclaration = true; if (!d.isToplevel() || !d.isShared()) { candidateDeclaration = false; } if (d instanceof Method) { Method methodDecl = (Method) d; if (!methodDecl.getParameterLists().isEmpty() && !methodDecl.getParameterLists().get(0).getParameters().isEmpty()) { candidateDeclaration = false; } } else if (d instanceof Class) { Class classDecl = (Class) d; if (classDecl.isAbstract() || classDecl.getParameterList()==null || !classDecl.getParameterList().getParameters().isEmpty()) { candidateDeclaration = false; } } else { candidateDeclaration = false; } return candidateDeclaration; } static Module getModule(IProject project, String fullModuleName) { fullModuleName = normalizeFullModuleName(fullModuleName); if (fullModuleName != null) { String[] parts = fullModuleName.split("/"); if (parts != null && parts.length != 2) { return null; } for (Module module: getProjectDeclaredSourceModules(project)) { if (module.getNameAsString().equals(parts[0]) && module.getVersion().equals(parts[1])) { return module; } } if (isDefaultModulePresent(project)) { return getDefaultModule(project); } } return null; } private static String normalizeFullModuleName(String fullModuleName) { if (Module.DEFAULT_MODULE_NAME.equals(fullModuleName)) { return getFullModuleName(getEmptyDefaultModule()); } else { return fullModuleName; } } private static Module getDefaultModule(IProject project) { Module defaultModule = getProjectModules(project).getDefaultModule(); if (defaultModule == null) { defaultModule = getEmptyDefaultModule(); } return defaultModule; } private static Module getEmptyDefaultModule() { Module defaultModule = new Module(); defaultModule.setName(Arrays.asList(new String[]{Module.DEFAULT_MODULE_NAME})); defaultModule.setVersion("unversioned"); defaultModule.setDefault(true); return defaultModule; } static Module getModule(Declaration decl) { if (decl.getUnit().getPackage() != null) { if (decl.getUnit().getPackage().getModule() != null) { return decl.getUnit().getPackage().getModule(); } } return getEmptyDefaultModule(); } static String getModuleFullName(Declaration decl) { Module module = getModule(decl); if (module.isDefault()) { return Module.DEFAULT_MODULE_NAME; } else { return getFullModuleName(module); } } static Set<Module> getModules(IProject project, boolean includeDefault) { Set<Module> modules = new HashSet<Module>(); for(Module module: getProjectDeclaredSourceModules(project)) { if (module.isAvailable() && !module.getNameAsString().startsWith(Module.LANGUAGE_MODULE_NAME) && !module.isJava() ) { if ((module.isDefault() && includeDefault) // TODO : this is *never* true : the default module is not in the requested list || (!module.isDefault() && module.getPackage(module.getNameAsString()) != null)){ modules.add(module); } } } if (modules.isEmpty() || isDefaultModulePresent(project)) { modules.add(getDefaultModule(project)); } return modules; } private static boolean isDefaultModulePresent(IProject project) { Module defaultModule = getProjectModules(project).getDefaultModule(); if (defaultModule != null) { List<Declaration> decls = getDeclarationsForModule(project, defaultModule); if (!decls.isEmpty()) { return true; } } return false; } static boolean isModuleInProject(IProject project, String fullModuleName) { if (fullModuleName.equals(Module.DEFAULT_MODULE_NAME) && isDefaultModulePresent(project)) { return true; } for (Module module : getModules(project, false)) { if (fullModuleName != null && fullModuleName.equals(getFullModuleName(module))) { return true; } } return false; } static String getFullModuleName(Module module) { return module.getNameAsString()+"/"+module.getVersion(); } static List<Declaration> getDeclarationsForModule(IProject project, Module module) { List<Declaration> modDecls = new LinkedList<Declaration>(); if (module != null) { List<Package> pkgs = module.getPackages(); // avoid concurrent exception for (Package pkg : pkgs) { if (pkg.getModule() != null && isPackageInProject(project, pkg)) for (Declaration decl : pkg.getMembers()) { if (isRunnable(decl)) { modDecls.add(decl); } } } } return modDecls; } private static boolean isPackageInProject(IProject project, Package pkg) { TypeChecker typeChecker = getProjectTypeChecker(project); List<PhasedUnit> pus = typeChecker.getPhasedUnits().getPhasedUnits(); for (PhasedUnit phasedUnit : pus) { if (pkg.equals(phasedUnit.getPackage())) { return true; } } return false; } static List<Declaration> getDeclarationsForModule(String projectName, String fullModuleName) { IProject project = getProjectFromName(projectName); Module module = getModule(project, fullModuleName); return getDeclarationsForModule(project, module); } /** * Does not attempt to get all declarations before it returns true * @param project * @param fullModuleName * @param topLevelName * @return boolean if a top-level is contained in a module */ static boolean isModuleContainsTopLevel(IProject project, String fullModuleName, String topLevelName) { if (!isModuleInProject(project, fullModuleName)) { return false; } if (Module.DEFAULT_MODULE_NAME.equals(fullModuleName)) { fullModuleName = getFullModuleName(getDefaultModule(project)); } Module mod = getModule(project, fullModuleName); if (mod == null) { return false; } for (Package pkg : mod.getPackages()) { for (Declaration decl : pkg.getMembers()) { if (getRunnableName(decl).equals(topLevelName)) { return true; } } } return false; } static String getRunnableName(Declaration d) { return d.getQualifiedNameString().replace("::", "."); } static Declaration chooseDeclaration(final List<Declaration> decls) { FilteredItemsSelectionDialog sd = new CeylonTopLevelSelectionDialog(EditorUtil.getShell(), false, decls); if (sd.open() == Window.OK) { return (Declaration)sd.getFirstResult(); } return null; } static Module chooseModule(String projectName, boolean includeDefault) { return chooseModule(getProjectFromName(projectName), includeDefault); } static Module chooseModule(IProject project, boolean includeDefault) { if (getDefaultOrOnlyModule(project, includeDefault) != null) { return getDefaultOrOnlyModule(project, includeDefault); } Set<Module> modules = getModules(project, true); FilteredItemsSelectionDialog cmsd = new CeylonModuleSelectionDialog(EditorUtil.getShell(), modules, "Choose Ceylon Module"); if (cmsd.open() == Window.OK) { return (Module)cmsd.getFirstResult(); } return null; } static IProject getProjectFromName(String projectName) { if (projectName != null && projectName.length() > 0) { IWorkspace workspace = getWorkspace(); IStatus status = workspace.validateName(projectName, IResource.PROJECT); if (status.isOK()) { return workspace.getRoot().getProject(projectName); } } return null; } static String getTopLevelNormalName(String moduleFullName, String displayName) { if (displayName.contains(DEFAULT_RUN_MARKER) && moduleFullName.indexOf('/') != -1) { return moduleFullName.substring(0, moduleFullName.indexOf('/')) + ".run"; } return displayName; } static String getTopLevelDisplayName(Declaration decl) { String topLevelName = getRunnableName(decl); if (getModule(decl) != null && decl.equals(getDefaultRunnableForModule(getModule(decl)))) { topLevelName = "run" + DEFAULT_RUN_MARKER; } return topLevelName; } static Module getDefaultOrOnlyModule(IProject project, boolean includeDefault) { Set<Module> modules = getModules(project, true); //if only one real module or just one default module, just send it back if (modules.size() == 1) { return modules.iterator().next(); } if (modules.size() ==2 && !includeDefault) { Iterator<Module> modIterator = modules.iterator(); while (modIterator.hasNext()) { Module realMod = modIterator.next(); if (!realMod.isDefault()) { return realMod; } } } return null; } static Declaration getDefaultRunnableForModule(Module mod) { Declaration decl = null; if (mod.getRootPackage() != null) { decl = mod.getRootPackage() .getDirectMember("run", null, false); } return decl; } static Module getModule(IFolder folder) { Package pkg = getPackage(folder); if (pkg != null) { return pkg.getModule(); } return null; } static boolean isBuilderEnabled(IProject project, String property) { if (CAN_LAUNCH_AS_CEYLON_JAVA_MODULE.equals(property)) { return CeylonBuilder.compileToJava(project); } else if (CAN_LAUNCH_AS_CEYLON_JAVASCIPT_MODULE.equals(property)) { return CeylonBuilder.compileToJs(project); } return false; } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_launch_LaunchHelper.java
1,823
constructors[VALUES] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new MapValueCollection(); } };
0true
hazelcast_src_main_java_com_hazelcast_map_MapDataSerializerHook.java
2,095
public class CachedStreamInput { static class Entry { final HandlesStreamInput handles; Entry(HandlesStreamInput handles) { this.handles = handles; } } private static final ThreadLocal<SoftReference<Entry>> cache = new ThreadLocal<SoftReference<Entry>>(); static Entry instance() { SoftReference<Entry> ref = cache.get(); Entry entry = ref == null ? null : ref.get(); if (entry == null) { HandlesStreamInput handles = new HandlesStreamInput(); entry = new Entry(handles); cache.set(new SoftReference<Entry>(entry)); } return entry; } public static void clear() { cache.remove(); } public static StreamInput compressed(Compressor compressor, StreamInput in) throws IOException { return compressor.streamInput(in); } public static HandlesStreamInput cachedHandles(StreamInput in) { HandlesStreamInput handles = instance().handles; handles.reset(in); return handles; } public static HandlesStreamInput cachedHandlesCompressed(Compressor compressor, StreamInput in) throws IOException { Entry entry = instance(); entry.handles.reset(compressor.streamInput(in)); return entry.handles; } }
0true
src_main_java_org_elasticsearch_common_io_stream_CachedStreamInput.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
626
c3.addListenerConfig(new ListenerConfig(new LifecycleListener() { public void stateChanged(final LifecycleEvent event) { if (event.getState() == LifecycleState.MERGED) { latch.countDown(); } } }));
0true
hazelcast_src_test_java_com_hazelcast_cluster_SplitBrainHandlerTest.java
1,095
public interface OSQLFunctionFactory { boolean hasFunction(String iName); /** * @return Set of supported function names of this factory */ Set<String> getFunctionNames(); /** * Create function for the given name. returned function may be a new instance each time or a constant. * * @param name * @return OSQLFunction : created function * @throws OCommandExecutionException * : when function creation fail */ OSQLFunction createFunction(String name) throws OCommandExecutionException; }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_functions_OSQLFunctionFactory.java
1,400
public class OMVRBTreeMapProvider<K, V> extends OMVRBTreeProviderAbstract<K, V> { private static final long serialVersionUID = 1L; public final static byte CURRENT_PROTOCOL_VERSION = 3; protected final OMemoryStream stream; protected OBinarySerializer<K> keySerializer; protected OStreamSerializer streamKeySerializer; protected OStreamSerializer valueSerializer; protected boolean keepKeysInMemory; protected boolean keepValuesInMemory; public OMVRBTreeMapProvider(final OStorage iStorage, final String iClusterName, final ORID iRID) { this(iStorage, iClusterName, null, null); record.setIdentity(iRID.getClusterId(), iRID.getClusterPosition()); } public OMVRBTreeMapProvider(final OStorage iStorage, final String iClusterName, final OBinarySerializer<K> iKeySerializer, final OStreamSerializer iValueSerializer) { super(new ORecordBytesLazy().unpin(), iStorage, iClusterName); ((ORecordBytesLazy) record).recycle(this); stream = new OMemoryStream(); keySerializer = iKeySerializer; valueSerializer = iValueSerializer; } public OMVRBTreeEntryDataProvider<K, V> getEntry(final ORID iRid) { return new OMVRBTreeMapEntryProvider<K, V>(this, iRid); } public OMVRBTreeEntryDataProvider<K, V> createEntry() { return new OMVRBTreeMapEntryProvider<K, V>(this); } @Override public OMVRBTreeProvider<K, V> copy() { return new OMVRBTreeMapProvider<K, V>(storage, clusterName, keySerializer, valueSerializer); } @Override protected void load(final ODatabaseRecord iDb) { ((ORecordBytesLazy) record).recycle(this); super.load(iDb); } @Override protected void load(final OStorage iSt) { ((ORecordBytesLazy) record).recycle(this); super.load(iSt); } public boolean updateConfig() { final boolean changed = super.updateConfig(); keepKeysInMemory = OGlobalConfiguration.MVRBTREE_ENTRY_KEYS_IN_MEMORY.getValueAsBoolean(); keepValuesInMemory = OGlobalConfiguration.MVRBTREE_ENTRY_VALUES_IN_MEMORY.getValueAsBoolean(); return changed; } public byte[] toStream() throws OSerializationException { final OProfilerMBean profiler = Orient.instance().getProfiler(); final long timer = profiler.startChrono(); try { stream.jump(0); stream.set(CURRENT_PROTOCOL_VERSION); stream.setAsFixed(root != null ? root.toStream() : ORecordId.EMPTY_RECORD_ID_STREAM); stream.set(size); stream.set(pageSize); stream.set(keySize); stream.set(keySerializer.getId()); stream.set(valueSerializer.getName()); if (streamKeySerializer != null) stream.set(streamKeySerializer.getName()); else stream.set(""); final byte[] result = stream.toByteArray(); record.fromStream(result); return result; } finally { profiler.stopChrono(profiler.getProcessMetric("mvrbtree.toStream"), "Serialize a MVRBTree", timer); } } @SuppressWarnings("unchecked") public OSerializableStream fromStream(final byte[] iStream) throws OSerializationException { final OProfilerMBean profiler = Orient.instance().getProfiler(); final long timer = profiler.startChrono(); try { stream.setSource(iStream); byte protocolVersion = stream.peek(); if (protocolVersion != -1) { // @COMPATIBILITY BEFORE 0.9.25 stream.getAsByte(); if (protocolVersion != CURRENT_PROTOCOL_VERSION) OLogManager .instance() .debug( this, "Found tree %s created with MVRBTree protocol version %d while current one supports the version %d. The tree will be migrated transparently", getRecord().getIdentity(), protocolVersion, CURRENT_PROTOCOL_VERSION); } root = new ORecordId(); root.fromStream(stream.getAsByteArrayFixed(ORecordId.PERSISTENT_SIZE)); size = stream.getAsInteger(); if (protocolVersion == -1) // @COMPATIBILITY BEFORE 0.9.25 pageSize = stream.getAsShort(); else pageSize = stream.getAsInteger(); // @COMPATIBILITY BEFORE 1.0 if (protocolVersion < 1) { keySize = 1; OLogManager.instance().warn(this, "Previous index version was found, partial composite index queries may do not work if you " + "do not recreate index."); } else keySize = stream.getAsInteger(); // @COMPATIBILITY BEFORE 1.0 if (protocolVersion < 3) { streamKeySerializer = OStreamSerializerFactory.get(stream.getAsString()); valueSerializer = OStreamSerializerFactory.get(stream.getAsString()); keySerializer = createRelatedSerializer(streamKeySerializer); } else { keySerializer = (OBinarySerializer<K>) OBinarySerializerFactory.INSTANCE.getObjectSerializer(stream.getAsByte()); valueSerializer = OStreamSerializerFactory.get(stream.getAsString()); final String oldKeySerializerName = stream.getAsString(); if (oldKeySerializerName != null && oldKeySerializerName.length() > 0) streamKeySerializer = OStreamSerializerFactory.get(oldKeySerializerName); } } catch (Exception e) { OLogManager.instance().error(this, "Error on unmarshalling OMVRBTreeMapProvider object from record: %s", e, OSerializationException.class, root); } finally { profiler.stopChrono(profiler.getProcessMetric("mvrbtree.fromStream"), "Deserialize a MVRBTree", timer); } return this; } @SuppressWarnings({ "unchecked", "rawtypes" }) public OBinarySerializer<K> createRelatedSerializer(final OStreamSerializer streamKeySerializer) { if (streamKeySerializer instanceof OBinarySerializer) return (OBinarySerializer<K>) streamKeySerializer; if (streamKeySerializer instanceof OStreamSerializerLiteral) return (OBinarySerializer<K>) new OSimpleKeySerializer(); if (streamKeySerializer instanceof OStreamSerializerLong) return (OBinarySerializer<K>) OLongSerializer.INSTANCE; throw new OSerializationException("Given serializer " + streamKeySerializer.getClass().getName() + " can not be converted into " + OBinarySerializer.class.getName() + "."); } public OBinarySerializer<K> getKeySerializer() { return keySerializer; } public OStreamSerializer getValueSerializer() { return valueSerializer; } }
0true
core_src_main_java_com_orientechnologies_orient_core_type_tree_provider_OMVRBTreeMapProvider.java
1,270
@SuppressWarnings("unchecked") public class InternalTransportClusterAdminClient extends AbstractClusterAdminClient implements InternalClusterAdminClient { private final TransportClientNodesService nodesService; private final ThreadPool threadPool; private final ImmutableMap<ClusterAction, TransportActionNodeProxy> actions; @Inject public InternalTransportClusterAdminClient(Settings settings, TransportClientNodesService nodesService, ThreadPool threadPool, TransportService transportService, Map<String, GenericAction> actions) { this.nodesService = nodesService; this.threadPool = threadPool; MapBuilder<ClusterAction, TransportActionNodeProxy> actionsBuilder = new MapBuilder<ClusterAction, TransportActionNodeProxy>(); for (GenericAction action : actions.values()) { if (action instanceof ClusterAction) { actionsBuilder.put((ClusterAction) action, new TransportActionNodeProxy(settings, action, transportService)); } } this.actions = actionsBuilder.immutableMap(); } @Override public ThreadPool threadPool() { return this.threadPool; } @SuppressWarnings("unchecked") @Override public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute(final ClusterAction<Request, Response, RequestBuilder> action, final Request request) { final TransportActionNodeProxy<Request, Response> proxy = actions.get(action); return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<Response>>() { @Override public ActionFuture<Response> doWithNode(DiscoveryNode node) throws ElasticsearchException { return proxy.execute(node, request); } }); } @SuppressWarnings("unchecked") @Override public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute(final ClusterAction<Request, Response, RequestBuilder> action, final Request request, final ActionListener<Response> listener) { final TransportActionNodeProxy<Request, Response> proxy = actions.get(action); nodesService.execute(new TransportClientNodesService.NodeListenerCallback<Response>() { @Override public void doWithNode(DiscoveryNode node, ActionListener<Response> listener) throws ElasticsearchException { proxy.execute(node, request, listener); } }, listener); } }
1no label
src_main_java_org_elasticsearch_client_transport_support_InternalTransportClusterAdminClient.java
154
assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(1, listener.events.size()); MembershipEvent event = listener.events.get(0); assertEquals(MembershipEvent.MEMBER_REMOVED, event.getEventType()); assertEquals(server2Member, event.getMember()); assertEquals(getMembers(server1), event.getMembers()); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_MembershipListenerTest.java
61
public static class Builder extends UserModifiableConfiguration { private Builder() { super(GraphDatabaseConfiguration.buildConfiguration()); } /** * Configures the provided configuration path to the given value. * * @param path * @param value * @return */ public Builder set(String path, Object value) { super.set(path, value); return this; } /** * Opens a Titan graph with the previously configured options. * * @return */ public TitanGraph open() { return TitanFactory.open(super.getConfiguration()); } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanFactory.java
2,612
public final class UTFEncoderDecoder { private static final int STRING_CHUNK_SIZE = 16 * 1024; private static final UTFEncoderDecoder INSTANCE; static { INSTANCE = buildUTFUtil(); } private final StringCreator stringCreator; private final boolean hazelcastEnterpriseActive; private UTFEncoderDecoder(boolean fastStringCreator) { this(fastStringCreator ? buildFastStringCreator() : new DefaultStringCreator(), false); } private UTFEncoderDecoder(StringCreator stringCreator, boolean hazelcastEnterpriseActive) { this.stringCreator = stringCreator; this.hazelcastEnterpriseActive = hazelcastEnterpriseActive; } public StringCreator getStringCreator() { return stringCreator; } public static void writeUTF(final DataOutput out, final String str, byte[] buffer) throws IOException { INSTANCE.writeUTF0(out, str, buffer); } public static String readUTF(final DataInput in, byte[] buffer) throws IOException { return INSTANCE.readUTF0(in, buffer); } public boolean isHazelcastEnterpriseActive() { return hazelcastEnterpriseActive; } public void writeUTF0(final DataOutput out, final String str, byte[] buffer) throws IOException { boolean isNull = str == null; out.writeBoolean(isNull); if (isNull) { return; } int length = str.length(); out.writeInt(length); if (length > 0) { int chunkSize = (length / STRING_CHUNK_SIZE) + 1; for (int i = 0; i < chunkSize; i++) { int beginIndex = Math.max(0, i * STRING_CHUNK_SIZE - 1); int endIndex = Math.min((i + 1) * STRING_CHUNK_SIZE - 1, length); writeShortUTF(out, str, beginIndex, endIndex, buffer); } } } private void writeShortUTF(final DataOutput out, final String str, final int beginIndex, final int endIndex, byte[] buffer) throws IOException { int utfLength = 0; int c = 0; int count = 0; /* use charAt instead of copying String to char array */ for (int i = beginIndex; i < endIndex; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { utfLength++; } else if (c > 0x07FF) { utfLength += 3; } else { utfLength += 2; } } if (utfLength > 65535) { throw new UTFDataFormatException("encoded string too long:" + utfLength + " bytes"); } out.writeShort(utfLength); int i; for (i = beginIndex; i < endIndex; i++) { c = str.charAt(i); if (!((c >= 0x0001) && (c <= 0x007F))) { break; } buffering(buffer, count++, (byte) c, out); } for (; i < endIndex; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { buffering(buffer, count++, (byte) c, out); } else if (c > 0x07FF) { buffering(buffer, count++, (byte) (0xE0 | ((c >> 12) & 0x0F)), out); buffering(buffer, count++, (byte) (0x80 | ((c >> 6) & 0x3F)), out); buffering(buffer, count++, (byte) (0x80 | ((c) & 0x3F)), out); } else { buffering(buffer, count++, (byte) (0xC0 | ((c >> 6) & 0x1F)), out); buffering(buffer, count++, (byte) (0x80 | ((c) & 0x3F)), out); } } int length = count % buffer.length; out.write(buffer, 0, length == 0 ? buffer.length : length); } public String readUTF0(final DataInput in, byte[] buffer) throws IOException { boolean isNull = in.readBoolean(); if (isNull) { return null; } int length = in.readInt(); final char[] data = new char[length]; if (length > 0) { int chunkSize = length / STRING_CHUNK_SIZE + 1; for (int i = 0; i < chunkSize; i++) { int beginIndex = Math.max(0, i * STRING_CHUNK_SIZE - 1); int endIndex = Math.min((i + 1) * STRING_CHUNK_SIZE - 1, length); readShortUTF(in, data, beginIndex, endIndex, buffer); } } return stringCreator.buildString(data); } private void readShortUTF(final DataInput in, final char[] data, final int beginIndex, final int endIndex, byte[] buffer) throws IOException { final int utflen = in.readShort(); int c = 0; int char2 = 0; int char3 = 0; int count = 0; int charArrCount = beginIndex; int lastCount = -1; while (count < utflen) { c = buffered(buffer, count, utflen, in) & 0xff; if (c > 127) { break; } lastCount = count; count++; data[charArrCount++] = (char) c; } while (count < utflen) { if (lastCount > -1 && lastCount < count) { c = buffered(buffer, count, utflen, in) & 0xff; } switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: /* 0xxxxxxx */ lastCount = count; count++; data[charArrCount++] = (char) c; break; case 12: case 13: /* 110x xxxx 10xx xxxx */ lastCount = count++; if (count + 1 > utflen) { throw new UTFDataFormatException("malformed input: partial character at end"); } char2 = buffered(buffer, count++, utflen, in); if ((char2 & 0xC0) != 0x80) { throw new UTFDataFormatException("malformed input around byte " + count); } data[charArrCount++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: /* 1110 xxxx 10xx xxxx 10xx xxxx */ lastCount = count++; if (count + 2 > utflen) { throw new UTFDataFormatException("malformed input: partial character at end"); } char2 = buffered(buffer, count++, utflen, in); char3 = buffered(buffer, count++, utflen, in); if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) { throw new UTFDataFormatException("malformed input around byte " + (count - 1)); } data[charArrCount++] = (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; default: /* 10xx xxxx, 1111 xxxx */ throw new UTFDataFormatException("malformed input around byte " + count); } } } private void buffering(byte[] buffer, int pos, byte value, DataOutput out) throws IOException { int innerPos = pos % buffer.length; if (pos > 0 && innerPos == 0) { out.write(buffer, 0, buffer.length); } buffer[innerPos] = value; } private byte buffered(byte[] buffer, int pos, int utfLenght, DataInput in) throws IOException { int innerPos = pos % buffer.length; if (innerPos == 0) { int length = Math.min(buffer.length, utfLenght - pos); in.readFully(buffer, 0, length); } return buffer[innerPos]; } public static boolean useOldStringConstructor() { try { Class<String> clazz = String.class; clazz.getDeclaredConstructor(int.class, int.class, char[].class); return true; } catch (Throwable ignore) { } return false; } private static UTFEncoderDecoder buildUTFUtil() { try { Class<?> clazz = Class.forName("com.hazelcast.nio.utf8.EnterpriseStringCreator"); Method method = clazz.getDeclaredMethod("findBestStringCreator"); return new UTFEncoderDecoder((StringCreator) method.invoke(clazz), true); } catch (Throwable t) { } boolean faststringEnabled = Boolean.parseBoolean(System.getProperty("hazelcast.nio.faststring", "true")); return new UTFEncoderDecoder(faststringEnabled ? buildFastStringCreator() : new DefaultStringCreator(), false); } private static StringCreator buildFastStringCreator() { try { // Give access to the package private String constructor Constructor<String> constructor = null; if (UTFEncoderDecoder.useOldStringConstructor()) { constructor = String.class.getDeclaredConstructor(int.class, int.class, char[].class); } else { constructor = String.class.getDeclaredConstructor(char[].class, boolean.class); } if (constructor != null) { constructor.setAccessible(true); return new FastStringCreator(constructor); } } catch (Throwable ignore) { } return null; } private static class DefaultStringCreator implements UTFEncoderDecoder.StringCreator { @Override public String buildString(char[] chars) { return new String(chars); } } private static class FastStringCreator implements UTFEncoderDecoder.StringCreator { private final Constructor<String> constructor; private final boolean useOldStringConstructor; public FastStringCreator(Constructor<String> constructor) { this.constructor = constructor; this.useOldStringConstructor = constructor.getParameterTypes().length == 3; } @Override public String buildString(char[] chars) { try { if (useOldStringConstructor) { return constructor.newInstance(0, chars.length, chars); } else { return constructor.newInstance(chars, Boolean.TRUE); } } catch (Exception e) { throw new RuntimeException(e); } } } public interface StringCreator { String buildString(char[] chars); } }
1no label
hazelcast_src_main_java_com_hazelcast_nio_UTFEncoderDecoder.java
201
{ @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { return Command.readCommand( null, null, byteChannel, buffer ); } };
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogExtractor.java
1,652
public class ODistributedSelectQueryExecutor extends OAbstractDistributedQueryExecutor implements MessageListener<byte[]> { private static final int QUEUE_SIZE = 100; private static final AtomicLong SELECT_ID_GENERATOR = new AtomicLong(0); private final long storageId; private final long selectId; private final boolean anyFunctionAggregate; private final List<OPair<String, OSQLFunction>> mergers = new ArrayList<OPair<String, OSQLFunction>>(); private OPair<String, OSQLFunctionDistinct> distinct = null; private List<OPair<String, String>> order = null; private final int limit; private final boolean async; private final OCommandResultListener resultListener; private final BlockingQueue<byte[]> plainResult = new ArrayBlockingQueue<byte[]>(QUEUE_SIZE); private final ITopic<byte[]> resultTopic; public ODistributedSelectQueryExecutor(OCommandRequestText iCommand, OCommandExecutorSQLSelect executor, OStorageEmbedded wrapped, ServerInstance serverInstance) { super(iCommand, wrapped, serverInstance); this.selectId = SELECT_ID_GENERATOR.incrementAndGet(); this.storageId = serverInstance.getLocalNode().getNodeId(); this.anyFunctionAggregate = executor.isAnyFunctionAggregates(); if (executor.getProjections() != null) { for (Map.Entry<String, Object> projection : executor.getProjections().entrySet()) { if (projection.getValue() instanceof OSQLFunctionRuntime) { final OSQLFunctionRuntime fr = (OSQLFunctionRuntime) projection.getValue(); if (fr.getFunction().shouldMergeDistributedResult()) { mergers.add(new OPair<String, OSQLFunction>(projection.getKey(), fr.getFunction())); } else if (fr.getFunction() instanceof OSQLFunctionDistinct) { distinct = new OPair<String, OSQLFunctionDistinct>(projection.getKey(), (OSQLFunctionDistinct) fr.getFunction()); } } } } this.order = executor.getOrderedFields(); this.limit = executor.getLimit(); this.resultListener = (iCommand.getResultListener() != null && !(iCommand.getResultListener() instanceof OSQLSynchQuery)) ? iCommand .getResultListener() : null; this.async = resultListener != null && !anyFunctionAggregate && distinct == null && mergers.isEmpty() && order == null; this.resultTopic = ServerInstance.getHazelcast().getTopic(getResultTopicName(storageId, selectId)); this.resultTopic.addMessageListener(this); } @Override protected void addResult(Object result) { // hear result is always null, no actions needed } @Override public void onMessage(Message<byte[]> message) { try { plainResult.put(message.getMessageObject()); } catch (InterruptedException e) { OLogManager.instance().warn(this, "Failed to put message into queue"); } } @Override public Object execute() { if (iCommand.getParameters().size() == 1) { final Map.Entry<Object, Object> entry = iCommand.getParameters().entrySet().iterator().next(); if (entry.getKey().equals(Integer.valueOf(0)) && entry.getValue() == null) { iCommand.getParameters().clear(); } } int remainingExecutors = runCommandOnAllNodes(new OSQLAsynchQuery(iCommand.getText(), iCommand.getLimit(), iCommand instanceof OQueryAbstract ? ((OQueryAbstract) iCommand).getFetchPlan() : null, iCommand.getParameters(), new OHazelcastResultListener(ServerInstance.getHazelcast(), storageId, selectId))); int processed = 0; final List<OIdentifiable> result = new ArrayList<OIdentifiable>(); while (true) { try { final byte[] plainItem = plainResult.take(); final Object item = OCommandResultSerializationHelper.readFromStream(plainItem); if (item instanceof OIdentifiable) { if (async) { resultListener.result(item); } else { result.add((OIdentifiable) item); } processed++; } else if (item instanceof OHazelcastResultListener.EndOfResult) { remainingExecutors--; } else { throw new IllegalArgumentException("Invalid type provided"); } } catch (InterruptedException e) { OLogManager.instance().warn(this, "Failed to take message from queue"); } catch (IOException e) { OLogManager.instance().warn(this, "Error deserializing result"); } if (remainingExecutors <= failedNodes.get() || (async && limit != -1 && processed >= limit)) { break; } } resultTopic.destroy(); if (async) { return null; } else { return processResult(result); } } private List<OIdentifiable> processResult(List<OIdentifiable> result) { final Map<String, Object> values = new HashMap<String, Object>(); for (OPair<String, OSQLFunction> merger : mergers) { final List<Object> dataToMerge = new ArrayList<Object>(); for (OIdentifiable o : result) { dataToMerge.add(((ODocument) o).field(merger.getKey())); } values.put(merger.getKey(), merger.getValue().mergeDistributedResult(dataToMerge)); } if (distinct != null) { final List<OIdentifiable> resultToMerge = new ArrayList<OIdentifiable>(result); result.clear(); for (OIdentifiable record : resultToMerge) { Object ret = distinct.getValue() .execute(record, null, new Object[] { ((ODocument) record).field(distinct.getKey()) }, null); if (ret != null) { final ODocument resultItem = new ODocument().setOrdered(true); // ASSIGN A TEMPORARY RID TO ALLOW PAGINATION IF ANY ((ORecordId) resultItem.getIdentity()).clusterId = -2; resultItem.field(distinct.getKey(), ret); result.add(resultItem); } } } if (anyFunctionAggregate && !result.isEmpty()) { // left only one result final OIdentifiable doc = result.get(0); result.clear(); result.add(doc); } // inject values if (!values.isEmpty()) { for (Map.Entry<String, Object> entry : values.entrySet()) { for (OIdentifiable item : result) { ((ODocument) item).field(entry.getKey(), entry.getValue()); } } } if (order != null) { ODocumentHelper.sort(result, order); } if (limit != -1 && result.size() > limit) { do { result.remove(result.size() - 1); } while (result.size() > limit); } if (!result.isEmpty() && result.get(0).getIdentity().getClusterId() == -2) { long position = 0; for (OIdentifiable id : result) { ((ORecordId) id.getIdentity()).clusterPosition = OClusterPositionFactory.INSTANCE.valueOf(position); } } if (resultListener != null) { for (Object o : result) { resultListener.result(o); } } return result; } public static String getResultTopicName(long storageId, long selectId) { return new StringBuilder("query-").append(storageId).append("-").append(selectId).toString(); } }
0true
distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_oldsharding_ODistributedSelectQueryExecutor.java
365
public class DeleteRepositoryResponse extends AcknowledgedResponse { DeleteRepositoryResponse() { } DeleteRepositoryResponse(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_cluster_repositories_delete_DeleteRepositoryResponse.java
5,821
public class HighlighterParseElement implements SearchParseElement { private static final String[] DEFAULT_PRE_TAGS = new String[]{"<em>"}; private static final String[] DEFAULT_POST_TAGS = new String[]{"</em>"}; private static final String[] STYLED_PRE_TAG = { "<em class=\"hlt1\">", "<em class=\"hlt2\">", "<em class=\"hlt3\">", "<em class=\"hlt4\">", "<em class=\"hlt5\">", "<em class=\"hlt6\">", "<em class=\"hlt7\">", "<em class=\"hlt8\">", "<em class=\"hlt9\">", "<em class=\"hlt10\">" }; private static final String[] STYLED_POST_TAGS = {"</em>"}; @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token; String topLevelFieldName = null; List<SearchContextHighlight.Field> fields = newArrayList(); String[] globalPreTags = DEFAULT_PRE_TAGS; String[] globalPostTags = DEFAULT_POST_TAGS; boolean globalScoreOrdered = false; boolean globalHighlightFilter = false; boolean globalRequireFieldMatch = false; boolean globalForceSource = false; int globalFragmentSize = 100; int globalNumOfFragments = 5; String globalEncoder = "default"; int globalBoundaryMaxScan = SimpleBoundaryScanner.DEFAULT_MAX_SCAN; Character[] globalBoundaryChars = SimpleBoundaryScanner.DEFAULT_BOUNDARY_CHARS; String globalHighlighterType = null; String globalFragmenter = null; Map<String, Object> globalOptions = null; Query globalHighlightQuery = null; int globalNoMatchSize = 0; int globalPhraseLimit = 256; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { topLevelFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("pre_tags".equals(topLevelFieldName) || "preTags".equals(topLevelFieldName)) { List<String> preTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { preTagsList.add(parser.text()); } globalPreTags = preTagsList.toArray(new String[preTagsList.size()]); } else if ("post_tags".equals(topLevelFieldName) || "postTags".equals(topLevelFieldName)) { List<String> postTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { postTagsList.add(parser.text()); } globalPostTags = postTagsList.toArray(new String[postTagsList.size()]); } } else if (token.isValue()) { if ("order".equals(topLevelFieldName)) { globalScoreOrdered = "score".equals(parser.text()); } else if ("tags_schema".equals(topLevelFieldName) || "tagsSchema".equals(topLevelFieldName)) { String schema = parser.text(); if ("styled".equals(schema)) { globalPreTags = STYLED_PRE_TAG; globalPostTags = STYLED_POST_TAGS; } } else if ("highlight_filter".equals(topLevelFieldName) || "highlightFilter".equals(topLevelFieldName)) { globalHighlightFilter = parser.booleanValue(); } else if ("fragment_size".equals(topLevelFieldName) || "fragmentSize".equals(topLevelFieldName)) { globalFragmentSize = parser.intValue(); } else if ("number_of_fragments".equals(topLevelFieldName) || "numberOfFragments".equals(topLevelFieldName)) { globalNumOfFragments = parser.intValue(); } else if ("encoder".equals(topLevelFieldName)) { globalEncoder = parser.text(); } else if ("require_field_match".equals(topLevelFieldName) || "requireFieldMatch".equals(topLevelFieldName)) { globalRequireFieldMatch = parser.booleanValue(); } else if ("boundary_max_scan".equals(topLevelFieldName) || "boundaryMaxScan".equals(topLevelFieldName)) { globalBoundaryMaxScan = parser.intValue(); } else if ("boundary_chars".equals(topLevelFieldName) || "boundaryChars".equals(topLevelFieldName)) { char[] charsArr = parser.text().toCharArray(); globalBoundaryChars = new Character[charsArr.length]; for (int i = 0; i < charsArr.length; i++) { globalBoundaryChars[i] = charsArr[i]; } } else if ("type".equals(topLevelFieldName)) { globalHighlighterType = parser.text(); } else if ("fragmenter".equals(topLevelFieldName)) { globalFragmenter = parser.text(); } else if ("no_match_size".equals(topLevelFieldName) || "noMatchSize".equals(topLevelFieldName)) { globalNoMatchSize = parser.intValue(); } else if ("force_source".equals(topLevelFieldName) || "forceSource".equals(topLevelFieldName)) { globalForceSource = parser.booleanValue(); } else if ("phrase_limit".equals(topLevelFieldName) || "phraseLimit".equals(topLevelFieldName)) { globalPhraseLimit = parser.intValue(); } } else if (token == XContentParser.Token.START_OBJECT && "options".equals(topLevelFieldName)) { globalOptions = parser.map(); } else if (token == XContentParser.Token.START_OBJECT) { if ("fields".equals(topLevelFieldName)) { String highlightFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { highlightFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { SearchContextHighlight.Field field = new SearchContextHighlight.Field(highlightFieldName); String fieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { fieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("pre_tags".equals(fieldName) || "preTags".equals(fieldName)) { List<String> preTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { preTagsList.add(parser.text()); } field.preTags(preTagsList.toArray(new String[preTagsList.size()])); } else if ("post_tags".equals(fieldName) || "postTags".equals(fieldName)) { List<String> postTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { postTagsList.add(parser.text()); } field.postTags(postTagsList.toArray(new String[postTagsList.size()])); } else if ("matched_fields".equals(fieldName) || "matchedFields".equals(fieldName)) { Set<String> matchedFields = Sets.newHashSet(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { matchedFields.add(parser.text()); } field.matchedFields(matchedFields); } } else if (token.isValue()) { if ("fragment_size".equals(fieldName) || "fragmentSize".equals(fieldName)) { field.fragmentCharSize(parser.intValue()); } else if ("number_of_fragments".equals(fieldName) || "numberOfFragments".equals(fieldName)) { field.numberOfFragments(parser.intValue()); } else if ("fragment_offset".equals(fieldName) || "fragmentOffset".equals(fieldName)) { field.fragmentOffset(parser.intValue()); } else if ("highlight_filter".equals(fieldName) || "highlightFilter".equals(fieldName)) { field.highlightFilter(parser.booleanValue()); } else if ("order".equals(fieldName)) { field.scoreOrdered("score".equals(parser.text())); } else if ("require_field_match".equals(fieldName) || "requireFieldMatch".equals(fieldName)) { field.requireFieldMatch(parser.booleanValue()); } else if ("boundary_max_scan".equals(topLevelFieldName) || "boundaryMaxScan".equals(topLevelFieldName)) { field.boundaryMaxScan(parser.intValue()); } else if ("boundary_chars".equals(topLevelFieldName) || "boundaryChars".equals(topLevelFieldName)) { char[] charsArr = parser.text().toCharArray(); Character[] boundaryChars = new Character[charsArr.length]; for (int i = 0; i < charsArr.length; i++) { boundaryChars[i] = charsArr[i]; } field.boundaryChars(boundaryChars); } else if ("type".equals(fieldName)) { field.highlighterType(parser.text()); } else if ("fragmenter".equals(fieldName)) { field.fragmenter(parser.text()); } else if ("no_match_size".equals(fieldName) || "noMatchSize".equals(fieldName)) { field.noMatchSize(parser.intValue()); } else if ("force_source".equals(fieldName) || "forceSource".equals(fieldName)) { field.forceSource(parser.booleanValue()); } else if ("phrase_limit".equals(fieldName) || "phraseLimit".equals(fieldName)) { field.phraseLimit(parser.intValue()); } } else if (token == XContentParser.Token.START_OBJECT) { if ("highlight_query".equals(fieldName) || "highlightQuery".equals(fieldName)) { field.highlightQuery(context.queryParserService().parse(parser).query()); } else if (fieldName.equals("options")) { field.options(parser.map()); } } } fields.add(field); } } } else if ("highlight_query".equals(topLevelFieldName) || "highlightQuery".equals(topLevelFieldName)) { globalHighlightQuery = context.queryParserService().parse(parser).query(); } } } if (globalPreTags != null && globalPostTags == null) { throw new SearchParseException(context, "Highlighter global preTags are set, but global postTags are not set"); } // now, go over and fill all fields with default values from the global state for (SearchContextHighlight.Field field : fields) { if (field.preTags() == null) { field.preTags(globalPreTags); } if (field.postTags() == null) { field.postTags(globalPostTags); } if (field.highlightFilter() == null) { field.highlightFilter(globalHighlightFilter); } if (field.scoreOrdered() == null) { field.scoreOrdered(globalScoreOrdered); } if (field.fragmentCharSize() == -1) { field.fragmentCharSize(globalFragmentSize); } if (field.numberOfFragments() == -1) { field.numberOfFragments(globalNumOfFragments); } if (field.encoder() == null) { field.encoder(globalEncoder); } if (field.requireFieldMatch() == null) { field.requireFieldMatch(globalRequireFieldMatch); } if (field.boundaryMaxScan() == -1) { field.boundaryMaxScan(globalBoundaryMaxScan); } if (field.boundaryChars() == null) { field.boundaryChars(globalBoundaryChars); } if (field.highlighterType() == null) { field.highlighterType(globalHighlighterType); } if (field.fragmenter() == null) { field.fragmenter(globalFragmenter); } if (field.options() == null || field.options().size() == 0) { field.options(globalOptions); } if (field.highlightQuery() == null && globalHighlightQuery != null) { field.highlightQuery(globalHighlightQuery); } if (field.noMatchSize() == -1) { field.noMatchSize(globalNoMatchSize); } if (field.forceSource() == null) { field.forceSource(globalForceSource); } if (field.phraseLimit() == -1) { field.phraseLimit(globalPhraseLimit); } } context.highlight(new SearchContextHighlight(fields)); } }
1no label
src_main_java_org_elasticsearch_search_highlight_HighlighterParseElement.java
1,814
constructors[PUT] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new PutOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_map_MapDataSerializerHook.java
235
private static final class ReferencesPresenterControlCreator implements IInformationControlCreator { private CeylonEditor editor; private ReferencesPresenterControlCreator(CeylonEditor editor) { this.editor = editor; } @Override public IInformationControl createInformationControl(Shell parent) { return new ReferencesPopup(parent, getPopupStyle(), editor); } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonSourceViewerConfiguration.java
786
public class MultiPercolateRequest extends ActionRequest<MultiPercolateRequest> { private String[] indices; private String documentType; private IndicesOptions indicesOptions = IndicesOptions.strict(); private List<PercolateRequest> requests = Lists.newArrayList(); public MultiPercolateRequest add(PercolateRequestBuilder requestBuilder) { return add(requestBuilder.request()); } public MultiPercolateRequest add(PercolateRequest request) { if (request.indices() == null && indices != null) { request.indices(indices); } if (request.documentType() == null && documentType != null) { request.documentType(documentType); } if (request.indicesOptions() == IndicesOptions.strict() && indicesOptions != IndicesOptions.strict()) { request.indicesOptions(indicesOptions); } requests.add(request); return this; } public MultiPercolateRequest add(byte[] data, int from, int length, boolean contentUnsafe) throws Exception { return add(new BytesArray(data, from, length), contentUnsafe, true); } public MultiPercolateRequest add(BytesReference data, boolean contentUnsafe, boolean allowExplicitIndex) throws Exception { XContent xContent = XContentFactory.xContent(data); int from = 0; int length = data.length(); byte marker = xContent.streamSeparator(); while (true) { int nextMarker = findNextMarker(marker, from, data, length); if (nextMarker == -1) { break; } // support first line with \n if (nextMarker == 0) { from = nextMarker + 1; continue; } PercolateRequest percolateRequest = new PercolateRequest(); if (indices != null) { percolateRequest.indices(indices); } if (documentType != null) { percolateRequest.documentType(documentType); } if (indicesOptions != IndicesOptions.strict()) { percolateRequest.indicesOptions(indicesOptions); } // now parse the action if (nextMarker - from > 0) { XContentParser parser = xContent.createParser(data.slice(from, nextMarker - from)); try { // Move to START_OBJECT, if token is null, its an empty data XContentParser.Token token = parser.nextToken(); if (token != null) { // Top level json object assert token == XContentParser.Token.START_OBJECT; token = parser.nextToken(); if (token != XContentParser.Token.FIELD_NAME) { throw new ElasticsearchParseException("Expected field"); } token = parser.nextToken(); if (token != XContentParser.Token.START_OBJECT) { throw new ElasticsearchParseException("expected start object"); } String percolateAction = parser.currentName(); if ("percolate".equals(percolateAction)) { parsePercolateAction(parser, percolateRequest, allowExplicitIndex); } else if ("count".equals(percolateAction)) { percolateRequest.onlyCount(true); parsePercolateAction(parser, percolateRequest, allowExplicitIndex); } else { throw new ElasticsearchParseException(percolateAction + " isn't a supported percolate operation"); } } } finally { parser.close(); } } // move pointers from = nextMarker + 1; // now for the body nextMarker = findNextMarker(marker, from, data, length); if (nextMarker == -1) { break; } percolateRequest.source(data.slice(from, nextMarker - from), contentUnsafe); // move pointers from = nextMarker + 1; add(percolateRequest); } return this; } private void parsePercolateAction(XContentParser parser, PercolateRequest percolateRequest, boolean allowExplicitIndex) throws IOException { String globalIndex = indices != null && indices.length > 0 ? indices[0] : null; Map<String, Object> header = new HashMap<String, Object>(); String currentFieldName = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { header.put(currentFieldName, parser.text()); } else if (token == XContentParser.Token.START_ARRAY) { header.put(currentFieldName, parseArray(parser)); } } boolean ignoreUnavailable = IndicesOptions.strict().ignoreUnavailable(); boolean allowNoIndices = IndicesOptions.strict().allowNoIndices(); boolean expandWildcardsOpen = IndicesOptions.strict().expandWildcardsOpen(); boolean expandWildcardsClosed = IndicesOptions.strict().expandWildcardsClosed(); if (header.containsKey("id")) { GetRequest getRequest = new GetRequest(globalIndex); percolateRequest.getRequest(getRequest); for (Map.Entry<String, Object> entry : header.entrySet()) { Object value = entry.getValue(); if ("id".equals(entry.getKey())) { getRequest.id((String) value); header.put("id", entry.getValue()); } else if ("index".equals(entry.getKey()) || "indices".equals(entry.getKey())) { if (!allowExplicitIndex) { throw new ElasticsearchIllegalArgumentException("explicit index in multi percolate is not allowed"); } getRequest.index((String) value); } else if ("type".equals(entry.getKey())) { getRequest.type((String) value); } else if ("preference".equals(entry.getKey())) { getRequest.preference((String) value); } else if ("routing".equals(entry.getKey())) { getRequest.routing((String) value); } else if ("percolate_index".equals(entry.getKey()) || "percolate_indices".equals(entry.getKey()) || "percolateIndex".equals(entry.getKey()) || "percolateIndices".equals(entry.getKey())) { if (value instanceof String[]) { percolateRequest.indices((String[]) value); } else { percolateRequest.indices(Strings.splitStringByCommaToArray((String) value)); } } else if ("percolate_type".equals(entry.getKey()) || "percolateType".equals(entry.getKey())) { percolateRequest.documentType((String) value); } else if ("percolate_preference".equals(entry.getKey()) || "percolatePreference".equals(entry.getKey())) { percolateRequest.preference((String) value); } else if ("percolate_routing".equals(entry.getKey()) || "percolateRouting".equals(entry.getKey())) { percolateRequest.routing((String) value); } else if ("ignore_unavailable".equals(currentFieldName) || "ignoreUnavailable".equals(currentFieldName)) { ignoreUnavailable = Boolean.valueOf((String) value); } else if ("allow_no_indices".equals(currentFieldName) || "allowNoIndices".equals(currentFieldName)) { allowNoIndices = Boolean.valueOf((String) value); } else if ("expand_wildcards".equals(currentFieldName) || "expandWildcards".equals(currentFieldName)) { String[] wildcards; if (value instanceof String[]) { wildcards = (String[]) value; } else { wildcards = Strings.splitStringByCommaToArray((String) value); } for (String wildcard : wildcards) { if ("open".equals(wildcard)) { expandWildcardsOpen = true; } else if ("closed".equals(wildcard)) { expandWildcardsClosed = true; } else { throw new ElasticsearchIllegalArgumentException("No valid expand wildcard value [" + wildcard + "]"); } } } } // Setting values based on get request, if needed... if ((percolateRequest.indices() == null || percolateRequest.indices().length == 0) && getRequest.index() != null) { percolateRequest.indices(getRequest.index()); } if (percolateRequest.documentType() == null && getRequest.type() != null) { percolateRequest.documentType(getRequest.type()); } if (percolateRequest.routing() == null && getRequest.routing() != null) { percolateRequest.routing(getRequest.routing()); } if (percolateRequest.preference() == null && getRequest.preference() != null) { percolateRequest.preference(getRequest.preference()); } } else { for (Map.Entry<String, Object> entry : header.entrySet()) { Object value = entry.getValue(); if ("index".equals(entry.getKey()) || "indices".equals(entry.getKey())) { if (!allowExplicitIndex) { throw new ElasticsearchIllegalArgumentException("explicit index in multi percolate is not allowed"); } if (value instanceof String[]) { percolateRequest.indices((String[]) value); } else { percolateRequest.indices(Strings.splitStringByCommaToArray((String) value)); } } else if ("type".equals(entry.getKey())) { percolateRequest.documentType((String) value); } else if ("preference".equals(entry.getKey())) { percolateRequest.preference((String) value); } else if ("routing".equals(entry.getKey())) { percolateRequest.routing((String) value); } else if ("ignore_unavailable".equals(currentFieldName) || "ignoreUnavailable".equals(currentFieldName)) { ignoreUnavailable = Boolean.valueOf((String) value); } else if ("allow_no_indices".equals(currentFieldName) || "allowNoIndices".equals(currentFieldName)) { allowNoIndices = Boolean.valueOf((String) value); } else if ("expand_wildcards".equals(currentFieldName) || "expandWildcards".equals(currentFieldName)) { String[] wildcards; if (value instanceof String[]) { wildcards = (String[]) value; } else { wildcards = Strings.splitStringByCommaToArray((String) value); } for (String wildcard : wildcards) { if ("open".equals(wildcard)) { expandWildcardsOpen = true; } else if ("closed".equals(wildcard)) { expandWildcardsClosed = true; } else { throw new ElasticsearchIllegalArgumentException("No valid expand wildcard value [" + wildcard + "]"); } } } } } percolateRequest.indicesOptions(IndicesOptions.fromOptions(ignoreUnavailable, allowNoIndices, expandWildcardsOpen, expandWildcardsClosed)); } private String[] parseArray(XContentParser parser) throws IOException { final List<String> list = new ArrayList<String>(); assert parser.currentToken() == XContentParser.Token.START_ARRAY; while (parser.nextToken() != XContentParser.Token.END_ARRAY) { list.add(parser.text()); } return list.toArray(new String[list.size()]); } private int findNextMarker(byte marker, int from, BytesReference data, int length) { for (int i = from; i < length; i++) { if (data.get(i) == marker) { return i; } } return -1; } public List<PercolateRequest> requests() { return this.requests; } public IndicesOptions indicesOptions() { return indicesOptions; } public MultiPercolateRequest indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } public String[] indices() { return indices; } public MultiPercolateRequest indices(String... indices) { this.indices = indices; return this; } public String documentType() { return documentType; } public MultiPercolateRequest documentType(String type) { this.documentType = type; return this; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (requests.isEmpty()) { validationException = addValidationError("no requests added", validationException); } for (int i = 0; i < requests.size(); i++) { ActionRequestValidationException ex = requests.get(i).validate(); if (ex != null) { if (validationException == null) { validationException = new ActionRequestValidationException(); } validationException.addValidationErrors(ex.validationErrors()); } } return validationException; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); indices = in.readStringArray(); documentType = in.readOptionalString(); indicesOptions = IndicesOptions.readIndicesOptions(in); int size = in.readVInt(); for (int i = 0; i < size; i++) { PercolateRequest request = new PercolateRequest(); request.readFrom(in); requests.add(request); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArrayNullable(indices); out.writeOptionalString(documentType); indicesOptions.writeIndicesOptions(out); out.writeVInt(requests.size()); for (PercolateRequest request : requests) { request.writeTo(out); } } }
1no label
src_main_java_org_elasticsearch_action_percolate_MultiPercolateRequest.java
1,954
public final class InternalContext { private Map<Object, ConstructionContext<?>> constructionContexts = Maps.newHashMap(); private Dependency dependency; @SuppressWarnings("unchecked") public <T> ConstructionContext<T> getConstructionContext(Object key) { ConstructionContext<T> constructionContext = (ConstructionContext<T>) constructionContexts.get(key); if (constructionContext == null) { constructionContext = new ConstructionContext<T>(); constructionContexts.put(key, constructionContext); } return constructionContext; } public Dependency getDependency() { return dependency; } public void setDependency(Dependency dependency) { this.dependency = dependency; } }
0true
src_main_java_org_elasticsearch_common_inject_internal_InternalContext.java
280
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientSSLSocketTest { @After @Before public void cleanup() throws Exception { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } @Test @Category(ProblematicTest.class) public void test() throws IOException { Properties props = TestKeyStoreUtil.createSslProperties(); Config cfg = new Config(); cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); cfg.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true).addMember("127.0.0.1"); cfg.getNetworkConfig().setSSLConfig(new SSLConfig().setEnabled(true).setProperties(props)); final HazelcastInstance hz1 = Hazelcast.newHazelcastInstance(cfg); final HazelcastInstance hz2 = Hazelcast.newHazelcastInstance(cfg); ClientConfig config = new ClientConfig(); config.getNetworkConfig().addAddress("127.0.0.1"); config.getNetworkConfig().setRedoOperation(true); config.getNetworkConfig().setSSLConfig(new SSLConfig().setEnabled(true).setProperties(props)); final HazelcastInstance client = HazelcastClient.newHazelcastClient(config); IMap<Object, Object> clientMap = client.getMap("test"); int size = 1000; for (int i = 0; i < size; i++) { Assert.assertNull(clientMap.put(i, 2 * i + 1)); } IMap<Object, Object> map = hz1.getMap("test"); for (int i = 0; i < size; i++) { assertEquals(2 * i + 1, map.get(i)); } } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_io_ClientSSLSocketTest.java
674
constructors[COLLECTION_PREPARE_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new CollectionPrepareBackupOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
628
@SuppressWarnings("unchecked") public abstract class OIndexRemote<T> implements OIndex<T> { private final String wrappedType; private final ORID rid; protected final String databaseName; protected OIndexDefinition indexDefinition; protected String name; protected ODocument configuration; protected Set<String> clustersToIndex; protected final static String QUERY_ENTRIES = "select key, rid from index:%s"; private final static String QUERY_GET_MAJOR = "select from index:%s where key > ?"; private final static String QUERY_GET_MAJOR_EQUALS = "select from index:%s where key >= ?"; private final static String QUERY_GET_VALUE_MAJOR = "select EXPAND( rid ) from index:%s where key > ?"; private final static String QUERY_GET_VALUE_MAJOR_EQUALS = "select EXPAND( rid ) from index:%s where key >= ?"; private final static String QUERY_GET_MINOR = "select from index:%s where key < ?"; private final static String QUERY_GET_MINOR_EQUALS = "select from index:%s where key <= ?"; private final static String QUERY_GET_VALUE_MINOR = "select EXPAND( rid ) from index:%s where key < ?"; private final static String QUERY_GET_VALUE_MINOR_EQUALS = "select EXPAND( rid ) from index:%s where key <= ?"; private final static String QUERY_GET_RANGE = "select from index:%s where key between ? and ?"; private final static String QUERY_GET_VALUES = "select EXPAND( rid ) from index:%s where key in [%s]"; private final static String QUERY_GET_ENTRIES = "select from index:%s where key in [%s]"; private final static String QUERY_GET_VALUE_RANGE = "select EXPAND( rid ) from index:%s where key between ? and ?"; private final static String QUERY_PUT = "insert into index:%s (key,rid) values (?,?)"; private final static String QUERY_REMOVE = "delete from index:%s where key = ?"; private final static String QUERY_REMOVE2 = "delete from index:%s where key = ? and rid = ?"; private final static String QUERY_REMOVE3 = "delete from index:%s where rid = ?"; private final static String QUERY_CONTAINS = "select count(*) as size from index:%s where key = ?"; private final static String QUERY_COUNT = "select count(*) as size from index:%s where key = ?"; private final static String QUERY_COUNT_RANGE = "select count(*) as size from index:%s where "; private final static String QUERY_SIZE = "select count(*) as size from index:%s"; private final static String QUERY_KEY_SIZE = "select count(distinct( key )) as size from index:%s"; private final static String QUERY_KEYS = "select key from index:%s"; private final static String QUERY_REBUILD = "rebuild index %s"; private final static String QUERY_CLEAR = "delete from index:%s"; public static final String QUERY_GET_VALUES_BEETWEN_SELECT = "select from index:%s where "; public static final String QUERY_GET_VALUES_BEETWEN_INCLUSIVE_FROM_CONDITION = "key >= ?"; public static final String QUERY_GET_VALUES_BEETWEN_EXCLUSIVE_FROM_CONDITION = "key > ?"; public static final String QUERY_GET_VALUES_BEETWEN_INCLUSIVE_TO_CONDITION = "key <= ?"; public static final String QUERY_GET_VALUES_BEETWEN_EXCLUSIVE_TO_CONDITION = "key < ?"; public static final String QUERY_GET_VALUES_AND_OPERATOR = " and "; public static final String QUERY_GET_VALUES_LIMIT = " limit "; public OIndexRemote(final String iName, final String iWrappedType, final ORID iRid, final OIndexDefinition iIndexDefinition, final ODocument iConfiguration, final Set<String> clustersToIndex) { this.name = iName; this.wrappedType = iWrappedType; this.rid = iRid; this.indexDefinition = iIndexDefinition; this.configuration = iConfiguration; this.clustersToIndex = new HashSet<String>(clustersToIndex); this.databaseName = ODatabaseRecordThreadLocal.INSTANCE.get().getName(); } public OIndexRemote<T> create(final String name, final OIndexDefinition indexDefinition, final String clusterIndexName, final Set<String> clustersToIndex, boolean rebuild, final OProgressListener progressListener) { this.name = name; return this; } public OIndexRemote<T> delete() { return this; } @Override public void deleteWithoutIndexLoad(String indexName) { throw new UnsupportedOperationException("deleteWithoutIndexLoad"); } public String getDatabaseName() { return databaseName; } public Set<ODocument> getEntriesBetween(final Object iRangeFrom, final Object iRangeTo, final boolean iInclusive) { final OCommandRequest cmd = formatCommand(QUERY_GET_RANGE, name); return getDatabase().command(cmd).execute(iRangeFrom, iRangeTo); } public Collection<OIdentifiable> getValuesBetween(final Object iRangeFrom, final Object iRangeTo) { final OCommandRequest cmd = formatCommand(QUERY_GET_VALUE_RANGE, name); return getDatabase().command(cmd).execute(iRangeFrom, iRangeTo); } public Collection<OIdentifiable> getValuesBetween(final Object iRangeFrom, final boolean iFromInclusive, final Object iRangeTo, final boolean iToInclusive) { final StringBuilder query = new StringBuilder(QUERY_GET_VALUES_BEETWEN_SELECT); if (iFromInclusive) { query.append(QUERY_GET_VALUES_BEETWEN_INCLUSIVE_FROM_CONDITION); } else { query.append(QUERY_GET_VALUES_BEETWEN_EXCLUSIVE_FROM_CONDITION); } query.append(QUERY_GET_VALUES_AND_OPERATOR); if (iToInclusive) { query.append(QUERY_GET_VALUES_BEETWEN_INCLUSIVE_TO_CONDITION); } else { query.append(QUERY_GET_VALUES_BEETWEN_EXCLUSIVE_TO_CONDITION); } final OCommandRequest cmd = formatCommand(query.toString()); return getDatabase().command(cmd).execute(iRangeFrom, iRangeTo); } public Collection<ODocument> getEntriesBetween(final Object iRangeFrom, final Object iRangeTo) { final OCommandRequest cmd = formatCommand(QUERY_GET_RANGE, name); return getDatabase().command(cmd).execute(iRangeFrom, iRangeTo); } public Collection<OIdentifiable> getValuesMajor(final Object fromKey, final boolean isInclusive) { final OCommandRequest cmd; if (isInclusive) cmd = formatCommand(QUERY_GET_VALUE_MAJOR_EQUALS, name); else cmd = formatCommand(QUERY_GET_VALUE_MAJOR, name); return getDatabase().command(cmd).execute(fromKey); } public Collection<ODocument> getEntriesMajor(final Object fromKey, final boolean isInclusive) { final OCommandRequest cmd; if (isInclusive) cmd = formatCommand(QUERY_GET_MAJOR_EQUALS, name); else cmd = formatCommand(QUERY_GET_MAJOR, name); return getDatabase().command(cmd).execute(fromKey); } public Collection<OIdentifiable> getValuesMinor(final Object toKey, final boolean isInclusive) { final OCommandRequest cmd; if (isInclusive) cmd = formatCommand(QUERY_GET_VALUE_MINOR_EQUALS, name); else cmd = formatCommand(QUERY_GET_VALUE_MINOR, name); return getDatabase().command(cmd).execute(toKey); } public Collection<ODocument> getEntriesMinor(final Object toKey, final boolean isInclusive) { final OCommandRequest cmd; if (isInclusive) cmd = formatCommand(QUERY_GET_MINOR_EQUALS, name); else cmd = formatCommand(QUERY_GET_MINOR, name); return getDatabase().command(cmd).execute(toKey); } public boolean contains(final Object iKey) { final OCommandRequest cmd = formatCommand(QUERY_CONTAINS, name); final List<ODocument> result = getDatabase().command(cmd).execute(iKey); return (Long) result.get(0).field("size") > 0; } public long count(final Object iKey) { final OCommandRequest cmd = formatCommand(QUERY_COUNT, name); final List<ODocument> result = getDatabase().command(cmd).execute(iKey); return (Long) result.get(0).field("size"); } @Override public long count(final Object iRangeFrom, final boolean iFromInclusive, final Object iRangeTo, final boolean iToInclusive, final int maxValuesToFetch) { final StringBuilder query = new StringBuilder(QUERY_COUNT_RANGE); if (iFromInclusive) query.append(QUERY_GET_VALUES_BEETWEN_INCLUSIVE_FROM_CONDITION); else query.append(QUERY_GET_VALUES_BEETWEN_EXCLUSIVE_FROM_CONDITION); query.append(QUERY_GET_VALUES_AND_OPERATOR); if (iToInclusive) query.append(QUERY_GET_VALUES_BEETWEN_INCLUSIVE_TO_CONDITION); else query.append(QUERY_GET_VALUES_BEETWEN_EXCLUSIVE_TO_CONDITION); if (maxValuesToFetch > 0) query.append(QUERY_GET_VALUES_LIMIT).append(maxValuesToFetch); final OCommandRequest cmd = formatCommand(query.toString()); return (Long) getDatabase().command(cmd).execute(iRangeFrom, iRangeTo); } public OIndexRemote<T> put(final Object iKey, final OIdentifiable iValue) { if (iValue instanceof ORecord<?> && !iValue.getIdentity().isValid()) // SAVE IT BEFORE TO PUT ((ORecord<?>) iValue).save(); if (iValue.getIdentity().isNew()) throw new OIndexException( "Cannot insert values in manual indexes against remote protocol during a transaction. Temporary RID cannot be managed at server side"); final OCommandRequest cmd = formatCommand(QUERY_PUT, name); getDatabase().command(cmd).execute(iKey, iValue.getIdentity()); return this; } public boolean remove(final Object key) { final OCommandRequest cmd = formatCommand(QUERY_REMOVE, name); return ((Integer) getDatabase().command(cmd).execute(key)) > 0; } public boolean remove(final Object iKey, final OIdentifiable iRID) { final int deleted; if (iRID != null) { if (iRID.getIdentity().isNew()) throw new OIndexException( "Cannot remove values in manual indexes against remote protocol during a transaction. Temporary RID cannot be managed at server side"); final OCommandRequest cmd = formatCommand(QUERY_REMOVE2, name); deleted = (Integer) getDatabase().command(cmd).execute(iKey, iRID); } else { final OCommandRequest cmd = formatCommand(QUERY_REMOVE, name); deleted = (Integer) getDatabase().command(cmd).execute(iKey); } return deleted > 0; } public int remove(final OIdentifiable iRecord) { final OCommandRequest cmd = formatCommand(QUERY_REMOVE3, name, iRecord.getIdentity()); return (Integer) getDatabase().command(cmd).execute(iRecord); } public void automaticRebuild() { throw new UnsupportedOperationException("autoRebuild()"); } public long rebuild() { final OCommandRequest cmd = formatCommand(QUERY_REBUILD, name); return (Long) getDatabase().command(cmd).execute(); } public OIndexRemote<T> clear() { final OCommandRequest cmd = formatCommand(QUERY_CLEAR, name); getDatabase().command(cmd).execute(); return this; } public Iterable<Object> keys() { final OCommandRequest cmd = formatCommand(QUERY_KEYS, name); return (Iterable<Object>) getDatabase().command(cmd).execute(); } public long getSize() { final OCommandRequest cmd = formatCommand(QUERY_SIZE, name); final List<ODocument> result = getDatabase().command(cmd).execute(); return (Long) result.get(0).field("size"); } public long getKeySize() { final OCommandRequest cmd = formatCommand(QUERY_KEY_SIZE, name); final List<ODocument> result = getDatabase().command(cmd).execute(); return (Long) result.get(0).field("size"); } public void unload() { } public boolean isAutomatic() { return indexDefinition != null && indexDefinition.getClassName() != null; } public String getName() { return name; } @Override public void flush() { } public String getType() { return wrappedType; } public ODocument getConfiguration() { return configuration; } public ORID getIdentity() { return rid; } protected OCommandRequest formatCommand(final String iTemplate, final Object... iArgs) { final String text = String.format(iTemplate, iArgs); return new OCommandSQL(text); } public void commit(final ODocument iDocument) { } public OIndexInternal<T> getInternal() { return null; } protected ODatabaseComplex<ORecordInternal<?>> getDatabase() { return ODatabaseRecordThreadLocal.INSTANCE.get(); } public long rebuild(final OProgressListener iProgressListener) { return rebuild(); } public OType[] getKeyTypes() { if (indexDefinition != null) return indexDefinition.getTypes(); return null; } public Collection<OIdentifiable> getValues(final Collection<?> iKeys) { final StringBuilder params = new StringBuilder(); if (!iKeys.isEmpty()) { params.append("?"); for (int i = 1; i < iKeys.size(); i++) { params.append(", ?"); } } final OCommandRequest cmd = formatCommand(QUERY_GET_VALUES, name, params.toString()); return (Collection<OIdentifiable>) getDatabase().command(cmd).execute(iKeys.toArray()); } public Collection<ODocument> getEntries(final Collection<?> iKeys) { final StringBuilder params = new StringBuilder(); if (!iKeys.isEmpty()) { params.append("?"); for (int i = 1; i < iKeys.size(); i++) { params.append(", ?"); } } final OCommandRequest cmd = formatCommand(QUERY_GET_ENTRIES, name, params.toString()); return (Collection<ODocument>) getDatabase().command(cmd).execute(iKeys.toArray()); } public OIndexDefinition getDefinition() { return indexDefinition; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final OIndexRemote<?> that = (OIndexRemote<?>) o; return name.equals(that.name); } @Override public int hashCode() { return name.hashCode(); } @Override public void getValuesBetween(Object iRangeFrom, boolean iFromInclusive, Object iRangeTo, boolean iToInclusive, IndexValuesResultListener resultListener) { Collection<OIdentifiable> result = getValuesBetween(iRangeFrom, iFromInclusive, iRangeTo, iToInclusive, -1); addValues(resultListener, result); } private void addValues(IndexValuesResultListener resultListener, Collection<OIdentifiable> result) { for (OIdentifiable identifiable : result) if (!resultListener.addResult(identifiable)) break; } @Override public void getValuesMajor(Object fromKey, boolean isInclusive, IndexValuesResultListener resultListener) { Collection<OIdentifiable> result = getValuesMajor(fromKey, isInclusive); addValues(resultListener, result); } @Override public void getValuesMinor(Object toKey, boolean isInclusive, IndexValuesResultListener valuesResultListener) { Collection<OIdentifiable> result = getValuesMinor(toKey, isInclusive); addValues(valuesResultListener, result); } @Override public void getEntriesMajor(Object fromKey, boolean isInclusive, IndexEntriesResultListener entriesResultListener) { Collection<ODocument> result = getEntriesMajor(fromKey, isInclusive); addEntries(entriesResultListener, result); } private void addEntries(IndexEntriesResultListener entriesResultListener, Collection<ODocument> result) { for (ODocument entry : result) if (!entriesResultListener.addResult(entry)) break; } @Override public void getEntriesMinor(Object toKey, boolean isInclusive, IndexEntriesResultListener entriesResultListener) { Collection<ODocument> result = getEntriesMinor(toKey, isInclusive); addEntries(entriesResultListener, result); } @Override public void getEntriesBetween(Object iRangeFrom, Object iRangeTo, boolean iInclusive, IndexEntriesResultListener entriesResultListener) { Collection<ODocument> result = getEntriesBetween(iRangeFrom, iRangeTo, iInclusive); addEntries(entriesResultListener, result); } public Collection<OIdentifiable> getValuesBetween(final Object iRangeFrom, final boolean iFromInclusive, final Object iRangeTo, final boolean iToInclusive, final int maxValuesToFetch) { if (maxValuesToFetch < 0) return getValuesBetween(iRangeFrom, iFromInclusive, iRangeTo, iToInclusive); final StringBuilder query = new StringBuilder(QUERY_GET_VALUES_BEETWEN_SELECT); if (iFromInclusive) { query.append(QUERY_GET_VALUES_BEETWEN_INCLUSIVE_FROM_CONDITION); } else { query.append(QUERY_GET_VALUES_BEETWEN_EXCLUSIVE_FROM_CONDITION); } query.append(QUERY_GET_VALUES_AND_OPERATOR); if (iToInclusive) { query.append(QUERY_GET_VALUES_BEETWEN_INCLUSIVE_TO_CONDITION); } else { query.append(QUERY_GET_VALUES_BEETWEN_EXCLUSIVE_TO_CONDITION); } query.append(QUERY_GET_VALUES_LIMIT).append(maxValuesToFetch); final OCommandRequest cmd = formatCommand(query.toString()); return getDatabase().command(cmd).execute(iRangeFrom, iRangeTo); } public Collection<OIdentifiable> getValuesMajor(final Object fromKey, final boolean isInclusive, final int maxValuesToFetch) { if (maxValuesToFetch < 0) return getValuesMajor(fromKey, isInclusive); final OCommandRequest cmd; if (isInclusive) cmd = formatCommand(QUERY_GET_VALUE_MAJOR_EQUALS + QUERY_GET_VALUES_LIMIT + maxValuesToFetch, name); else cmd = formatCommand(QUERY_GET_VALUE_MAJOR + QUERY_GET_VALUES_LIMIT + maxValuesToFetch, name); return (Collection<OIdentifiable>) getDatabase().command(cmd).execute(fromKey); } public Collection<OIdentifiable> getValuesMinor(final Object toKey, final boolean isInclusive, final int maxValuesToFetch) { if (maxValuesToFetch < 0) return getValuesMinor(toKey, isInclusive); final OCommandRequest cmd; if (isInclusive) cmd = formatCommand(QUERY_GET_VALUE_MINOR_EQUALS + QUERY_GET_VALUES_LIMIT + maxValuesToFetch, name); else cmd = formatCommand(QUERY_GET_VALUE_MINOR + QUERY_GET_VALUES_LIMIT + maxValuesToFetch, name); return (Collection<OIdentifiable>) getDatabase().command(cmd).execute(toKey); } public Collection<ODocument> getEntriesMajor(final Object fromKey, final boolean isInclusive, final int maxEntriesToFetch) { if (maxEntriesToFetch < 0) return getEntriesMajor(fromKey, isInclusive); final OCommandRequest cmd; if (isInclusive) cmd = formatCommand(QUERY_GET_MAJOR_EQUALS + QUERY_GET_VALUES_LIMIT + maxEntriesToFetch, name); else cmd = formatCommand(QUERY_GET_MAJOR + QUERY_GET_VALUES_LIMIT + maxEntriesToFetch, name); return (Collection<ODocument>) getDatabase().command(cmd).execute(fromKey); } public Collection<ODocument> getEntriesMinor(final Object toKey, final boolean isInclusive, final int maxEntriesToFetch) { if (maxEntriesToFetch < 0) return getEntriesMinor(toKey, isInclusive); final OCommandRequest cmd; if (isInclusive) cmd = formatCommand(QUERY_GET_MINOR_EQUALS + QUERY_GET_VALUES_LIMIT + maxEntriesToFetch, name); else cmd = formatCommand(QUERY_GET_MINOR + QUERY_GET_VALUES_LIMIT + maxEntriesToFetch, name); return (Collection<ODocument>) getDatabase().command(cmd).execute(toKey); } public Collection<ODocument> getEntriesBetween(final Object iRangeFrom, final Object iRangeTo, final boolean iInclusive, final int maxEntriesToFetch) { if (maxEntriesToFetch < 0) return getEntriesBetween(iRangeFrom, iRangeTo, iInclusive); final OCommandRequest cmd = formatCommand(QUERY_GET_RANGE + QUERY_GET_VALUES_LIMIT + maxEntriesToFetch, name); return (Set<ODocument>) getDatabase().command(cmd).execute(iRangeFrom, iRangeTo); } @Override public void getValues(Collection<?> iKeys, IndexValuesResultListener resultListener) { Collection<OIdentifiable> result = getValues(iKeys); addValues(resultListener, result); } public Collection<OIdentifiable> getValues(final Collection<?> iKeys, final int maxValuesToFetch) { if (maxValuesToFetch < 0) return getValues(iKeys); final StringBuilder params = new StringBuilder(); if (!iKeys.isEmpty()) { params.append("?"); for (int i = 1; i < iKeys.size(); i++) { params.append(", ?"); } } final OCommandRequest cmd = formatCommand(QUERY_GET_VALUES + QUERY_GET_VALUES_LIMIT + maxValuesToFetch, name, params.toString()); return (Collection<OIdentifiable>) getDatabase().command(cmd).execute(iKeys.toArray()); } @Override public void getEntries(final Collection<?> iKeys, IndexEntriesResultListener resultListener) { final Collection<ODocument> result = getEntries(iKeys); addEntries(resultListener, result); } public Collection<ODocument> getEntries(final Collection<?> iKeys, int maxEntriesToFetch) { if (maxEntriesToFetch < 0) return getEntries(iKeys); final StringBuilder params = new StringBuilder(); if (!iKeys.isEmpty()) { params.append("?"); for (int i = 1; i < iKeys.size(); i++) { params.append(", ?"); } } final OCommandRequest cmd = formatCommand(QUERY_GET_ENTRIES + QUERY_GET_VALUES_LIMIT + maxEntriesToFetch, name, params.toString()); return getDatabase().command(cmd).execute(iKeys.toArray()); } public Set<String> getClusters() { return Collections.unmodifiableSet(clustersToIndex); } public void checkEntry(final OIdentifiable iRecord, final Object iKey) { } @Override public boolean isRebuiding() { return false; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_index_OIndexRemote.java
1,278
public interface RatingSummary { public Long getId(); public void setId(Long id); public RatingType getRatingType(); public void setRatingType(RatingType ratingType); public String getItemId(); public void setItemId(String itemId); public Integer getNumberOfRatings(); public Integer getNumberOfReviews(); public Double getAverageRating(); public void resetAverageRating(); public List<ReviewDetail> getReviews(); public void setReviews(List<ReviewDetail> reviews); public List<RatingDetail> getRatings(); public void setRatings(List<RatingDetail> ratings); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_rating_domain_RatingSummary.java
1,774
public class CircleBuilder extends ShapeBuilder { public static final String FIELD_RADIUS = "radius"; public static final GeoShapeType TYPE = GeoShapeType.CIRCLE; private DistanceUnit unit; private double radius; private Coordinate center; /** * Set the center of the circle * * @param center coordinate of the circles center * @return this */ public CircleBuilder center(Coordinate center) { this.center = center; return this; } /** * set the center of the circle * @param lon longitude of the center * @param lat latitude of the center * @return this */ public CircleBuilder center(double lon, double lat) { return center(new Coordinate(lon, lat)); } /** * Set the radius of the circle. The String value will be parsed by {@link DistanceUnit} * @param radius Value and unit of the circle combined in a string * @return this */ public CircleBuilder radius(String radius) { return radius(DistanceUnit.Distance.parseDistance(radius)); } /** * Set the radius of the circle * @param radius radius of the circle (see {@link DistanceUnit.Distance}) * @return this */ public CircleBuilder radius(Distance radius) { return radius(radius.value, radius.unit); } /** * Set the radius of the circle * @param radius value of the circles radius * @param unit unit name of the radius value (see {@link DistanceUnit}) * @return this */ public CircleBuilder radius(double radius, String unit) { return radius(radius, DistanceUnit.fromString(unit)); } /** * Set the radius of the circle * @param radius value of the circles radius * @param unit unit of the radius value (see {@link DistanceUnit}) * @return this */ public CircleBuilder radius(double radius, DistanceUnit unit) { this.unit = unit; this.radius = radius; return this; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(FIELD_TYPE, TYPE.shapename); builder.field(FIELD_RADIUS, unit.toString(radius)); builder.field(FIELD_COORDINATES); toXContent(builder, center); return builder.endObject(); } @Override public Circle build() { return SPATIAL_CONTEXT.makeCircle(center.x, center.y, 180 * radius / unit.getEarthCircumference()); } @Override public GeoShapeType type() { return TYPE; } }
0true
src_main_java_org_elasticsearch_common_geo_builders_CircleBuilder.java
3,692
public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { TTLFieldMapper.Builder builder = ttl(); parseField(builder, builder.name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("enabled")) { EnabledAttributeMapper enabledState = nodeBooleanValue(fieldNode) ? EnabledAttributeMapper.ENABLED : EnabledAttributeMapper.DISABLED; builder.enabled(enabledState); } else if (fieldName.equals("default")) { TimeValue ttlTimeValue = nodeTimeValue(fieldNode, null); if (ttlTimeValue != null) { builder.defaultTTL(ttlTimeValue.millis()); } } } return builder; } }
0true
src_main_java_org_elasticsearch_index_mapper_internal_TTLFieldMapper.java
1,944
new Converter<Member>(Member.class) { public String toString(Member member) { return MoreTypes.toString(member); } },
0true
src_main_java_org_elasticsearch_common_inject_internal_Errors.java
372
@PreInitializeConfigOptions public class HBaseStoreManager extends DistributedStoreManager implements KeyColumnValueStoreManager, CustomizeStoreKCVSManager { private static final Logger logger = LoggerFactory.getLogger(HBaseStoreManager.class); public static final ConfigNamespace HBASE_NS = new ConfigNamespace(GraphDatabaseConfiguration.STORAGE_NS, "hbase", "HBase storage options"); public static final ConfigOption<Boolean> SHORT_CF_NAMES = new ConfigOption<Boolean>(HBASE_NS, "short-cf-names", "Whether to shorten the names of Titan's column families to one-character mnemonics " + "to conserve storage space", ConfigOption.Type.FIXED, true); public static final String COMPRESSION_DEFAULT = "-DEFAULT-"; public static final ConfigOption<String> COMPRESSION = new ConfigOption<String>(HBASE_NS, "compression-algorithm", "An HBase Compression.Algorithm enum string which will be applied to newly created column families. " + "The compression algorithm must be installed and available on the HBase cluster. Titan cannot install " + "and configure new compression algorithms on the HBase cluster by itself.", ConfigOption.Type.MASKABLE, "GZ"); public static final ConfigOption<Boolean> SKIP_SCHEMA_CHECK = new ConfigOption<Boolean>(HBASE_NS, "skip-schema-check", "Assume that Titan's HBase table and column families already exist. " + "When this is true, Titan will not check for the existence of its table/CFs, " + "nor will it attempt to create them under any circumstances. This is useful " + "when running Titan without HBase admin privileges.", ConfigOption.Type.MASKABLE, false); public static final ConfigOption<String> HBASE_TABLE = new ConfigOption<String>(HBASE_NS, "table", "The name of the table Titan will use. When " + ConfigElement.getPath(SKIP_SCHEMA_CHECK) + " is false, Titan will automatically create this table if it does not already exist.", ConfigOption.Type.LOCAL, "titan"); /** * Related bug fixed in 0.98.0, 0.94.7, 0.95.0: * * https://issues.apache.org/jira/browse/HBASE-8170 */ public static final int MIN_REGION_COUNT = 3; /** * The total number of HBase regions to create with Titan's table. This * setting only effects table creation; this normally happens just once when * Titan connects to an HBase backend for the first time. */ public static final ConfigOption<Integer> REGION_COUNT = new ConfigOption<Integer>(HBASE_NS, "region-count", "The number of initial regions set when creating Titan's HBase table", ConfigOption.Type.MASKABLE, Integer.class, new Predicate<Integer>() { @Override public boolean apply(Integer input) { return null != input && MIN_REGION_COUNT <= input; } } ); /** * This setting is used only when {@link #REGION_COUNT} is unset. * <p/> * If Titan's HBase table does not exist, then it will be created with total * region count = (number of servers reported by ClusterStatus) * (this * value). * <p/> * The Apache HBase manual suggests an order-of-magnitude range of potential * values for this setting: * * <ul> * <li> * <a href="https://hbase.apache.org/book/important_configurations.html#disable.splitting">2.5.2.7. Managed Splitting</a>: * <blockquote> * What's the optimal number of pre-split regions to create? Mileage will * vary depending upon your application. You could start low with 10 * pre-split regions / server and watch as data grows over time. It's * better to err on the side of too little regions and rolling split later. * </blockquote> * </li> * <li> * <a href="https://hbase.apache.org/book/regions.arch.html">9.7 Regions</a>: * <blockquote> * In general, HBase is designed to run with a small (20-200) number of * relatively large (5-20Gb) regions per server... Typically you want to * keep your region count low on HBase for numerous reasons. Usually * right around 100 regions per RegionServer has yielded the best results. * </blockquote> * </li> * </ul> * * These considerations may differ for other HBase implementations (e.g. MapR). */ public static final ConfigOption<Integer> REGIONS_PER_SERVER = new ConfigOption<Integer>(HBASE_NS, "regions-per-server", "The number of regions per regionserver to set when creating Titan's HBase table", ConfigOption.Type.MASKABLE, Integer.class); /** * If this key is present in either the JVM system properties or the process * environment (checked in the listed order, first hit wins), then its value * must be the full package and class name of an implementation of * {@link HBaseCompat} that has a no-arg public constructor. * <p> * When this <b>is not</b> set, Titan attempts to automatically detect the * HBase runtime version by calling {@link VersionInfo#getVersion()}. Titan * then checks the returned version string against a hard-coded list of * supported version prefixes and instantiates the associated compat layer * if a match is found. * <p> * When this <b>is</b> set, Titan will not call * {@code VersionInfo.getVersion()} or read its hard-coded list of supported * version prefixes. Titan will instead attempt to instantiate the class * specified (via the no-arg constructor which must exist) and then attempt * to cast it to HBaseCompat and use it as such. Titan will assume the * supplied implementation is compatible with the runtime HBase version and * make no attempt to verify that assumption. * <p> * Setting this key incorrectly could cause runtime exceptions at best or * silent data corruption at worst. This setting is intended for users * running exotic HBase implementations that don't support VersionInfo or * implementations which return values from {@code VersionInfo.getVersion()} * that are inconsistent with Apache's versioning convention. It may also be * useful to users who want to run against a new release of HBase that Titan * doesn't yet officially support. * */ public static final ConfigOption<String> COMPAT_CLASS = new ConfigOption<String>(HBASE_NS, "compat-class", "The package and class name of the HBaseCompat implementation. HBaseCompat masks version-specific HBase API differences. " + "When this option is unset, Titan calls HBase's VersionInfo.getVersion() and loads the matching compat class " + "at runtime. Setting this option forces Titan to instead reflectively load and instantiate the specified class.", ConfigOption.Type.MASKABLE, String.class); public static final int PORT_DEFAULT = 9160; public static final Timestamps PREFERRED_TIMESTAMPS = Timestamps.MILLI; public static final ConfigNamespace HBASE_CONFIGURATION_NAMESPACE = new ConfigNamespace(HBASE_NS, "ext", "Overrides for hbase-{site,default}.xml options", true); private static final BiMap<String, String> SHORT_CF_NAME_MAP = ImmutableBiMap.<String, String>builder() .put(INDEXSTORE_NAME, "g") .put(INDEXSTORE_NAME + LOCK_STORE_SUFFIX, "h") .put(ID_STORE_NAME, "i") .put(EDGESTORE_NAME, "e") .put(EDGESTORE_NAME + LOCK_STORE_SUFFIX, "f") .put(SYSTEM_PROPERTIES_STORE_NAME, "s") .put(SYSTEM_PROPERTIES_STORE_NAME + LOCK_STORE_SUFFIX, "t") .put(SYSTEM_MGMT_LOG_NAME, "m") .put(SYSTEM_TX_LOG_NAME, "l") .build(); private static final StaticBuffer FOUR_ZERO_BYTES = BufferUtil.zeroBuffer(4); static { // Verify that shortCfNameMap is injective // Should be guaranteed by Guava BiMap, but it doesn't hurt to check Preconditions.checkArgument(null != SHORT_CF_NAME_MAP); Collection<String> shorts = SHORT_CF_NAME_MAP.values(); Preconditions.checkArgument(Sets.newHashSet(shorts).size() == shorts.size()); } // Immutable instance fields private final String tableName; private final String compression; private final int regionCount; private final int regionsPerServer; private final HConnection cnx; private final org.apache.hadoop.conf.Configuration hconf; private final boolean shortCfNames; private final boolean skipSchemaCheck; private final String compatClass; private final HBaseCompat compat; private static final ConcurrentHashMap<HBaseStoreManager, Throwable> openManagers = new ConcurrentHashMap<HBaseStoreManager, Throwable>(); // Mutable instance state private final ConcurrentMap<String, HBaseKeyColumnValueStore> openStores; public HBaseStoreManager(com.thinkaurelius.titan.diskstorage.configuration.Configuration config) throws BackendException { super(config, PORT_DEFAULT); checkConfigDeprecation(config); this.tableName = config.get(HBASE_TABLE); this.compression = config.get(COMPRESSION); this.regionCount = config.has(REGION_COUNT) ? config.get(REGION_COUNT) : -1; this.regionsPerServer = config.has(REGIONS_PER_SERVER) ? config.get(REGIONS_PER_SERVER) : -1; this.skipSchemaCheck = config.get(SKIP_SCHEMA_CHECK); this.compatClass = config.has(COMPAT_CLASS) ? config.get(COMPAT_CLASS) : null; this.compat = HBaseCompatLoader.getCompat(compatClass); /* * Specifying both region count options is permitted but may be * indicative of a misunderstanding, so issue a warning. */ if (config.has(REGIONS_PER_SERVER) && config.has(REGION_COUNT)) { logger.warn("Both {} and {} are set in Titan's configuration, but " + "the former takes precedence and the latter will be ignored.", REGION_COUNT, REGIONS_PER_SERVER); } /* This static factory calls HBaseConfiguration.addHbaseResources(), * which in turn applies the contents of hbase-default.xml and then * applies the contents of hbase-site.xml. */ this.hconf = HBaseConfiguration.create(); // Copy a subset of our commons config into a Hadoop config int keysLoaded=0; Map<String,Object> configSub = config.getSubset(HBASE_CONFIGURATION_NAMESPACE); for (Map.Entry<String,Object> entry : configSub.entrySet()) { logger.info("HBase configuration: setting {}={}", entry.getKey(), entry.getValue()); if (entry.getValue()==null) continue; hconf.set(entry.getKey(), entry.getValue().toString()); keysLoaded++; } // Special case for STORAGE_HOSTS if (config.has(GraphDatabaseConfiguration.STORAGE_HOSTS)) { String zkQuorumKey = "hbase.zookeeper.quorum"; String csHostList = Joiner.on(",").join(config.get(GraphDatabaseConfiguration.STORAGE_HOSTS)); hconf.set(zkQuorumKey, csHostList); logger.info("Copied host list from {} to {}: {}", GraphDatabaseConfiguration.STORAGE_HOSTS, zkQuorumKey, csHostList); } logger.debug("HBase configuration: set a total of {} configuration values", keysLoaded); this.shortCfNames = config.get(SHORT_CF_NAMES); try { this.cnx = HConnectionManager.createConnection(hconf); } catch (ZooKeeperConnectionException e) { throw new PermanentBackendException(e); } catch (@SuppressWarnings("hiding") IOException e) { // not thrown in 0.94, but thrown in 0.96+ throw new PermanentBackendException(e); } if (logger.isTraceEnabled()) { openManagers.put(this, new Throwable("Manager Opened")); dumpOpenManagers(); } logger.debug("Dumping HBase config key=value pairs"); for (Map.Entry<String, String> entry : hconf) { logger.debug("[HBaseConfig] " + entry.getKey() + "=" + entry.getValue()); } logger.debug("End of HBase config key=value pairs"); openStores = new ConcurrentHashMap<String, HBaseKeyColumnValueStore>(); } @Override public Deployment getDeployment() { List<KeyRange> local; try { local = getLocalKeyPartition(); return null != local && !local.isEmpty() ? Deployment.LOCAL : Deployment.REMOTE; } catch (BackendException e) { // propagating StorageException might be a better approach throw new RuntimeException(e); } } @Override public String toString() { return "hbase[" + tableName + "@" + super.toString() + "]"; } public void dumpOpenManagers() { int estimatedSize = openManagers.size(); logger.trace("---- Begin open HBase store manager list ({} managers) ----", estimatedSize); for (HBaseStoreManager m : openManagers.keySet()) { logger.trace("Manager {} opened at:", m, openManagers.get(m)); } logger.trace("---- End open HBase store manager list ({} managers) ----", estimatedSize); } @Override public void close() { openStores.clear(); if (logger.isTraceEnabled()) openManagers.remove(this); IOUtils.closeQuietly(cnx); } @Override public StoreFeatures getFeatures() { Configuration c = GraphDatabaseConfiguration.buildConfiguration(); StandardStoreFeatures.Builder fb = new StandardStoreFeatures.Builder() .orderedScan(true).unorderedScan(true).batchMutation(true) .multiQuery(true).distributed(true).keyOrdered(true).storeTTL(true) .timestamps(true).preferredTimestamps(PREFERRED_TIMESTAMPS) .keyConsistent(c); try { fb.localKeyPartition(getDeployment() == Deployment.LOCAL); } catch (Exception e) { logger.warn("Unexpected exception during getDeployment()", e); } return fb.build(); } @Override public void mutateMany(Map<String, Map<StaticBuffer, KCVMutation>> mutations, StoreTransaction txh) throws BackendException { final MaskedTimestamp commitTime = new MaskedTimestamp(txh); // In case of an addition and deletion with identical timestamps, the // deletion tombstone wins. // http://hbase.apache.org/book/versions.html#d244e4250 Map<StaticBuffer, Pair<Put, Delete>> commandsPerKey = convertToCommands( mutations, commitTime.getAdditionTime(times.getUnit()), commitTime.getDeletionTime(times.getUnit())); List<Row> batch = new ArrayList<Row>(commandsPerKey.size()); // actual batch operation // convert sorted commands into representation required for 'batch' operation for (Pair<Put, Delete> commands : commandsPerKey.values()) { if (commands.getFirst() != null) batch.add(commands.getFirst()); if (commands.getSecond() != null) batch.add(commands.getSecond()); } try { HTableInterface table = null; try { table = cnx.getTable(tableName); table.batch(batch); table.flushCommits(); } finally { IOUtils.closeQuietly(table); } } catch (IOException e) { throw new TemporaryBackendException(e); } catch (InterruptedException e) { throw new TemporaryBackendException(e); } sleepAfterWrite(txh, commitTime); } @Override public KeyColumnValueStore openDatabase(String longName) throws BackendException { return openDatabase(longName, -1); } @Override public KeyColumnValueStore openDatabase(final String longName, int ttlInSeconds) throws BackendException { HBaseKeyColumnValueStore store = openStores.get(longName); if (store == null) { final String cfName = shortCfNames ? shortenCfName(longName) : longName; HBaseKeyColumnValueStore newStore = new HBaseKeyColumnValueStore(this, cnx, tableName, cfName, longName); store = openStores.putIfAbsent(longName, newStore); // nothing bad happens if we loose to other thread if (store == null) { if (!skipSchemaCheck) ensureColumnFamilyExists(tableName, cfName, ttlInSeconds); store = newStore; } } return store; } @Override public StoreTransaction beginTransaction(final BaseTransactionConfig config) throws BackendException { return new HBaseTransaction(config); } @Override public String getName() { return tableName; } /** * Deletes the specified table with all its columns. * ATTENTION: Invoking this method will delete the table if it exists and therefore causes data loss. */ @Override public void clearStorage() throws BackendException { HBaseAdmin adm = null; try { // first of all, check if table exists, if not - we are done adm = getAdminInterface(); if (!adm.tableExists(tableName)) { logger.debug("clearStorage() called before table {} was created, skipping.", tableName); return; } } catch (IOException e) { throw new TemporaryBackendException(e); } finally { IOUtils.closeQuietly(adm); } // long before = System.currentTimeMillis(); // try { // adm.disableTable(tableName); // adm.deleteTable(tableName); // } catch (IOException e) { // throw new PermanentBackendException(e); // } // ensureTableExists(tableName, getCfNameForStoreName(GraphDatabaseConfiguration.SYSTEM_PROPERTIES_STORE_NAME), 0); // long after = System.currentTimeMillis(); // logger.debug("Dropped and recreated table {} in {} ms", tableName, after - before); HTable table = null; try { table = new HTable(hconf, tableName); Scan scan = new Scan(); scan.setBatch(100); scan.setCacheBlocks(false); scan.setCaching(2000); scan.setTimeRange(0, Long.MAX_VALUE); scan.setMaxVersions(1); ResultScanner scanner = null; long timestamp = times.getTime().getNativeTimestamp(); try { scanner = table.getScanner(scan); for (Result res : scanner) { Delete d = new Delete(res.getRow()); d.setTimestamp(timestamp); table.delete(d); } } finally { IOUtils.closeQuietly(scanner); } } catch (IOException e) { throw new TemporaryBackendException(e); } finally { IOUtils.closeQuietly(table); } } @Override public List<KeyRange> getLocalKeyPartition() throws BackendException { List<KeyRange> result = new LinkedList<KeyRange>(); HTable table = null; try { ensureTableExists(tableName, getCfNameForStoreName(GraphDatabaseConfiguration.SYSTEM_PROPERTIES_STORE_NAME), 0); table = new HTable(hconf, tableName); Map<KeyRange, ServerName> normed = normalizeKeyBounds(table.getRegionLocations()); for (Map.Entry<KeyRange, ServerName> e : normed.entrySet()) { if (NetworkUtil.isLocalConnection(e.getValue().getHostname())) { result.add(e.getKey()); logger.debug("Found local key/row partition {} on host {}", e.getKey(), e.getValue()); } else { logger.debug("Discarding remote {}", e.getValue()); } } } catch (MasterNotRunningException e) { logger.warn("Unexpected MasterNotRunningException", e); } catch (ZooKeeperConnectionException e) { logger.warn("Unexpected ZooKeeperConnectionException", e); } catch (IOException e) { logger.warn("Unexpected IOException", e); } finally { IOUtils.closeQuietly(table); } return result; } /** * Given a map produced by {@link HTable#getRegionLocations()}, transform * each key from an {@link HRegionInfo} to a {@link KeyRange} expressing the * region's start and end key bounds using Titan-partitioning-friendly * conventions (start inclusive, end exclusive, zero bytes appended where * necessary to make all keys at least 4 bytes long). * <p/> * This method iterates over the entries in its map parameter and performs * the following conditional conversions on its keys. "Require" below means * either a {@link Preconditions} invocation or an assertion. HRegionInfo * sometimes returns start and end keys of zero length; this method replaces * zero length keys with null before doing any of the checks described * below. The parameter map and the values it contains are only read and * never modified. * * <ul> * <li>If an entry's HRegionInfo has null start and end keys, then first * require that the parameter map is a singleton, and then return a * single-entry map whose {@code KeyRange} has start and end buffers that * are both four bytes of zeros.</li> * <li>If the entry has a null end key (but non-null start key), put an * equivalent entry in the result map with a start key identical to the * input, except that zeros are appended to values less than 4 bytes long, * and an end key that is four bytes of zeros. * <li>If the entry has a null start key (but non-null end key), put an * equivalent entry in the result map where the start key is four bytes of * zeros, and the end key has zeros appended, if necessary, to make it at * least 4 bytes long, after which one is added to the padded value in * unsigned 32-bit arithmetic with overflow allowed.</li> * <li>Any entry which matches none of the above criteria results in an * equivalent entry in the returned map, except that zeros are appended to * both keys to make each at least 4 bytes long, and the end key is then * incremented as described in the last bullet point.</li> * </ul> * * After iterating over the parameter map, this method checks that it either * saw no entries with null keys, one entry with a null start key and a * different entry with a null end key, or one entry with both start and end * keys null. If any null keys are observed besides these three cases, the * method will die with a precondition failure. * * @param raw * A map of HRegionInfo and ServerName from HBase * @return Titan-friendly expression of each region's rowkey boundaries */ private Map<KeyRange, ServerName> normalizeKeyBounds(NavigableMap<HRegionInfo, ServerName> raw) { Map.Entry<HRegionInfo, ServerName> nullStart = null; Map.Entry<HRegionInfo, ServerName> nullEnd = null; ImmutableMap.Builder<KeyRange, ServerName> b = ImmutableMap.builder(); for (Map.Entry<HRegionInfo, ServerName> e : raw.entrySet()) { HRegionInfo regionInfo = e.getKey(); byte startKey[] = regionInfo.getStartKey(); byte endKey[] = regionInfo.getEndKey(); if (0 == startKey.length) { startKey = null; logger.trace("Converted zero-length HBase startKey byte array to null"); } if (0 == endKey.length) { endKey = null; logger.trace("Converted zero-length HBase endKey byte array to null"); } if (null == startKey && null == endKey) { Preconditions.checkState(1 == raw.size()); logger.debug("HBase table {} has a single region {}", tableName, regionInfo); // Choose arbitrary shared value = startKey = endKey return b.put(new KeyRange(FOUR_ZERO_BYTES, FOUR_ZERO_BYTES), e.getValue()).build(); } else if (null == startKey) { logger.debug("Found HRegionInfo with null startKey on server {}: {}", e.getValue(), regionInfo); Preconditions.checkState(null == nullStart); nullStart = e; // I thought endBuf would be inclusive from the HBase javadoc, but in practice it is exclusive StaticBuffer endBuf = StaticArrayBuffer.of(zeroExtend(endKey)); // Replace null start key with zeroes b.put(new KeyRange(FOUR_ZERO_BYTES, endBuf), e.getValue()); } else if (null == endKey) { logger.debug("Found HRegionInfo with null endKey on server {}: {}", e.getValue(), regionInfo); Preconditions.checkState(null == nullEnd); nullEnd = e; // Replace null end key with zeroes b.put(new KeyRange(StaticArrayBuffer.of(zeroExtend(startKey)), FOUR_ZERO_BYTES), e.getValue()); } else { Preconditions.checkState(null != startKey); Preconditions.checkState(null != endKey); // Convert HBase's inclusive end keys into exclusive Titan end keys StaticBuffer startBuf = StaticArrayBuffer.of(zeroExtend(startKey)); StaticBuffer endBuf = StaticArrayBuffer.of(zeroExtend(endKey)); KeyRange kr = new KeyRange(startBuf, endBuf); b.put(kr, e.getValue()); logger.debug("Found HRegionInfo with non-null end and start keys on server {}: {}", e.getValue(), regionInfo); } } // Require either no null key bounds or a pair of them Preconditions.checkState(!(null == nullStart ^ null == nullEnd)); // Check that every key in the result is at least 4 bytes long Map<KeyRange, ServerName> result = b.build(); for (KeyRange kr : result.keySet()) { Preconditions.checkState(4 <= kr.getStart().length()); Preconditions.checkState(4 <= kr.getEnd().length()); } return result; } /** * If the parameter is shorter than 4 bytes, then create and return a new 4 * byte array with the input array's bytes followed by zero bytes. Otherwise * return the parameter. * * @param dataToPad non-null but possibly zero-length byte array * @return either the parameter or a new array */ private final byte[] zeroExtend(byte[] dataToPad) { assert null != dataToPad; final int targetLength = 4; if (targetLength <= dataToPad.length) return dataToPad; byte padded[] = new byte[targetLength]; for (int i = 0; i < dataToPad.length; i++) padded[i] = dataToPad[i]; for (int i = dataToPad.length; i < padded.length; i++) padded[i] = (byte)0; return padded; } private String shortenCfName(String longName) throws PermanentBackendException { final String s; if (SHORT_CF_NAME_MAP.containsKey(longName)) { s = SHORT_CF_NAME_MAP.get(longName); Preconditions.checkNotNull(s); logger.debug("Substituted default CF name \"{}\" with short form \"{}\" to reduce HBase KeyValue size", longName, s); } else { if (SHORT_CF_NAME_MAP.containsValue(longName)) { String fmt = "Must use CF long-form name \"%s\" instead of the short-form name \"%s\" when configured with %s=true"; String msg = String.format(fmt, SHORT_CF_NAME_MAP.inverse().get(longName), longName, SHORT_CF_NAMES.getName()); throw new PermanentBackendException(msg); } s = longName; logger.debug("Kept default CF name \"{}\" because it has no associated short form", s); } return s; } private HTableDescriptor ensureTableExists(String tableName, String initialCFName, int ttlInSeconds) throws BackendException { HBaseAdmin adm = null; HTableDescriptor desc; try { // Create our table, if necessary adm = getAdminInterface(); /* * Some HBase versions/impls respond badly to attempts to create a * table without at least one CF. See #661. Creating a CF along with * the table avoids HBase carping. */ if (adm.tableExists(tableName)) { desc = adm.getTableDescriptor(tableName.getBytes()); } else { desc = createTable(tableName, initialCFName, ttlInSeconds, adm); } } catch (IOException e) { throw new TemporaryBackendException(e); } finally { IOUtils.closeQuietly(adm); } return desc; } private HTableDescriptor createTable(String tableName, String cfName, int ttlInSeconds, HBaseAdmin adm) throws IOException { HTableDescriptor desc = compat.newTableDescriptor(tableName); HColumnDescriptor cdesc = new HColumnDescriptor(cfName); setCFOptions(cdesc, ttlInSeconds); desc.addFamily(cdesc); int count; // total regions to create String src; if (MIN_REGION_COUNT <= (count = regionCount)) { src = "region count configuration"; } else if (0 < regionsPerServer && MIN_REGION_COUNT <= (count = regionsPerServer * getServerCount(adm))) { src = "ClusterStatus server count"; } else { count = -1; src = "default"; } if (MIN_REGION_COUNT < count) { adm.createTable(desc, getStartKey(count), getEndKey(count), count); logger.debug("Created table {} with region count {} from {}", tableName, count, src); } else { adm.createTable(desc); logger.debug("Created table {} with default start key, end key, and region count", tableName); } return desc; } /** * This method generates the second argument to * {@link HBaseAdmin#createTable(HTableDescriptor, byte[], byte[], int)}. * <p/> * From the {@code createTable} javadoc: * "The start key specified will become the end key of the first region of * the table, and the end key specified will become the start key of the * last region of the table (the first region has a null start key and * the last region has a null end key)" * <p/> * To summarize, the {@code createTable} argument called "startKey" is * actually the end key of the first region. */ private byte[] getStartKey(int regionCount) { ByteBuffer regionWidth = ByteBuffer.allocate(4); regionWidth.putInt((int)(((1L << 32) - 1L) / regionCount)).flip(); return StaticArrayBuffer.of(regionWidth).getBytes(0, 4); } /** * Companion to {@link #getStartKey(int)}. See its javadoc for details. */ private byte[] getEndKey(int regionCount) { ByteBuffer regionWidth = ByteBuffer.allocate(4); regionWidth.putInt((int)(((1L << 32) - 1L) / regionCount * (regionCount - 1))).flip(); return StaticArrayBuffer.of(regionWidth).getBytes(0, 4); } private void ensureColumnFamilyExists(String tableName, String columnFamily, int ttlInSeconds) throws BackendException { HBaseAdmin adm = null; try { adm = getAdminInterface(); HTableDescriptor desc = ensureTableExists(tableName, columnFamily, ttlInSeconds); Preconditions.checkNotNull(desc); HColumnDescriptor cf = desc.getFamily(columnFamily.getBytes()); // Create our column family, if necessary if (cf == null) { try { if (!adm.isTableDisabled(tableName)) { adm.disableTable(tableName); } } catch (TableNotEnabledException e) { logger.debug("Table {} already disabled", tableName); } catch (IOException e) { throw new TemporaryBackendException(e); } try { HColumnDescriptor cdesc = new HColumnDescriptor(columnFamily); setCFOptions(cdesc, ttlInSeconds); adm.addColumn(tableName, cdesc); try { logger.debug("Added HBase ColumnFamily {}, waiting for 1 sec. to propogate.", columnFamily); Thread.sleep(1000L); } catch (InterruptedException ie) { throw new TemporaryBackendException(ie); } adm.enableTable(tableName); } catch (TableNotFoundException ee) { logger.error("TableNotFoundException", ee); throw new PermanentBackendException(ee); } catch (org.apache.hadoop.hbase.TableExistsException ee) { logger.debug("Swallowing exception {}", ee); } catch (IOException ee) { throw new TemporaryBackendException(ee); } } } finally { IOUtils.closeQuietly(adm); } } private void setCFOptions(HColumnDescriptor cdesc, int ttlInSeconds) { if (null != compression && !compression.equals(COMPRESSION_DEFAULT)) compat.setCompression(cdesc, compression); if (ttlInSeconds > 0) cdesc.setTimeToLive(ttlInSeconds); } /** * Convert Titan internal Mutation representation into HBase native commands. * * @param mutations Mutations to convert into HBase commands. * @param putTimestamp The timestamp to use for Put commands. * @param delTimestamp The timestamp to use for Delete commands. * @return Commands sorted by key converted from Titan internal representation. * @throws com.thinkaurelius.titan.diskstorage.PermanentBackendException */ private Map<StaticBuffer, Pair<Put, Delete>> convertToCommands(Map<String, Map<StaticBuffer, KCVMutation>> mutations, final long putTimestamp, final long delTimestamp) throws PermanentBackendException { Map<StaticBuffer, Pair<Put, Delete>> commandsPerKey = new HashMap<StaticBuffer, Pair<Put, Delete>>(); for (Map.Entry<String, Map<StaticBuffer, KCVMutation>> entry : mutations.entrySet()) { String cfString = getCfNameForStoreName(entry.getKey()); byte[] cfName = cfString.getBytes(); for (Map.Entry<StaticBuffer, KCVMutation> m : entry.getValue().entrySet()) { byte[] key = m.getKey().as(StaticBuffer.ARRAY_FACTORY); KCVMutation mutation = m.getValue(); Pair<Put, Delete> commands = commandsPerKey.get(m.getKey()); if (commands == null) { commands = new Pair<Put, Delete>(); commandsPerKey.put(m.getKey(), commands); } if (mutation.hasDeletions()) { if (commands.getSecond() == null) { Delete d = new Delete(key); d.setTimestamp(delTimestamp); commands.setSecond(d); } for (StaticBuffer b : mutation.getDeletions()) { commands.getSecond().deleteColumns(cfName, b.as(StaticBuffer.ARRAY_FACTORY), delTimestamp); } } if (mutation.hasAdditions()) { if (commands.getFirst() == null) { Put p = new Put(key, putTimestamp); commands.setFirst(p); } for (Entry e : mutation.getAdditions()) { commands.getFirst().add(cfName, e.getColumnAs(StaticBuffer.ARRAY_FACTORY), putTimestamp, e.getValueAs(StaticBuffer.ARRAY_FACTORY)); } } } } return commandsPerKey; } private String getCfNameForStoreName(String storeName) throws PermanentBackendException { return shortCfNames ? shortenCfName(storeName) : storeName; } /** * Estimate the number of regionservers in the HBase cluster by calling * {@link HBaseAdmin#getClusterStatus()} and then * {@link ClusterStatus#getServers()} and finally {@code size()} on the * returned server list. * * @param adm * HBase admin interface * @return the number of servers in the cluster or -1 if an error occurred */ private int getServerCount(HBaseAdmin adm) { int serverCount = -1; try { serverCount = adm.getClusterStatus().getServers().size(); logger.debug("Read {} servers from HBase ClusterStatus", serverCount); } catch (IOException e) { logger.debug("Unable to retrieve HBase cluster status", e); } return serverCount; } private void checkConfigDeprecation(com.thinkaurelius.titan.diskstorage.configuration.Configuration config) { if (config.has(GraphDatabaseConfiguration.STORAGE_PORT)) { logger.warn("The configuration property {} is ignored for HBase. Set hbase.zookeeper.property.clientPort in hbase-site.xml or {}.hbase.zookeeper.property.clientPort in Titan's configuration file.", ConfigElement.getPath(GraphDatabaseConfiguration.STORAGE_PORT), ConfigElement.getPath(HBASE_CONFIGURATION_NAMESPACE)); } } private <T> T runWithAdmin(BackendFunction<HBaseAdmin, T> closure) throws BackendException { HBaseAdmin adm = null; try { adm = new HBaseAdmin(cnx); return closure.apply(adm); } catch (IOException e) { throw new TitanException(e); } finally { IOUtils.closeQuietly(adm); } } private HBaseAdmin getAdminInterface() { try { return new HBaseAdmin(cnx); } catch (IOException e) { throw new TitanException(e); } } /** * Similar to {@link Function}, except that the {@code apply} method is allowed * to throw {@link BackendException}. */ private static interface BackendFunction<F, T> { T apply(F input) throws BackendException; } }
0true
titan-hbase-parent_titan-hbase-core_src_main_java_com_thinkaurelius_titan_diskstorage_hbase_HBaseStoreManager.java
1,442
public class GoogleAnalyticsTag extends SimpleTagSupport { private static final Log LOG = LogFactory.getLog(GoogleAnalyticsTag.class); @Value("${googleAnalytics.webPropertyId}") private String webPropertyId; private Order order; public void setOrder(Order order) { this.order = order; } public void setWebPropertyId(String webPropertyId) { this.webPropertyId = webPropertyId; } @Override public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); if (webPropertyId == null) { ServletContext sc = ((PageContext) getJspContext()).getServletContext(); ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc); context.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false); } if (webPropertyId.equals("UA-XXXXXXX-X")) { LOG.warn("googleAnalytics.webPropertyId has not been overridden in a custom property file. Please set this in order to properly use the Google Analytics tag"); } out.println(analytics(webPropertyId, order)); super.doTag(); } /** * Documentation for the recommended asynchronous GA tag is at: * http://code.google.com/apis/analytics/docs/tracking/gaTrackingEcommerce.html * * @param webPropertyId - Google Analytics ID * @param order - optionally track the order submission. This should be included on the * page after the order has been sucessfully submitted. If null, this will just track the current page * @return the relevant Javascript to render on the page */ protected String analytics(String webPropertyId, Order order) { StringBuffer sb = new StringBuffer(); sb.append("<script type=\"text/javascript\">"); sb.append("var _gaq = _gaq || [];"); sb.append("_gaq.push(['_setAccount', '" + webPropertyId + "']);"); sb.append("_gaq.push(['_trackPageview']);"); if (order != null) { Address paymentAddress = order.getPaymentInfos().get(0).getAddress(); sb.append("_gaq.push(['_addTrans','" + order.getId() + "'"); sb.append(",'" + order.getName() + "'"); sb.append(",'" + order.getTotal() + "'"); sb.append(",'" + order.getTotalTax() + "'"); sb.append(",'" + order.getTotalShipping() + "'"); sb.append(",'" + paymentAddress.getCity() + "'"); sb.append(",'" + paymentAddress.getState().getName() + "'"); sb.append(",'" + paymentAddress.getCountry().getName() + "'"); sb.append("]);"); for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) { for (FulfillmentGroupItem fulfillmentGroupItem : fulfillmentGroup.getFulfillmentGroupItems()) { DiscreteOrderItem orderItem = (DiscreteOrderItem) fulfillmentGroupItem.getOrderItem(); sb.append("_gaq.push(['_addItem','" + order.getId() + "'"); sb.append(",'" + orderItem.getSku().getId() + "'"); sb.append(",'" + orderItem.getSku().getName() + "'"); sb.append(",' " + orderItem.getProduct().getDefaultCategory() + "'"); sb.append(",'" + orderItem.getPrice() + "'"); sb.append(",'" + orderItem.getQuantity() + "'"); sb.append("]);"); } } sb.append("_gaq.push(['_trackTrans']);"); } sb.append(" (function() {" + "var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;" + "ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';" + "var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);" + "})();"); sb.append("</script>"); return sb.toString(); } }
1no label
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_catalog_taglib_GoogleAnalyticsTag.java
1,744
public class LZFCompressedStreamOutput extends CompressedStreamOutput<LZFCompressorContext> { private final BufferRecycler recycler; private final ChunkEncoder encoder; public LZFCompressedStreamOutput(StreamOutput out) throws IOException { super(out, LZFCompressorContext.INSTANCE); this.recycler = BufferRecycler.instance(); this.uncompressed = this.recycler.allocOutputBuffer(LZFChunk.MAX_CHUNK_LEN); this.uncompressedLength = LZFChunk.MAX_CHUNK_LEN; this.encoder = new ChunkEncoder(LZFChunk.MAX_CHUNK_LEN); } @Override public void writeHeader(StreamOutput out) throws IOException { // nothing to do here, each chunk has a header of its own } @Override protected void compress(byte[] data, int offset, int len, StreamOutput out) throws IOException { encoder.encodeAndWriteChunk(data, offset, len, out); } @Override protected void doClose() throws IOException { byte[] buf = uncompressed; if (buf != null) { uncompressed = null; recycler.releaseOutputBuffer(buf); } encoder.close(); } }
0true
src_main_java_org_elasticsearch_common_compress_lzf_LZFCompressedStreamOutput.java
2,247
private static class UidField extends Field { private static final FieldType FIELD_TYPE = new FieldType(); static { FIELD_TYPE.setTokenized(true); FIELD_TYPE.setIndexed(true); FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); FIELD_TYPE.setStored(true); FIELD_TYPE.freeze(); } String uid; long version; UidField(String uid, long version) { super(UidFieldMapper.NAME, uid, FIELD_TYPE); this.uid = uid; this.version = version; } @Override public TokenStream tokenStream(Analyzer analyzer) throws IOException { return new TokenStream() { boolean finished = true; final CharTermAttribute term = addAttribute(CharTermAttribute.class); final PayloadAttribute payload = addAttribute(PayloadAttribute.class); @Override public boolean incrementToken() throws IOException { if (finished) { return false; } term.setEmpty().append(uid); payload.setPayload(new BytesRef(Numbers.longToBytes(version))); finished = true; return true; } @Override public void reset() throws IOException { finished = false; } }; } }
0true
src_test_java_org_elasticsearch_common_lucene_uid_VersionsTests.java
2
Collection<Long> perm1Ids = BLCCollectionUtils.collect(perm1, new TypedTransformer<Long>() { @Override public Long transform(Object input) { return ((ProductOptionValue) input).getId(); } });
0true
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_server_service_AdminCatalogServiceImpl.java
4,034
public class MultiMatchQuery extends MatchQuery { private boolean useDisMax = true; private float tieBreaker; public void setUseDisMax(boolean useDisMax) { this.useDisMax = useDisMax; } public void setTieBreaker(float tieBreaker) { this.tieBreaker = tieBreaker; } public MultiMatchQuery(QueryParseContext parseContext) { super(parseContext); } private Query parseAndApply(Type type, String fieldName, Object value, String minimumShouldMatch, Float boostValue) throws IOException { Query query = parse(type, fieldName, value); if (query instanceof BooleanQuery) { Queries.applyMinimumShouldMatch((BooleanQuery) query, minimumShouldMatch); } if (boostValue != null && query != null) { query.setBoost(boostValue); } return query; } public Query parse(Type type, Map<String, Float> fieldNames, Object value, String minimumShouldMatch) throws IOException { if (fieldNames.size() == 1) { Map.Entry<String, Float> fieldBoost = fieldNames.entrySet().iterator().next(); Float boostValue = fieldBoost.getValue(); return parseAndApply(type, fieldBoost.getKey(), value, minimumShouldMatch, boostValue); } if (useDisMax) { DisjunctionMaxQuery disMaxQuery = new DisjunctionMaxQuery(tieBreaker); boolean clauseAdded = false; for (String fieldName : fieldNames.keySet()) { Float boostValue = fieldNames.get(fieldName); Query query = parseAndApply(type, fieldName, value, minimumShouldMatch, boostValue); if (query != null) { clauseAdded = true; disMaxQuery.add(query); } } return clauseAdded ? disMaxQuery : null; } else { BooleanQuery booleanQuery = new BooleanQuery(); for (String fieldName : fieldNames.keySet()) { Float boostValue = fieldNames.get(fieldName); Query query = parseAndApply(type, fieldName, value, minimumShouldMatch, boostValue); if (query != null) { booleanQuery.add(query, BooleanClause.Occur.SHOULD); } } return !booleanQuery.clauses().isEmpty() ? booleanQuery : null; } } }
1no label
src_main_java_org_elasticsearch_index_search_MultiMatchQuery.java
1,500
public class BalanceConfigurationTests extends ElasticsearchAllocationTestCase { private final ESLogger logger = Loggers.getLogger(BalanceConfigurationTests.class); // TODO maybe we can randomize these numbers somehow final int numberOfNodes = 25; final int numberOfIndices = 12; final int numberOfShards = 2; final int numberOfReplicas = 2; @Test public void testIndexBalance() { /* Tests balance over indices only */ final float indexBalance = 1.0f; final float replicaBalance = 0.0f; final float primaryBalance = 0.0f; final float balanceTreshold = 1.0f; ImmutableSettings.Builder settings = settingsBuilder(); settings.put("cluster.routing.allocation.allow_rebalance", ClusterRebalanceAllocationDecider.ClusterRebalanceType.ALWAYS.toString()); settings.put(BalancedShardsAllocator.SETTING_INDEX_BALANCE_FACTOR, indexBalance); settings.put(BalancedShardsAllocator.SETTING_SHARD_BALANCE_FACTOR, replicaBalance); settings.put(BalancedShardsAllocator.SETTING_PRIMARY_BALANCE_FACTOR, primaryBalance); settings.put(BalancedShardsAllocator.SETTING_THRESHOLD, balanceTreshold); AllocationService strategy = createAllocationService(settings.build()); ClusterState clusterState = initCluster(strategy); assertIndexBalance(logger, clusterState.getRoutingNodes(), numberOfNodes, numberOfIndices, numberOfReplicas, numberOfShards, balanceTreshold); clusterState = addNode(clusterState, strategy); assertIndexBalance(logger, clusterState.getRoutingNodes(), numberOfNodes + 1, numberOfIndices, numberOfReplicas, numberOfShards, balanceTreshold); clusterState = removeNodes(clusterState, strategy); assertIndexBalance(logger, clusterState.getRoutingNodes(), (numberOfNodes + 1) - (numberOfNodes + 1) / 2, numberOfIndices, numberOfReplicas, numberOfShards, balanceTreshold); } @Test public void testReplicaBalance() { /* Tests balance over replicas only */ final float indexBalance = 0.0f; final float replicaBalance = 1.0f; final float primaryBalance = 0.0f; final float balanceTreshold = 1.0f; ImmutableSettings.Builder settings = settingsBuilder(); settings.put("cluster.routing.allocation.allow_rebalance", ClusterRebalanceAllocationDecider.ClusterRebalanceType.ALWAYS.toString()); settings.put(BalancedShardsAllocator.SETTING_INDEX_BALANCE_FACTOR, indexBalance); settings.put(BalancedShardsAllocator.SETTING_SHARD_BALANCE_FACTOR, replicaBalance); settings.put(BalancedShardsAllocator.SETTING_PRIMARY_BALANCE_FACTOR, primaryBalance); settings.put(BalancedShardsAllocator.SETTING_THRESHOLD, balanceTreshold); AllocationService strategy = createAllocationService(settings.build()); ClusterState clusterState = initCluster(strategy); assertReplicaBalance(logger, clusterState.getRoutingNodes(), numberOfNodes, numberOfIndices, numberOfReplicas, numberOfShards, balanceTreshold); clusterState = addNode(clusterState, strategy); assertReplicaBalance(logger, clusterState.getRoutingNodes(), numberOfNodes + 1, numberOfIndices, numberOfReplicas, numberOfShards, balanceTreshold); clusterState = removeNodes(clusterState, strategy); assertReplicaBalance(logger, clusterState.getRoutingNodes(), (numberOfNodes + 1) - (numberOfNodes + 1) / 2, numberOfIndices, numberOfReplicas, numberOfShards, balanceTreshold); } @Test public void testPrimaryBalance() { /* Tests balance over primaries only */ final float indexBalance = 0.0f; final float replicaBalance = 0.0f; final float primaryBalance = 1.0f; final float balanceTreshold = 1.0f; ImmutableSettings.Builder settings = settingsBuilder(); settings.put("cluster.routing.allocation.allow_rebalance", ClusterRebalanceAllocationDecider.ClusterRebalanceType.ALWAYS.toString()); settings.put(BalancedShardsAllocator.SETTING_INDEX_BALANCE_FACTOR, indexBalance); settings.put(BalancedShardsAllocator.SETTING_SHARD_BALANCE_FACTOR, replicaBalance); settings.put(BalancedShardsAllocator.SETTING_PRIMARY_BALANCE_FACTOR, primaryBalance); settings.put(BalancedShardsAllocator.SETTING_THRESHOLD, balanceTreshold); AllocationService strategy = createAllocationService(settings.build()); ClusterState clusterstate = initCluster(strategy); assertPrimaryBalance(logger, clusterstate.getRoutingNodes(), numberOfNodes, numberOfIndices, numberOfReplicas, numberOfShards, balanceTreshold); clusterstate = addNode(clusterstate, strategy); assertPrimaryBalance(logger, clusterstate.getRoutingNodes(), numberOfNodes + 1, numberOfIndices, numberOfReplicas, numberOfShards, balanceTreshold); clusterstate = removeNodes(clusterstate, strategy); assertPrimaryBalance(logger, clusterstate.getRoutingNodes(), numberOfNodes + 1 - (numberOfNodes + 1) / 2, numberOfIndices, numberOfReplicas, numberOfShards, balanceTreshold); } private ClusterState initCluster(AllocationService strategy) { MetaData.Builder metaDataBuilder = MetaData.builder(); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); for (int i = 0; i < numberOfIndices; i++) { IndexMetaData.Builder index = IndexMetaData.builder("test" + i).numberOfShards(numberOfShards).numberOfReplicas(numberOfReplicas); metaDataBuilder = metaDataBuilder.put(index); } MetaData metaData = metaDataBuilder.build(); for (ObjectCursor<IndexMetaData> cursor : metaData.indices().values()) { routingTableBuilder.addAsNew(cursor.value); } RoutingTable routingTable = routingTableBuilder.build(); logger.info("start " + numberOfNodes + " nodes"); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(); for (int i = 0; i < numberOfNodes; i++) { nodes.put(newNode("node" + i)); } ClusterState clusterState = ClusterState.builder().nodes(nodes).metaData(metaData).routingTable(routingTable).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); RoutingNodes routingNodes = clusterState.routingNodes(); logger.info("restart all the primary shards, replicas will start initializing"); routingNodes = clusterState.routingNodes(); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); logger.info("start the replica shards"); routingNodes = clusterState.routingNodes(); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); logger.info("complete rebalancing"); RoutingTable prev = routingTable; while (true) { routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); if (routingTable == prev) break; prev = routingTable; } return clusterState; } private ClusterState addNode(ClusterState clusterState, AllocationService strategy) { logger.info("now, start 1 more node, check that rebalancing will happen because we set it to always"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()) .put(newNode("node" + numberOfNodes))) .build(); RoutingTable routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); RoutingNodes routingNodes = clusterState.routingNodes(); // move initializing to started RoutingTable prev = routingTable; while (true) { routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); if (routingTable == prev) break; prev = routingTable; } return clusterState; } private ClusterState removeNodes(ClusterState clusterState, AllocationService strategy) { logger.info("Removing half the nodes (" + (numberOfNodes + 1) / 2 + ")"); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(clusterState.nodes()); for (int i = (numberOfNodes + 1) / 2; i <= numberOfNodes; i++) { nodes.remove("node" + i); } clusterState = ClusterState.builder(clusterState).nodes(nodes.build()).build(); RoutingNodes routingNodes = clusterState.routingNodes(); logger.info("start all the primary shards, replicas will start initializing"); RoutingTable routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); logger.info("start the replica shards"); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); logger.info("rebalancing"); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); logger.info("complete rebalancing"); RoutingTable prev = routingTable; while (true) { routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); if (routingTable == prev) break; prev = routingTable; } return clusterState; } private void assertReplicaBalance(ESLogger logger, RoutingNodes nodes, int numberOfNodes, int numberOfIndices, int numberOfReplicas, int numberOfShards, float treshold) { final int numShards = numberOfIndices * numberOfShards * (numberOfReplicas + 1); final float avgNumShards = (float) (numShards) / (float) (numberOfNodes); final int minAvgNumberOfShards = Math.round(Math.round(Math.floor(avgNumShards - treshold))); final int maxAvgNumberOfShards = Math.round(Math.round(Math.ceil(avgNumShards + treshold))); for (RoutingNode node : nodes) { // logger.info(node.nodeId() + ": " + node.shardsWithState(INITIALIZING, STARTED).size() + " shards ("+minAvgNumberOfShards+" to "+maxAvgNumberOfShards+")"); assertThat(node.shardsWithState(STARTED).size(), Matchers.greaterThanOrEqualTo(minAvgNumberOfShards)); assertThat(node.shardsWithState(STARTED).size(), Matchers.lessThanOrEqualTo(maxAvgNumberOfShards)); } } private void assertIndexBalance(ESLogger logger, RoutingNodes nodes, int numberOfNodes, int numberOfIndices, int numberOfReplicas, int numberOfShards, float treshold) { final int numShards = numberOfShards * (numberOfReplicas + 1); final float avgNumShards = (float) (numShards) / (float) (numberOfNodes); final int minAvgNumberOfShards = Math.round(Math.round(Math.floor(avgNumShards - treshold))); final int maxAvgNumberOfShards = Math.round(Math.round(Math.ceil(avgNumShards + treshold))); for (String index : nodes.getRoutingTable().indicesRouting().keySet()) { for (RoutingNode node : nodes) { // logger.info(node.nodeId() +":"+index+ ": " + node.shardsWithState(index, INITIALIZING, STARTED).size() + " shards ("+minAvgNumberOfShards+" to "+maxAvgNumberOfShards+")"); assertThat(node.shardsWithState(index, STARTED).size(), Matchers.greaterThanOrEqualTo(minAvgNumberOfShards)); assertThat(node.shardsWithState(index, STARTED).size(), Matchers.lessThanOrEqualTo(maxAvgNumberOfShards)); } } } private void assertPrimaryBalance(ESLogger logger, RoutingNodes nodes, int numberOfNodes, int numberOfIndices, int numberOfReplicas, int numberOfShards, float treshold) { final int numShards = numberOfShards; final float avgNumShards = (float) (numShards) / (float) (numberOfNodes); final int minAvgNumberOfShards = Math.round(Math.round(Math.floor(avgNumShards - treshold))); final int maxAvgNumberOfShards = Math.round(Math.round(Math.ceil(avgNumShards + treshold))); for (String index : nodes.getRoutingTable().indicesRouting().keySet()) { for (RoutingNode node : nodes) { int primaries = 0; for (ShardRouting shard : node.shardsWithState(index, STARTED)) { primaries += shard.primary() ? 1 : 0; } // logger.info(node.nodeId() + ": " + primaries + " primaries ("+minAvgNumberOfShards+" to "+maxAvgNumberOfShards+")"); assertThat(primaries, Matchers.greaterThanOrEqualTo(minAvgNumberOfShards)); assertThat(primaries, Matchers.lessThanOrEqualTo(maxAvgNumberOfShards)); } } } @Test public void testPersistedSettings() { ImmutableSettings.Builder settings = settingsBuilder(); settings.put(BalancedShardsAllocator.SETTING_INDEX_BALANCE_FACTOR, 0.2); settings.put(BalancedShardsAllocator.SETTING_SHARD_BALANCE_FACTOR, 0.3); settings.put(BalancedShardsAllocator.SETTING_PRIMARY_BALANCE_FACTOR, 0.5); settings.put(BalancedShardsAllocator.SETTING_THRESHOLD, 2.0); final NodeSettingsService.Listener[] listeners = new NodeSettingsService.Listener[1]; NodeSettingsService service = new NodeSettingsService(settingsBuilder().build()) { @Override public void addListener(Listener listener) { assertNull("addListener was called twice while only one time was expected", listeners[0]); listeners[0] = listener; } }; BalancedShardsAllocator allocator = new BalancedShardsAllocator(settings.build(), service); assertThat(allocator.getIndexBalance(), Matchers.equalTo(0.2f)); assertThat(allocator.getShardBalance(), Matchers.equalTo(0.3f)); assertThat(allocator.getPrimaryBalance(), Matchers.equalTo(0.5f)); assertThat(allocator.getThreshold(), Matchers.equalTo(2.0f)); settings = settingsBuilder(); settings.put("cluster.routing.allocation.allow_rebalance", ClusterRebalanceAllocationDecider.ClusterRebalanceType.ALWAYS.toString()); listeners[0].onRefreshSettings(settings.build()); assertThat(allocator.getIndexBalance(), Matchers.equalTo(0.2f)); assertThat(allocator.getShardBalance(), Matchers.equalTo(0.3f)); assertThat(allocator.getPrimaryBalance(), Matchers.equalTo(0.5f)); assertThat(allocator.getThreshold(), Matchers.equalTo(2.0f)); settings = settingsBuilder(); settings.put(BalancedShardsAllocator.SETTING_INDEX_BALANCE_FACTOR, 0.5); settings.put(BalancedShardsAllocator.SETTING_SHARD_BALANCE_FACTOR, 0.1); settings.put(BalancedShardsAllocator.SETTING_PRIMARY_BALANCE_FACTOR, 0.4); settings.put(BalancedShardsAllocator.SETTING_THRESHOLD, 3.0); listeners[0].onRefreshSettings(settings.build()); assertThat(allocator.getIndexBalance(), Matchers.equalTo(0.5f)); assertThat(allocator.getShardBalance(), Matchers.equalTo(0.1f)); assertThat(allocator.getPrimaryBalance(), Matchers.equalTo(0.4f)); assertThat(allocator.getThreshold(), Matchers.equalTo(3.0f)); } @Test public void testNoRebalanceOnPrimaryOverload() { ImmutableSettings.Builder settings = settingsBuilder(); AllocationService strategy = new AllocationService(settings.build(), randomAllocationDeciders(settings.build(), new NodeSettingsService(ImmutableSettings.Builder.EMPTY_SETTINGS), getRandom()), new ShardsAllocators(settings.build(), new NoneGatewayAllocator(), new ShardsAllocator() { @Override public boolean rebalance(RoutingAllocation allocation) { return false; } @Override public boolean move(MutableShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { return false; } @Override public void applyStartedShards(StartedRerouteAllocation allocation) { } @Override public void applyFailedShards(FailedRerouteAllocation allocation) { } /* * // this allocator tries to rebuild this scenario where a rebalance is * // triggered solely by the primary overload on node [1] where a shard * // is rebalanced to node 0 routing_nodes: -----node_id[0][V] --------[test][0], node[0], [R], s[STARTED] --------[test][4], node[0], [R], s[STARTED] -----node_id[1][V] --------[test][0], node[1], [P], s[STARTED] --------[test][1], node[1], [P], s[STARTED] --------[test][3], node[1], [R], s[STARTED] -----node_id[2][V] --------[test][1], node[2], [R], s[STARTED] --------[test][2], node[2], [R], s[STARTED] --------[test][4], node[2], [P], s[STARTED] -----node_id[3][V] --------[test][2], node[3], [P], s[STARTED] --------[test][3], node[3], [P], s[STARTED] ---- unassigned */ @Override public boolean allocateUnassigned(RoutingAllocation allocation) { RoutingNodes.UnassignedShards unassigned = allocation.routingNodes().unassigned(); boolean changed = !unassigned.isEmpty(); for (MutableShardRouting sr : unassigned) { switch (sr.id()) { case 0: if (sr.primary()) { allocation.routingNodes().assign(sr, "node1"); } else { allocation.routingNodes().assign(sr, "node0"); } break; case 1: if (sr.primary()) { allocation.routingNodes().assign(sr, "node1"); } else { allocation.routingNodes().assign(sr, "node2"); } break; case 2: if (sr.primary()) { allocation.routingNodes().assign(sr, "node3"); } else { allocation.routingNodes().assign(sr, "node2"); } break; case 3: if (sr.primary()) { allocation.routingNodes().assign(sr, "node3"); } else { allocation.routingNodes().assign(sr, "node1"); } break; case 4: if (sr.primary()) { allocation.routingNodes().assign(sr, "node2"); } else { allocation.routingNodes().assign(sr, "node0"); } break; } } unassigned.clear(); return changed; } }), ClusterInfoService.EMPTY); MetaData.Builder metaDataBuilder = MetaData.builder(); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); IndexMetaData.Builder indexMeta = IndexMetaData.builder("test").numberOfShards(5).numberOfReplicas(1); metaDataBuilder = metaDataBuilder.put(indexMeta); MetaData metaData = metaDataBuilder.build(); for (ObjectCursor<IndexMetaData> cursor : metaData.indices().values()) { routingTableBuilder.addAsNew(cursor.value); } RoutingTable routingTable = routingTableBuilder.build(); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(); for (int i = 0; i < 4; i++) { DiscoveryNode node = newNode("node" + i); nodes.put(node); } ClusterState clusterState = ClusterState.builder().nodes(nodes).metaData(metaData).routingTable(routingTable).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); RoutingNodes routingNodes = clusterState.routingNodes(); for (RoutingNode routingNode : routingNodes) { for (MutableShardRouting mutableShardRouting : routingNode) { assertThat(mutableShardRouting.state(), Matchers.equalTo(ShardRoutingState.INITIALIZING)); } } strategy = createAllocationService(settings.build()); logger.info("use the new allocator and check if it moves shards"); routingNodes = clusterState.routingNodes(); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); for (RoutingNode routingNode : routingNodes) { for (MutableShardRouting mutableShardRouting : routingNode) { assertThat(mutableShardRouting.state(), Matchers.equalTo(ShardRoutingState.STARTED)); } } logger.info("start the replica shards"); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); for (RoutingNode routingNode : routingNodes) { for (MutableShardRouting mutableShardRouting : routingNode) { assertThat(mutableShardRouting.state(), Matchers.equalTo(ShardRoutingState.STARTED)); } } logger.info("rebalancing"); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); for (RoutingNode routingNode : routingNodes) { for (MutableShardRouting mutableShardRouting : routingNode) { assertThat(mutableShardRouting.state(), Matchers.equalTo(ShardRoutingState.STARTED)); } } } }
0true
src_test_java_org_elasticsearch_cluster_routing_allocation_BalanceConfigurationTests.java
1,628
public class EJB3ConfigurationDaoImpl implements EJB3ConfigurationDao { private Ejb3Configuration configuration = null; protected PersistenceUnitInfo persistenceUnitInfo; public Ejb3Configuration getConfiguration() { synchronized(this) { if (configuration == null) { Ejb3Configuration temp = new Ejb3Configuration(); String previousValue = persistenceUnitInfo.getProperties().getProperty("hibernate.hbm2ddl.auto"); persistenceUnitInfo.getProperties().setProperty("hibernate.hbm2ddl.auto", "none"); configuration = temp.configure(persistenceUnitInfo, new HashMap()); configuration.getHibernateConfiguration().buildSessionFactory(); persistenceUnitInfo.getProperties().setProperty("hibernate.hbm2ddl.auto", previousValue); } } return configuration; } public PersistenceUnitInfo getPersistenceUnitInfo() { return persistenceUnitInfo; } public void setPersistenceUnitInfo(PersistenceUnitInfo persistenceUnitInfo) { this.persistenceUnitInfo = persistenceUnitInfo; } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_dao_EJB3ConfigurationDaoImpl.java
1,600
enum Type { NODE, JOIN, CONNECTION, PARTITION, CALL, NONE }
0true
hazelcast_src_main_java_com_hazelcast_logging_SystemLog.java
1,339
completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference.set(t); latch2.countDown(); } });
0true
hazelcast_src_test_java_com_hazelcast_executor_ExecutorServiceTest.java
3,356
public static class SingleFixedSet extends GeoPointDoubleArrayAtomicFieldData { private final BigDoubleArrayList lon, lat; private final FixedBitSet set; private final long numOrds; public SingleFixedSet(BigDoubleArrayList lon, BigDoubleArrayList lat, int numDocs, FixedBitSet set, long numOrds) { super(numDocs); this.lon = lon; this.lat = lat; this.set = set; this.numOrds = numOrds; } @Override public boolean isMultiValued() { return false; } @Override public boolean isValuesOrdered() { return false; } @Override public long getNumberUniqueValues() { return numOrds; } @Override public long getMemorySizeInBytes() { if (size == -1) { size = RamUsageEstimator.NUM_BYTES_INT/*size*/ + RamUsageEstimator.NUM_BYTES_INT/*numDocs*/ + lon.sizeInBytes() + lat.sizeInBytes() + RamUsageEstimator.sizeOf(set.getBits()); } return size; } @Override public GeoPointValues getGeoPointValues() { return new GeoPointValuesSingleFixedSet(lon, lat, set); } static class GeoPointValuesSingleFixedSet extends GeoPointValues { private final BigDoubleArrayList lon; private final BigDoubleArrayList lat; private final FixedBitSet set; private final GeoPoint scratch = new GeoPoint(); GeoPointValuesSingleFixedSet(BigDoubleArrayList lon, BigDoubleArrayList lat, FixedBitSet set) { super(false); this.lon = lon; this.lat = lat; this.set = set; } @Override public int setDocument(int docId) { this.docId = docId; return set.get(docId) ? 1 : 0; } @Override public GeoPoint nextValue() { return scratch.reset(lat.get(docId), lon.get(docId)); } } }
0true
src_main_java_org_elasticsearch_index_fielddata_plain_GeoPointDoubleArrayAtomicFieldData.java
342
private final ITreeViewerListener fExpansionListener= new ITreeViewerListener() { public void treeCollapsed(TreeExpansionEvent event) { } public void treeExpanded(TreeExpansionEvent event) { Object element= event.getElement(); if (element instanceof ICompilationUnit || element instanceof IClassFile) expandMainType(element); } };
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_PackageExplorerPart.java
260
class GotoMatchingFenceAction extends Action { private final CeylonEditor fEditor; public GotoMatchingFenceAction(CeylonEditor editor) { super("Go to Matching Fence"); Assert.isNotNull(editor); fEditor= editor; setEnabled(true); //PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GOTO_MATCHING_BRACKET_ACTION); } public void run() { gotoMatchingFence(); } /** * Jumps to the matching bracket. */ public void gotoMatchingFence() { ISourceViewer sourceViewer = fEditor.getCeylonSourceViewer(); IDocument document= sourceViewer.getDocument(); if (document == null) return; IRegion selection= fEditor.getSignedSelection(); int selectionLength= Math.abs(selection.getLength()); if (selectionLength > 1) { fEditor.setStatusLineErrorMessage("Invalid selection"); sourceViewer.getTextWidget().getDisplay().beep(); return; } // #26314 int sourceCaretOffset= selection.getOffset() + selection.getLength(); if (isSurroundedByBrackets(document, sourceCaretOffset)) sourceCaretOffset -= selection.getLength(); IRegion region= fEditor.getBracketMatcher().match(document, sourceCaretOffset); if (region == null) { fEditor.setStatusLineErrorMessage("No matching fence!"); sourceViewer.getTextWidget().getDisplay().beep(); return; } int offset= region.getOffset(); int length= region.getLength(); if (length < 1) return; int anchor= fEditor.getBracketMatcher().getAnchor(); // http://dev.eclipse.org/bugs/show_bug.cgi?id=34195 int targetOffset= (ICharacterPairMatcher.RIGHT == anchor) ? offset + 1: offset + length; boolean visible= false; if (sourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer; visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1); } else { IRegion visibleRegion= sourceViewer.getVisibleRegion(); // http://dev.eclipse.org/bugs/show_bug.cgi?id=34195 visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength()); } if (!visible) { fEditor.setStatusLineErrorMessage("Matching fence is outside the currently selected element."); sourceViewer.getTextWidget().getDisplay().beep(); return; } if (selection.getLength() < 0) targetOffset -= selection.getLength(); sourceViewer.setSelectedRange(targetOffset, selection.getLength()); sourceViewer.revealRange(targetOffset, selection.getLength()); } private boolean isBracket(char character) { String[][] fences= getFences(); for(int i= 0; i != fences.length; ++i) { if (fences[i][0].indexOf(character) >= 0) return true; if (fences[i][1].indexOf(character) >= 0) return true; } return false; } private boolean isSurroundedByBrackets(IDocument document, int offset) { if (offset == 0 || offset == document.getLength()) return false; try { return isBracket(document.getChar(offset - 1)) && isBracket(document.getChar(offset)); } catch (BadLocationException e) { return false; } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_GotoMatchingFenceAction.java
1,128
public class FulfillmentBandResultAmountType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, FulfillmentBandResultAmountType> TYPES = new LinkedHashMap<String, FulfillmentBandResultAmountType>(); public static final FulfillmentBandResultAmountType RATE = new FulfillmentBandResultAmountType("RATE", "Rate"); public static final FulfillmentBandResultAmountType PERCENTAGE = new FulfillmentBandResultAmountType("PERCENTAGE", "Percentage"); public static FulfillmentBandResultAmountType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public FulfillmentBandResultAmountType() { //do nothing } public FulfillmentBandResultAmountType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } @Override public String getType() { return type; } @Override public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } @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; FulfillmentBandResultAmountType other = (FulfillmentBandResultAmountType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_type_FulfillmentBandResultAmountType.java
1,631
@Deprecated public class OServerHandlerHelper extends OServerPluginHelper { }
0true
server_src_main_java_com_orientechnologies_orient_server_handler_OServerHandlerHelper.java
454
private static class TreeKeyIterator implements Iterator<OIdentifiable> { private final boolean autoConvertToRecord; private OSBTreeMapEntryIterator<OIdentifiable, Boolean> entryIterator; public TreeKeyIterator(OTreeInternal<OIdentifiable, Boolean> tree, boolean autoConvertToRecord) { entryIterator = new OSBTreeMapEntryIterator<OIdentifiable, Boolean>(tree); this.autoConvertToRecord = autoConvertToRecord; } @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public OIdentifiable next() { final OIdentifiable identifiable = entryIterator.next().getKey(); if (autoConvertToRecord) return identifiable.getRecord(); else return identifiable; } @Override public void remove() { entryIterator.remove(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_record_ridset_sbtree_OIndexRIDContainerSBTree.java
1,834
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class MapLockTest extends HazelcastTestSupport { @Test public void testBackupDies() throws TransactionException { Config config = new Config(); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2); final HazelcastInstance h1 = factory.newHazelcastInstance(config); final HazelcastInstance h2 = factory.newHazelcastInstance(config); final IMap map1 = h1.getMap("testBackupDies"); final int size = 50; final CountDownLatch latch = new CountDownLatch(size + 1); Runnable runnable = new Runnable() { public void run() { for (int i = 0; i < size; i++) { map1.lock(i); try { Thread.sleep(100); } catch (InterruptedException e) { } latch.countDown(); } for (int i = 0; i < size; i++) { assertTrue(map1.isLocked(i)); } for (int i = 0; i < size; i++) { map1.unlock(i); } for (int i = 0; i < size; i++) { assertFalse(map1.isLocked(i)); } latch.countDown(); } }; new Thread(runnable).start(); try { Thread.sleep(1000); h2.shutdown(); latch.await(); for (int i = 0; i < size; i++) { assertFalse(map1.isLocked(i)); } } catch (InterruptedException e) { } } @Test(timeout = 20000) public void testLockEviction() throws Exception { final String mapName = "testLockEviction"; final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2); final Config config = new Config(); config.getMapConfig(mapName).setBackupCount(1); final HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(config); final HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(config); warmUpPartitions(instance2, instance1); final IMap map = instance1.getMap(mapName); map.put(1, 1); map.lock(1, 1, TimeUnit.SECONDS); assertTrue(map.isLocked(1)); final CountDownLatch latch = new CountDownLatch(1); Thread t = new Thread(new Runnable() { public void run() { map.lock(1); latch.countDown(); } }); t.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); } @Test(expected = IllegalArgumentException.class) public void testLockTTL_whenZeroTimeout() throws Exception { final Config config = new Config(); final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(1); final HazelcastInstance instance = nodeFactory.newHazelcastInstance(config); final IMap mm = instance.getMap(randomString()); final Object key = "Key"; mm.lock(key, 0, TimeUnit.SECONDS); } @Test(timeout = 100000) public void testLockEviction2() throws Exception { final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2); final Config config = new Config(); final HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(config); final HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(config); warmUpPartitions(instance2, instance1); final String name = "testLockEviction2"; final IMap map = instance1.getMap(name); Random rand = new Random(); for (int i = 0; i < 5; i++) { map.lock(i, rand.nextInt(5) + 1, TimeUnit.SECONDS); } final CountDownLatch latch = new CountDownLatch(5); Thread t = new Thread(new Runnable() { public void run() { for (int i = 0; i < 5; i++) { map.lock(i); latch.countDown(); } } }); t.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); } @Test(timeout = 100000) public void testLockMigration() throws Exception { final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final Config config = new Config(); final AtomicInteger integer = new AtomicInteger(0); final HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(config); final String name = "testLockMigration"; final IMap map = instance1.getMap(name); for (int i = 0; i < 1000; i++) { map.lock(i); } final HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(config); final HazelcastInstance instance3 = nodeFactory.newHazelcastInstance(config); Thread.sleep(3000); final CountDownLatch latch = new CountDownLatch(1000); Thread t = new Thread(new Runnable() { public void run() { for (int i = 0; i < 1000; i++) { if (map.isLocked(i)) { latch.countDown(); } } } }); t.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); } @Test(timeout = 100000) public void testLockEvictionWithMigration() throws Exception { final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); final Config config = new Config(); final HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(config); final String name = "testLockEvictionWithMigration"; final IMap map = instance1.getMap(name); for (int i = 0; i < 1000; i++) { map.lock(i, 20, TimeUnit.SECONDS); } final HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(config); final HazelcastInstance instance3 = nodeFactory.newHazelcastInstance(config); for (int i = 0; i < 1000; i++) { assertTrue(map.isLocked(i)); } final CountDownLatch latch = new CountDownLatch(1000); Thread t = new Thread(new Runnable() { public void run() { for (int i = 0; i < 1000; i++) { map.lock(i); latch.countDown(); } } }); t.start(); assertTrue(latch.await(60, TimeUnit.SECONDS)); } @Test(timeout = 1000*15, expected = IllegalMonitorStateException.class) public void testLockOwnership() throws Exception { final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2); final Config config = new Config(); final HazelcastInstance node1 = nodeFactory.newHazelcastInstance(config); final HazelcastInstance node2 = nodeFactory.newHazelcastInstance(config); final IMap map1 = node1.getMap("map"); final IMap map2 = node2.getMap("map"); map1.lock(1); map2.unlock(1); } @Test(timeout = 1000*30) public void testAbsentKeyIsLocked() throws Exception { final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2); final String MAP_A = "MAP_A"; final String KEY = "KEY"; final String VAL_2 = "VAL_2"; final HazelcastInstance node1 = nodeFactory.newHazelcastInstance(); final HazelcastInstance node2 = nodeFactory.newHazelcastInstance(); final IMap map1 = node1.getMap(MAP_A); final IMap map2 = node2.getMap(MAP_A); map1.lock(KEY); boolean putResult = map2.tryPut(KEY, VAL_2, 2, TimeUnit.SECONDS); Assert.assertFalse("the result of try put should be false as the absent key is locked", putResult); assertTrueEventually(new AssertTask() { public void run() { Assert.assertEquals("the key should be absent ", null, map1.get(KEY)); Assert.assertEquals("the key should be absent ", null, map2.get(KEY)); } }); } @Test @Category(ProblematicTest.class) public void testLockTTLKey() { final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2); final HazelcastInstance node1 = nodeFactory.newHazelcastInstance(); final IMap map = node1.getMap("map"); final String KEY = "key"; final String VAL = "val"; final int TTL_SEC = 1; map.put(KEY, VAL, TTL_SEC, TimeUnit.SECONDS); map.lock(KEY); sleepSeconds(TTL_SEC * 2); assertEquals("TTL of KEY has expired, KEY is locked, we expect VAL", VAL, map.get(KEY)); map.unlock(KEY); assertEquals("TTL of KEY has expired, KEY is unlocked, we expect null", null, map.get(KEY)); } }
0true
hazelcast_src_test_java_com_hazelcast_map_MapLockTest.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
66
public interface Result<V extends Element> { /** * Returns the element that matches the query * * @return */ public V getElement(); /** * Returns the score of the result with respect to the query (if available) * @return */ public double getScore(); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanIndexQuery.java
248
private final static class SurfaceFormAndPayload implements Comparable<SurfaceFormAndPayload> { BytesRef payload; long weight; public SurfaceFormAndPayload(BytesRef payload, long cost) { super(); this.payload = payload; this.weight = cost; } @Override public int compareTo(SurfaceFormAndPayload o) { int res = compare(weight, o.weight); if (res == 0 ){ return payload.compareTo(o.payload); } return res; } public static int compare(long x, long y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } }
0true
src_main_java_org_apache_lucene_search_suggest_analyzing_XAnalyzingSuggester.java
751
CreditCardPaymentInfo cc = new CreditCardPaymentInfo() { private static final long serialVersionUID = 1L; private String referenceNumber = "1234"; @Override public String getCvvCode() { return "123"; } @Override public Integer getExpirationMonth() { return 11; } @Override public Integer getExpirationYear() { return 2011; } @Override public Long getId() { return null; } @Override public String getPan() { return "1111111111111111"; } @Override public String getNameOnCard() { return "Cardholder Name"; } @Override public void setCvvCode(String cvvCode) { //do nothing } @Override public void setExpirationMonth(Integer expirationMonth) { //do nothing } @Override public void setExpirationYear(Integer expirationYear) { //do nothing } @Override public void setId(Long id) { //do nothing } @Override public void setNameOnCard(String nameOnCard) { //do nothing } @Override public void setPan(String pan) { //do nothing } @Override public EncryptionModule getEncryptionModule() { return encryptionModule; } @Override public String getReferenceNumber() { return referenceNumber; } @Override public void setEncryptionModule(EncryptionModule encryptionModule) { //do nothing } @Override public void setReferenceNumber(String referenceNumber) { this.referenceNumber = referenceNumber; } };
0true
integration_src_test_java_org_broadleafcommerce_core_checkout_service_legacy_LegacyCheckoutTest.java
34
static final class ThenPropagate extends Completion { final CompletableFuture<?> src; final CompletableFuture<Void> dst; ThenPropagate(CompletableFuture<?> src, CompletableFuture<Void> dst) { this.src = src; this.dst = dst; } public final void run() { final CompletableFuture<?> a; final CompletableFuture<Void> dst; Object r; Throwable ex; if ((dst = this.dst) != null && (a = this.src) != null && (r = a.result) != null && compareAndSet(0, 1)) { if (r instanceof AltResult) ex = ((AltResult)r).ex; else ex = null; dst.internalComplete(null, ex); } } private static final long serialVersionUID = 5232453952276885070L; }
0true
src_main_java_jsr166e_CompletableFuture.java
86
public interface OConsoleReader { public String readLine(); public void setConsole(OConsoleApplication console); public OConsoleApplication getConsole(); }
0true
commons_src_main_java_com_orientechnologies_common_console_OConsoleReader.java
2,754
static final class Fields { static final XContentBuilderString HTTP = new XContentBuilderString("http"); static final XContentBuilderString BOUND_ADDRESS = new XContentBuilderString("bound_address"); static final XContentBuilderString PUBLISH_ADDRESS = new XContentBuilderString("publish_address"); static final XContentBuilderString MAX_CONTENT_LENGTH = new XContentBuilderString("max_content_length"); static final XContentBuilderString MAX_CONTENT_LENGTH_IN_BYTES = new XContentBuilderString("max_content_length_in_bytes"); }
0true
src_main_java_org_elasticsearch_http_HttpInfo.java
84
public interface StaticAssetStorage { Long getId(); void setId(Long id); Blob getFileData(); void setFileData(Blob fileData); public Long getStaticAssetId(); public void setStaticAssetId(Long staticAssetId); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetStorage.java
975
public class GetLockCountOperation extends BaseLockOperation { public GetLockCountOperation() { } public GetLockCountOperation(ObjectNamespace namespace, Data key) { super(namespace, key, -1); } @Override public int getId() { return LockDataSerializerHook.GET_LOCK_COUNT; } @Override public void run() throws Exception { LockStoreImpl lockStore = getLockStore(); response = lockStore.getLockCount(key); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_lock_operations_GetLockCountOperation.java
2,009
private static final class RealMapBinder<K, V> extends MapBinder<K, V> implements Module { private final TypeLiteral<V> valueType; private final Key<Map<K, V>> mapKey; private final Key<Map<K, Provider<V>>> providerMapKey; private final RealMultibinder<Map.Entry<K, Provider<V>>> entrySetBinder; /* the target injector's binder. non-null until initialization, null afterwards */ private Binder binder; private RealMapBinder(Binder binder, TypeLiteral<V> valueType, Key<Map<K, V>> mapKey, Key<Map<K, Provider<V>>> providerMapKey, Multibinder<Map.Entry<K, Provider<V>>> entrySetBinder) { this.valueType = valueType; this.mapKey = mapKey; this.providerMapKey = providerMapKey; this.entrySetBinder = (RealMultibinder<Entry<K, Provider<V>>>) entrySetBinder; this.binder = binder; } /** * This creates two bindings. One for the {@code Map.Entry<K, Provider<V>>} * and another for {@code V}. */ @Override public LinkedBindingBuilder<V> addBinding(K key) { Multibinder.checkNotNull(key, "key"); Multibinder.checkConfiguration(!isInitialized(), "MapBinder was already initialized"); Key<V> valueKey = Key.get(valueType, new RealElement(entrySetBinder.getSetName())); entrySetBinder.addBinding().toInstance(new MapEntry<K, Provider<V>>(key, binder.getProvider(valueKey))); return binder.bind(valueKey); } public void configure(Binder binder) { Multibinder.checkConfiguration(!isInitialized(), "MapBinder was already initialized"); final ImmutableSet<Dependency<?>> dependencies = ImmutableSet.<Dependency<?>>of(Dependency.get(entrySetBinder.getSetKey())); // binds a Map<K, Provider<V>> from a collection of Map<Entry<K, Provider<V>> final Provider<Set<Entry<K, Provider<V>>>> entrySetProvider = binder .getProvider(entrySetBinder.getSetKey()); binder.bind(providerMapKey).toProvider(new ProviderWithDependencies<Map<K, Provider<V>>>() { private Map<K, Provider<V>> providerMap; @SuppressWarnings("unused") @Inject void initialize() { RealMapBinder.this.binder = null; Map<K, Provider<V>> providerMapMutable = new LinkedHashMap<K, Provider<V>>(); for (Entry<K, Provider<V>> entry : entrySetProvider.get()) { Multibinder.checkConfiguration(providerMapMutable.put(entry.getKey(), entry.getValue()) == null, "Map injection failed due to duplicated key \"%s\"", entry.getKey()); } providerMap = Collections.unmodifiableMap(providerMapMutable); } public Map<K, Provider<V>> get() { return providerMap; } public Set<Dependency<?>> getDependencies() { return dependencies; } }); final Provider<Map<K, Provider<V>>> mapProvider = binder.getProvider(providerMapKey); binder.bind(mapKey).toProvider(new ProviderWithDependencies<Map<K, V>>() { public Map<K, V> get() { Map<K, V> map = new LinkedHashMap<K, V>(); for (Entry<K, Provider<V>> entry : mapProvider.get().entrySet()) { V value = entry.getValue().get(); K key = entry.getKey(); Multibinder.checkConfiguration(value != null, "Map injection failed due to null value for key \"%s\"", key); map.put(key, value); } return Collections.unmodifiableMap(map); } public Set<Dependency<?>> getDependencies() { return dependencies; } }); } private boolean isInitialized() { return binder == null; } @Override public boolean equals(Object o) { return o instanceof RealMapBinder && ((RealMapBinder<?, ?>) o).mapKey.equals(mapKey); } @Override public int hashCode() { return mapKey.hashCode(); } private static final class MapEntry<K, V> implements Map.Entry<K, V> { private final K key; private final V value; private MapEntry(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { throw new UnsupportedOperationException(); } @Override public boolean equals(Object obj) { return obj instanceof Map.Entry && key.equals(((Map.Entry<?, ?>) obj).getKey()) && value.equals(((Map.Entry<?, ?>) obj).getValue()); } @Override public int hashCode() { return 127 * ("key".hashCode() ^ key.hashCode()) + 127 * ("value".hashCode() ^ value.hashCode()); } @Override public String toString() { return "MapEntry(" + key + ", " + value + ")"; } } }
0true
src_main_java_org_elasticsearch_common_inject_multibindings_MapBinder.java
1,390
public class MetaData implements Iterable<IndexMetaData> { public interface Custom { interface Factory<T extends Custom> { String type(); T readFrom(StreamInput in) throws IOException; void writeTo(T customIndexMetaData, StreamOutput out) throws IOException; T fromXContent(XContentParser parser) throws IOException; void toXContent(T customIndexMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException; /** * Returns true if this custom metadata should be persisted as part of global cluster state */ boolean isPersistent(); } } public static Map<String, Custom.Factory> customFactories = new HashMap<String, Custom.Factory>(); static { // register non plugin custom metadata registerFactory(RepositoriesMetaData.TYPE, RepositoriesMetaData.FACTORY); registerFactory(SnapshotMetaData.TYPE, SnapshotMetaData.FACTORY); registerFactory(RestoreMetaData.TYPE, RestoreMetaData.FACTORY); } /** * Register a custom index meta data factory. Make sure to call it from a static block. */ public static void registerFactory(String type, Custom.Factory factory) { customFactories.put(type, factory); } @Nullable public static <T extends Custom> Custom.Factory<T> lookupFactory(String type) { return customFactories.get(type); } public static <T extends Custom> Custom.Factory<T> lookupFactorySafe(String type) throws ElasticsearchIllegalArgumentException { Custom.Factory<T> factory = customFactories.get(type); if (factory == null) { throw new ElasticsearchIllegalArgumentException("No custom index metadata factory registered for type [" + type + "]"); } return factory; } public static final String SETTING_READ_ONLY = "cluster.blocks.read_only"; public static final ClusterBlock CLUSTER_READ_ONLY_BLOCK = new ClusterBlock(6, "cluster read-only (api)", false, false, RestStatus.FORBIDDEN, ClusterBlockLevel.WRITE, ClusterBlockLevel.METADATA); public static final MetaData EMPTY_META_DATA = builder().build(); public static final String GLOBAL_PERSISTENT_ONLY_PARAM = "global_persistent_only"; private final String uuid; private final long version; private final Settings transientSettings; private final Settings persistentSettings; private final Settings settings; private final ImmutableOpenMap<String, IndexMetaData> indices; private final ImmutableOpenMap<String, IndexTemplateMetaData> templates; private final ImmutableOpenMap<String, Custom> customs; private final transient int totalNumberOfShards; // Transient ? not serializable anyway? private final int numberOfShards; private final String[] allIndices; private final String[] allOpenIndices; private final String[] allClosedIndices; private final ImmutableOpenMap<String, ImmutableOpenMap<String, AliasMetaData>> aliases; private final ImmutableOpenMap<String, String[]> aliasAndIndexToIndexMap; @SuppressWarnings("unchecked") MetaData(String uuid, long version, Settings transientSettings, Settings persistentSettings, ImmutableOpenMap<String, IndexMetaData> indices, ImmutableOpenMap<String, IndexTemplateMetaData> templates, ImmutableOpenMap<String, Custom> customs) { this.uuid = uuid; this.version = version; this.transientSettings = transientSettings; this.persistentSettings = persistentSettings; this.settings = ImmutableSettings.settingsBuilder().put(persistentSettings).put(transientSettings).build(); this.indices = indices; this.customs = customs; this.templates = templates; int totalNumberOfShards = 0; int numberOfShards = 0; int numAliases = 0; for (ObjectCursor<IndexMetaData> cursor : indices.values()) { totalNumberOfShards += cursor.value.totalNumberOfShards(); numberOfShards += cursor.value.numberOfShards(); numAliases += cursor.value.aliases().size(); } this.totalNumberOfShards = totalNumberOfShards; this.numberOfShards = numberOfShards; // build all indices map List<String> allIndicesLst = Lists.newArrayList(); for (ObjectCursor<IndexMetaData> cursor : indices.values()) { allIndicesLst.add(cursor.value.index()); } allIndices = allIndicesLst.toArray(new String[allIndicesLst.size()]); int numIndices = allIndicesLst.size(); List<String> allOpenIndices = Lists.newArrayList(); List<String> allClosedIndices = Lists.newArrayList(); for (ObjectCursor<IndexMetaData> cursor : indices.values()) { IndexMetaData indexMetaData = cursor.value; if (indexMetaData.state() == IndexMetaData.State.OPEN) { allOpenIndices.add(indexMetaData.index()); } else if (indexMetaData.state() == IndexMetaData.State.CLOSE) { allClosedIndices.add(indexMetaData.index()); } } this.allOpenIndices = allOpenIndices.toArray(new String[allOpenIndices.size()]); this.allClosedIndices = allClosedIndices.toArray(new String[allClosedIndices.size()]); // build aliases map ImmutableOpenMap.Builder<String, Object> tmpAliases = ImmutableOpenMap.builder(numAliases); for (ObjectCursor<IndexMetaData> cursor : indices.values()) { IndexMetaData indexMetaData = cursor.value; String index = indexMetaData.index(); for (ObjectCursor<AliasMetaData> aliasCursor : indexMetaData.aliases().values()) { AliasMetaData aliasMd = aliasCursor.value; ImmutableOpenMap.Builder<String, AliasMetaData> indexAliasMap = (ImmutableOpenMap.Builder<String, AliasMetaData>) tmpAliases.get(aliasMd.alias()); if (indexAliasMap == null) { indexAliasMap = ImmutableOpenMap.builder(indices.size()); tmpAliases.put(aliasMd.alias(), indexAliasMap); } indexAliasMap.put(index, aliasMd); } } for (ObjectCursor<String> cursor : tmpAliases.keys()) { String alias = cursor.value; // if there is access to the raw values buffer of the map that the immutable maps wraps, then we don't need to use put, and just set array slots ImmutableOpenMap<String, AliasMetaData> map = ((ImmutableOpenMap.Builder) tmpAliases.get(alias)).cast().build(); tmpAliases.put(alias, map); } this.aliases = tmpAliases.<String, ImmutableOpenMap<String, AliasMetaData>>cast().build(); ImmutableOpenMap.Builder<String, Object> aliasAndIndexToIndexMap = ImmutableOpenMap.builder(numAliases + numIndices); for (ObjectCursor<IndexMetaData> cursor : indices.values()) { IndexMetaData indexMetaData = cursor.value; ObjectArrayList<String> indicesLst = (ObjectArrayList<String>) aliasAndIndexToIndexMap.get(indexMetaData.index()); if (indicesLst == null) { indicesLst = new ObjectArrayList<String>(); aliasAndIndexToIndexMap.put(indexMetaData.index(), indicesLst); } indicesLst.add(indexMetaData.index()); for (ObjectCursor<String> cursor1 : indexMetaData.aliases().keys()) { String alias = cursor1.value; indicesLst = (ObjectArrayList<String>) aliasAndIndexToIndexMap.get(alias); if (indicesLst == null) { indicesLst = new ObjectArrayList<String>(); aliasAndIndexToIndexMap.put(alias, indicesLst); } indicesLst.add(indexMetaData.index()); } } for (ObjectObjectCursor<String, Object> cursor : aliasAndIndexToIndexMap) { String[] indicesLst = ((ObjectArrayList<String>) cursor.value).toArray(String.class); aliasAndIndexToIndexMap.put(cursor.key, indicesLst); } this.aliasAndIndexToIndexMap = aliasAndIndexToIndexMap.<String, String[]>cast().build(); } public long version() { return this.version; } public String uuid() { return this.uuid; } /** * Returns the merges transient and persistent settings. */ public Settings settings() { return this.settings; } public Settings transientSettings() { return this.transientSettings; } public Settings persistentSettings() { return this.persistentSettings; } public ImmutableOpenMap<String, ImmutableOpenMap<String, AliasMetaData>> aliases() { return this.aliases; } public ImmutableOpenMap<String, ImmutableOpenMap<String, AliasMetaData>> getAliases() { return aliases(); } /** * Finds the specific index aliases that match with the specified aliases directly or partially via wildcards and * that point to the specified concrete indices or match partially with the indices via wildcards. * * @param aliases The names of the index aliases to find * @param concreteIndices The concrete indexes the index aliases must point to order to be returned. * @return the found index aliases grouped by index */ public ImmutableOpenMap<String, ImmutableList<AliasMetaData>> findAliases(final String[] aliases, String[] concreteIndices) { assert aliases != null; assert concreteIndices != null; if (concreteIndices.length == 0) { return ImmutableOpenMap.of(); } boolean matchAllAliases = matchAllAliases(aliases); ImmutableOpenMap.Builder<String, ImmutableList<AliasMetaData>> mapBuilder = ImmutableOpenMap.builder(); Iterable<String> intersection = HppcMaps.intersection(ObjectOpenHashSet.from(concreteIndices), indices.keys()); for (String index : intersection) { IndexMetaData indexMetaData = indices.get(index); List<AliasMetaData> filteredValues = Lists.newArrayList(); for (ObjectCursor<AliasMetaData> cursor : indexMetaData.getAliases().values()) { AliasMetaData value = cursor.value; if (matchAllAliases || Regex.simpleMatch(aliases, value.alias())) { filteredValues.add(value); } } if (!filteredValues.isEmpty()) { mapBuilder.put(index, ImmutableList.copyOf(filteredValues)); } } return mapBuilder.build(); } private boolean matchAllAliases(final String[] aliases) { for (String alias : aliases) { if (alias.equals("_all")) { return true; } } return aliases.length == 0; } /** * Checks if at least one of the specified aliases exists in the specified concrete indices. Wildcards are supported in the * alias names for partial matches. * * @param aliases The names of the index aliases to find * @param concreteIndices The concrete indexes the index aliases must point to order to be returned. * @return whether at least one of the specified aliases exists in one of the specified concrete indices. */ public boolean hasAliases(final String[] aliases, String[] concreteIndices) { assert aliases != null; assert concreteIndices != null; if (concreteIndices.length == 0) { return false; } Iterable<String> intersection = HppcMaps.intersection(ObjectOpenHashSet.from(concreteIndices), indices.keys()); for (String index : intersection) { IndexMetaData indexMetaData = indices.get(index); List<AliasMetaData> filteredValues = Lists.newArrayList(); for (ObjectCursor<AliasMetaData> cursor : indexMetaData.getAliases().values()) { AliasMetaData value = cursor.value; if (Regex.simpleMatch(aliases, value.alias())) { filteredValues.add(value); } } if (!filteredValues.isEmpty()) { return true; } } return false; } /* * Finds all mappings for types and concrete indices. Types are expanded to * include all types that match the glob patterns in the types array. Empty * types array, null or {"_all"} will be expanded to all types available for * the given indices. */ public ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> findMappings(String[] concreteIndices, final String[] types) { assert types != null; assert concreteIndices != null; if (concreteIndices.length == 0) { return ImmutableOpenMap.of(); } ImmutableOpenMap.Builder<String, ImmutableOpenMap<String, MappingMetaData>> indexMapBuilder = ImmutableOpenMap.builder(); Iterable<String> intersection = HppcMaps.intersection(ObjectOpenHashSet.from(concreteIndices), indices.keys()); for (String index : intersection) { IndexMetaData indexMetaData = indices.get(index); ImmutableOpenMap.Builder<String, MappingMetaData> filteredMappings; if (isAllTypes(types)) { indexMapBuilder.put(index, indexMetaData.getMappings()); // No types specified means get it all } else { filteredMappings = ImmutableOpenMap.builder(); for (ObjectObjectCursor<String, MappingMetaData> cursor : indexMetaData.mappings()) { if (Regex.simpleMatch(types, cursor.key)) { filteredMappings.put(cursor.key, cursor.value); } } if (!filteredMappings.isEmpty()) { indexMapBuilder.put(index, filteredMappings.build()); } } } return indexMapBuilder.build(); } public ImmutableOpenMap<String, ImmutableList<IndexWarmersMetaData.Entry>> findWarmers(String[] concreteIndices, final String[] types, final String[] uncheckedWarmers) { assert uncheckedWarmers != null; assert concreteIndices != null; if (concreteIndices.length == 0) { return ImmutableOpenMap.of(); } // special _all check to behave the same like not specifying anything for the warmers (not for the indices) final String[] warmers = Strings.isAllOrWildcard(uncheckedWarmers) ? Strings.EMPTY_ARRAY : uncheckedWarmers; ImmutableOpenMap.Builder<String, ImmutableList<IndexWarmersMetaData.Entry>> mapBuilder = ImmutableOpenMap.builder(); Iterable<String> intersection = HppcMaps.intersection(ObjectOpenHashSet.from(concreteIndices), indices.keys()); for (String index : intersection) { IndexMetaData indexMetaData = indices.get(index); IndexWarmersMetaData indexWarmersMetaData = indexMetaData.custom(IndexWarmersMetaData.TYPE); if (indexWarmersMetaData == null || indexWarmersMetaData.entries().isEmpty()) { continue; } Collection<IndexWarmersMetaData.Entry> filteredWarmers = Collections2.filter(indexWarmersMetaData.entries(), new Predicate<IndexWarmersMetaData.Entry>() { @Override public boolean apply(IndexWarmersMetaData.Entry warmer) { if (warmers.length != 0 && types.length != 0) { return Regex.simpleMatch(warmers, warmer.name()) && Regex.simpleMatch(types, warmer.types()); } else if (warmers.length != 0) { return Regex.simpleMatch(warmers, warmer.name()); } else if (types.length != 0) { return Regex.simpleMatch(types, warmer.types()); } else { return true; } } }); if (!filteredWarmers.isEmpty()) { mapBuilder.put(index, ImmutableList.copyOf(filteredWarmers)); } } return mapBuilder.build(); } /** * Returns all the concrete indices. */ public String[] concreteAllIndices() { return allIndices; } public String[] getConcreteAllIndices() { return concreteAllIndices(); } public String[] concreteAllOpenIndices() { return allOpenIndices; } public String[] getConcreteAllOpenIndices() { return allOpenIndices; } public String[] concreteAllClosedIndices() { return allClosedIndices; } public String[] getConcreteAllClosedIndices() { return allClosedIndices; } /** * Returns indexing routing for the given index. */ public String resolveIndexRouting(@Nullable String routing, String aliasOrIndex) { // Check if index is specified by an alias ImmutableOpenMap<String, AliasMetaData> indexAliases = aliases.get(aliasOrIndex); if (indexAliases == null || indexAliases.isEmpty()) { return routing; } if (indexAliases.size() > 1) { throw new ElasticsearchIllegalArgumentException("Alias [" + aliasOrIndex + "] has more than one index associated with it [" + Arrays.toString(indexAliases.keys().toArray(String.class)) + "], can't execute a single index op"); } AliasMetaData aliasMd = indexAliases.values().iterator().next().value; if (aliasMd.indexRouting() != null) { if (routing != null) { if (!routing.equals(aliasMd.indexRouting())) { throw new ElasticsearchIllegalArgumentException("Alias [" + aliasOrIndex + "] has index routing associated with it [" + aliasMd.indexRouting() + "], and was provided with routing value [" + routing + "], rejecting operation"); } } routing = aliasMd.indexRouting(); } if (routing != null) { if (routing.indexOf(',') != -1) { throw new ElasticsearchIllegalArgumentException("index/alias [" + aliasOrIndex + "] provided with routing value [" + routing + "] that resolved to several routing values, rejecting operation"); } } return routing; } public Map<String, Set<String>> resolveSearchRouting(@Nullable String routing, String aliasOrIndex) { return resolveSearchRouting(routing, convertFromWildcards(new String[]{aliasOrIndex}, IndicesOptions.lenient())); } public Map<String, Set<String>> resolveSearchRouting(@Nullable String routing, String[] aliasesOrIndices) { if (isAllIndices(aliasesOrIndices)) { return resolveSearchRoutingAllIndices(routing); } aliasesOrIndices = convertFromWildcards(aliasesOrIndices, IndicesOptions.lenient()); if (aliasesOrIndices.length == 1) { return resolveSearchRoutingSingleValue(routing, aliasesOrIndices[0]); } Map<String, Set<String>> routings = null; Set<String> paramRouting = null; // List of indices that don't require any routing Set<String> norouting = new HashSet<String>(); if (routing != null) { paramRouting = Strings.splitStringByCommaToSet(routing); } for (String aliasOrIndex : aliasesOrIndices) { ImmutableOpenMap<String, AliasMetaData> indexToRoutingMap = aliases.get(aliasOrIndex); if (indexToRoutingMap != null && !indexToRoutingMap.isEmpty()) { for (ObjectObjectCursor<String, AliasMetaData> indexRouting : indexToRoutingMap) { if (!norouting.contains(indexRouting.key)) { if (!indexRouting.value.searchRoutingValues().isEmpty()) { // Routing alias if (routings == null) { routings = newHashMap(); } Set<String> r = routings.get(indexRouting.key); if (r == null) { r = new HashSet<String>(); routings.put(indexRouting.key, r); } r.addAll(indexRouting.value.searchRoutingValues()); if (paramRouting != null) { r.retainAll(paramRouting); } if (r.isEmpty()) { routings.remove(indexRouting.key); } } else { // Non-routing alias if (!norouting.contains(indexRouting.key)) { norouting.add(indexRouting.key); if (paramRouting != null) { Set<String> r = new HashSet<String>(paramRouting); if (routings == null) { routings = newHashMap(); } routings.put(indexRouting.key, r); } else { if (routings != null) { routings.remove(indexRouting.key); } } } } } } } else { // Index if (!norouting.contains(aliasOrIndex)) { norouting.add(aliasOrIndex); if (paramRouting != null) { Set<String> r = new HashSet<String>(paramRouting); if (routings == null) { routings = newHashMap(); } routings.put(aliasOrIndex, r); } else { if (routings != null) { routings.remove(aliasOrIndex); } } } } } if (routings == null || routings.isEmpty()) { return null; } return routings; } private Map<String, Set<String>> resolveSearchRoutingSingleValue(@Nullable String routing, String aliasOrIndex) { Map<String, Set<String>> routings = null; Set<String> paramRouting = null; if (routing != null) { paramRouting = Strings.splitStringByCommaToSet(routing); } ImmutableOpenMap<String, AliasMetaData> indexToRoutingMap = aliases.get(aliasOrIndex); if (indexToRoutingMap != null && !indexToRoutingMap.isEmpty()) { // It's an alias for (ObjectObjectCursor<String, AliasMetaData> indexRouting : indexToRoutingMap) { if (!indexRouting.value.searchRoutingValues().isEmpty()) { // Routing alias Set<String> r = new HashSet<String>(indexRouting.value.searchRoutingValues()); if (paramRouting != null) { r.retainAll(paramRouting); } if (!r.isEmpty()) { if (routings == null) { routings = newHashMap(); } routings.put(indexRouting.key, r); } } else { // Non-routing alias if (paramRouting != null) { Set<String> r = new HashSet<String>(paramRouting); if (routings == null) { routings = newHashMap(); } routings.put(indexRouting.key, r); } } } } else { // It's an index if (paramRouting != null) { routings = ImmutableMap.of(aliasOrIndex, paramRouting); } } return routings; } /** * Sets the same routing for all indices */ private Map<String, Set<String>> resolveSearchRoutingAllIndices(String routing) { if (routing != null) { Set<String> r = Strings.splitStringByCommaToSet(routing); Map<String, Set<String>> routings = newHashMap(); String[] concreteIndices = concreteAllIndices(); for (String index : concreteIndices) { routings.put(index, r); } return routings; } return null; } /** * Translates the provided indices (possibly aliased) into actual indices. */ public String[] concreteIndices(String[] indices) throws IndexMissingException { return concreteIndices(indices, IndicesOptions.fromOptions(false, true, true, true)); } /** * Translates the provided indices (possibly aliased) into actual indices. */ public String[] concreteIndicesIgnoreMissing(String[] indices) { return concreteIndices(indices, IndicesOptions.fromOptions(true, true, true, false)); } /** * Translates the provided indices (possibly aliased) into actual indices. */ public String[] concreteIndices(String[] aliasesOrIndices, IndicesOptions indicesOptions) throws IndexMissingException { if (isAllIndices(aliasesOrIndices)) { String[] concreteIndices; if (indicesOptions.expandWildcardsOpen() && indicesOptions.expandWildcardsClosed()) { concreteIndices = concreteAllIndices(); } else if (indicesOptions.expandWildcardsOpen()) { concreteIndices = concreteAllOpenIndices(); } else if (indicesOptions.expandWildcardsClosed()) { concreteIndices = concreteAllClosedIndices(); } else { assert false : "Shouldn't end up here"; concreteIndices = Strings.EMPTY_ARRAY; } if (!indicesOptions.allowNoIndices() && concreteIndices.length == 0) { throw new IndexMissingException(new Index("_all")); } return concreteIndices; } aliasesOrIndices = convertFromWildcards(aliasesOrIndices, indicesOptions); // optimize for single element index (common case) if (aliasesOrIndices.length == 1) { String aliasOrIndex = aliasesOrIndices[0]; // if a direct index name, just return the array provided if (this.indices.containsKey(aliasOrIndex)) { return aliasesOrIndices; } String[] actualLst = aliasAndIndexToIndexMap.getOrDefault(aliasOrIndex, Strings.EMPTY_ARRAY); if (!indicesOptions.allowNoIndices() && actualLst == null) { throw new IndexMissingException(new Index(aliasOrIndex)); } else { return actualLst; } } // check if its a possible aliased index, if not, just return the // passed array boolean possiblyAliased = false; for (String index : aliasesOrIndices) { if (!this.indices.containsKey(index)) { possiblyAliased = true; break; } } if (!possiblyAliased) { return aliasesOrIndices; } Set<String> actualIndices = new HashSet<String>(); for (String index : aliasesOrIndices) { String[] actualLst = aliasAndIndexToIndexMap.get(index); if (actualLst == null) { if (!indicesOptions.ignoreUnavailable()) { throw new IndexMissingException(new Index(index)); } } else { for (String x : actualLst) { actualIndices.add(x); } } } if (!indicesOptions.allowNoIndices() && actualIndices.isEmpty()) { throw new IndexMissingException(new Index(Arrays.toString(aliasesOrIndices))); } return actualIndices.toArray(new String[actualIndices.size()]); } public String concreteIndex(String index) throws IndexMissingException, ElasticsearchIllegalArgumentException { // a quick check, if this is an actual index, if so, return it if (indices.containsKey(index)) { return index; } // not an actual index, fetch from an alias String[] lst = aliasAndIndexToIndexMap.get(index); if (lst == null) { throw new IndexMissingException(new Index(index)); } if (lst.length > 1) { throw new ElasticsearchIllegalArgumentException("Alias [" + index + "] has more than one indices associated with it [" + Arrays.toString(lst) + "], can't execute a single index op"); } return lst[0]; } /** * Converts a list of indices or aliases wildcards, and special +/- signs, into their respective full matches. It * won't convert only to indices, but also to aliases. For example, alias_* will expand to alias_1 and alias_2, not * to the respective indices those aliases point to. */ public String[] convertFromWildcards(String[] aliasesOrIndices, IndicesOptions indicesOptions) { if (aliasesOrIndices == null) { return null; } Set<String> result = null; for (int i = 0; i < aliasesOrIndices.length; i++) { String aliasOrIndex = aliasesOrIndices[i]; if (aliasAndIndexToIndexMap.containsKey(aliasOrIndex)) { if (result != null) { result.add(aliasOrIndex); } continue; } boolean add = true; if (aliasOrIndex.charAt(0) == '+') { // if its the first, add empty result set if (i == 0) { result = new HashSet<String>(); } add = true; aliasOrIndex = aliasOrIndex.substring(1); } else if (aliasOrIndex.charAt(0) == '-') { // if its the first, fill it with all the indices... if (i == 0) { String[] concreteIndices; if (indicesOptions.expandWildcardsOpen() && indicesOptions.expandWildcardsClosed()) { concreteIndices = concreteAllIndices(); } else if (indicesOptions.expandWildcardsOpen()) { concreteIndices = concreteAllOpenIndices(); } else if (indicesOptions.expandWildcardsClosed()) { concreteIndices = concreteAllClosedIndices(); } else { assert false : "Shouldn't end up here"; concreteIndices = Strings.EMPTY_ARRAY; } result = new HashSet<String>(Arrays.asList(concreteIndices)); } add = false; aliasOrIndex = aliasOrIndex.substring(1); } if (!Regex.isSimpleMatchPattern(aliasOrIndex)) { if (!indicesOptions.ignoreUnavailable() && !aliasAndIndexToIndexMap.containsKey(aliasOrIndex)) { throw new IndexMissingException(new Index(aliasOrIndex)); } if (result != null) { if (add) { result.add(aliasOrIndex); } else { result.remove(aliasOrIndex); } } continue; } if (result == null) { // add all the previous ones... result = new HashSet<String>(); result.addAll(Arrays.asList(aliasesOrIndices).subList(0, i)); } String[] indices; if (indicesOptions.expandWildcardsOpen() && indicesOptions.expandWildcardsClosed()) { indices = concreteAllIndices(); } else if (indicesOptions.expandWildcardsOpen()) { indices = concreteAllOpenIndices(); } else if (indicesOptions.expandWildcardsClosed()) { indices = concreteAllClosedIndices(); } else { assert false : "Shouldn't end up here"; indices = Strings.EMPTY_ARRAY; } boolean found = false; // iterating over all concrete indices and see if there is a wildcard match for (String index : indices) { if (Regex.simpleMatch(aliasOrIndex, index)) { found = true; if (add) { result.add(index); } else { result.remove(index); } } } // iterating over all aliases and see if there is a wildcard match for (ObjectCursor<String> cursor : aliases.keys()) { String alias = cursor.value; if (Regex.simpleMatch(aliasOrIndex, alias)) { found = true; if (add) { result.add(alias); } else { result.remove(alias); } } } if (!found && !indicesOptions.allowNoIndices()) { throw new IndexMissingException(new Index(aliasOrIndex)); } } if (result == null) { return aliasesOrIndices; } if (result.isEmpty() && !indicesOptions.allowNoIndices()) { throw new IndexMissingException(new Index(Arrays.toString(aliasesOrIndices))); } return result.toArray(new String[result.size()]); } public boolean hasIndex(String index) { return indices.containsKey(index); } public boolean hasConcreteIndex(String index) { return aliasAndIndexToIndexMap.containsKey(index); } public IndexMetaData index(String index) { return indices.get(index); } public ImmutableOpenMap<String, IndexMetaData> indices() { return this.indices; } public ImmutableOpenMap<String, IndexMetaData> getIndices() { return indices(); } public ImmutableOpenMap<String, IndexTemplateMetaData> templates() { return this.templates; } public ImmutableOpenMap<String, IndexTemplateMetaData> getTemplates() { return this.templates; } public ImmutableOpenMap<String, Custom> customs() { return this.customs; } public ImmutableOpenMap<String, Custom> getCustoms() { return this.customs; } public <T extends Custom> T custom(String type) { return (T) customs.get(type); } public int totalNumberOfShards() { return this.totalNumberOfShards; } public int getTotalNumberOfShards() { return totalNumberOfShards(); } public int numberOfShards() { return this.numberOfShards; } public int getNumberOfShards() { return numberOfShards(); } /** * Iterates through the list of indices and selects the effective list of filtering aliases for the * given index. * <p/> * <p>Only aliases with filters are returned. If the indices list contains a non-filtering reference to * the index itself - null is returned. Returns <tt>null</tt> if no filtering is required.</p> */ public String[] filteringAliases(String index, String... indicesOrAliases) { // expand the aliases wildcard indicesOrAliases = convertFromWildcards(indicesOrAliases, IndicesOptions.lenient()); if (isAllIndices(indicesOrAliases)) { return null; } // optimize for the most common single index/alias scenario if (indicesOrAliases.length == 1) { String alias = indicesOrAliases[0]; IndexMetaData indexMetaData = this.indices.get(index); if (indexMetaData == null) { // Shouldn't happen throw new IndexMissingException(new Index(index)); } AliasMetaData aliasMetaData = indexMetaData.aliases().get(alias); boolean filteringRequired = aliasMetaData != null && aliasMetaData.filteringRequired(); if (!filteringRequired) { return null; } return new String[]{alias}; } List<String> filteringAliases = null; for (String alias : indicesOrAliases) { if (alias.equals(index)) { return null; } IndexMetaData indexMetaData = this.indices.get(index); if (indexMetaData == null) { // Shouldn't happen throw new IndexMissingException(new Index(index)); } AliasMetaData aliasMetaData = indexMetaData.aliases().get(alias); // Check that this is an alias for the current index // Otherwise - skip it if (aliasMetaData != null) { boolean filteringRequired = aliasMetaData.filteringRequired(); if (filteringRequired) { // If filtering required - add it to the list of filters if (filteringAliases == null) { filteringAliases = newArrayList(); } filteringAliases.add(alias); } else { // If not, we have a non filtering alias for this index - no filtering needed return null; } } } if (filteringAliases == null) { return null; } return filteringAliases.toArray(new String[filteringAliases.size()]); } /** * Identifies whether the array containing index names given as argument refers to all indices * The empty or null array identifies all indices * * @param aliasesOrIndices the array containing index names * @return true if the provided array maps to all indices, false otherwise */ public boolean isAllIndices(String[] aliasesOrIndices) { return aliasesOrIndices == null || aliasesOrIndices.length == 0 || isExplicitAllPattern(aliasesOrIndices); } /** * Identifies whether the array containing type names given as argument refers to all types * The empty or null array identifies all types * * @param types the array containing index names * @return true if the provided array maps to all indices, false otherwise */ public boolean isAllTypes(String[] types) { return types == null || types.length == 0 || isExplicitAllPattern(types); } /** * Identifies whether the array containing index names given as argument explicitly refers to all indices * The empty or null array doesn't explicitly map to all indices * * @param aliasesOrIndices the array containing index names * @return true if the provided array explicitly maps to all indices, false otherwise */ public boolean isExplicitAllPattern(String[] aliasesOrIndices) { return aliasesOrIndices != null && aliasesOrIndices.length == 1 && "_all".equals(aliasesOrIndices[0]); } /** * Identifies whether the first argument (an array containing index names) is a pattern that matches all indices * * @param indicesOrAliases the array containing index names * @param concreteIndices array containing the concrete indices that the first argument refers to * @return true if the first argument is a pattern that maps to all available indices, false otherwise */ public boolean isPatternMatchingAllIndices(String[] indicesOrAliases, String[] concreteIndices) { // if we end up matching on all indices, check, if its a wildcard parameter, or a "-something" structure if (concreteIndices.length == concreteAllIndices().length && indicesOrAliases.length > 0) { //we might have something like /-test1,+test1 that would identify all indices //or something like /-test1 with test1 index missing and IndicesOptions.lenient() if (indicesOrAliases[0].charAt(0) == '-') { return true; } //otherwise we check if there's any simple regex for (String indexOrAlias : indicesOrAliases) { if (Regex.isSimpleMatchPattern(indexOrAlias)) { return true; } } } return false; } /** * @param concreteIndex The concrete index to check if routing is required * @param type The type to check if routing is required * @return Whether routing is required according to the mapping for the specified index and type */ public boolean routingRequired(String concreteIndex, String type) { IndexMetaData indexMetaData = indices.get(concreteIndex); if (indexMetaData != null) { MappingMetaData mappingMetaData = indexMetaData.getMappings().get(type); if (mappingMetaData != null) { return mappingMetaData.routing().required(); } } return false; } @Override public UnmodifiableIterator<IndexMetaData> iterator() { return indices.valuesIt(); } public static boolean isGlobalStateEquals(MetaData metaData1, MetaData metaData2) { if (!metaData1.persistentSettings.equals(metaData2.persistentSettings)) { return false; } if (!metaData1.templates.equals(metaData2.templates())) { return false; } // Check if any persistent metadata needs to be saved int customCount1 = 0; for (ObjectObjectCursor<String, Custom> cursor : metaData1.customs) { if (customFactories.get(cursor.key).isPersistent()) { if (!cursor.equals(metaData2.custom(cursor.key))) return false; customCount1++; } } int customCount2 = 0; for (ObjectObjectCursor<String, Custom> cursor : metaData2.customs) { if (customFactories.get(cursor.key).isPersistent()) { customCount2++; } } if (customCount1 != customCount2) return false; return true; } public static Builder builder() { return new Builder(); } public static Builder builder(MetaData metaData) { return new Builder(metaData); } public static class Builder { private String uuid; private long version; private Settings transientSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; private Settings persistentSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; private final ImmutableOpenMap.Builder<String, IndexMetaData> indices; private final ImmutableOpenMap.Builder<String, IndexTemplateMetaData> templates; private final ImmutableOpenMap.Builder<String, Custom> customs; public Builder() { uuid = "_na_"; indices = ImmutableOpenMap.builder(); templates = ImmutableOpenMap.builder(); customs = ImmutableOpenMap.builder(); } public Builder(MetaData metaData) { this.uuid = metaData.uuid; this.transientSettings = metaData.transientSettings; this.persistentSettings = metaData.persistentSettings; this.version = metaData.version; this.indices = ImmutableOpenMap.builder(metaData.indices); this.templates = ImmutableOpenMap.builder(metaData.templates); this.customs = ImmutableOpenMap.builder(metaData.customs); } public Builder put(IndexMetaData.Builder indexMetaDataBuilder) { // we know its a new one, increment the version and store indexMetaDataBuilder.version(indexMetaDataBuilder.version() + 1); IndexMetaData indexMetaData = indexMetaDataBuilder.build(); indices.put(indexMetaData.index(), indexMetaData); return this; } public Builder put(IndexMetaData indexMetaData, boolean incrementVersion) { if (indices.get(indexMetaData.index()) == indexMetaData) { return this; } // if we put a new index metadata, increment its version if (incrementVersion) { indexMetaData = IndexMetaData.builder(indexMetaData).version(indexMetaData.version() + 1).build(); } indices.put(indexMetaData.index(), indexMetaData); return this; } public IndexMetaData get(String index) { return indices.get(index); } public Builder remove(String index) { indices.remove(index); return this; } public Builder removeAllIndices() { indices.clear(); return this; } public Builder put(IndexTemplateMetaData.Builder template) { return put(template.build()); } public Builder put(IndexTemplateMetaData template) { templates.put(template.name(), template); return this; } public Builder removeTemplate(String templateName) { templates.remove(templateName); return this; } public Custom getCustom(String type) { return customs.get(type); } public Builder putCustom(String type, Custom custom) { customs.put(type, custom); return this; } public Builder removeCustom(String type) { customs.remove(type); return this; } public Builder updateSettings(Settings settings, String... indices) { if (indices == null || indices.length == 0) { indices = this.indices.keys().toArray(String.class); } for (String index : indices) { IndexMetaData indexMetaData = this.indices.get(index); if (indexMetaData == null) { throw new IndexMissingException(new Index(index)); } put(IndexMetaData.builder(indexMetaData) .settings(settingsBuilder().put(indexMetaData.settings()).put(settings))); } return this; } public Builder updateNumberOfReplicas(int numberOfReplicas, String... indices) { if (indices == null || indices.length == 0) { indices = this.indices.keys().toArray(String.class); } for (String index : indices) { IndexMetaData indexMetaData = this.indices.get(index); if (indexMetaData == null) { throw new IndexMissingException(new Index(index)); } put(IndexMetaData.builder(indexMetaData).numberOfReplicas(numberOfReplicas)); } return this; } public Settings transientSettings() { return this.transientSettings; } public Builder transientSettings(Settings settings) { this.transientSettings = settings; return this; } public Settings persistentSettings() { return this.persistentSettings; } public Builder persistentSettings(Settings settings) { this.persistentSettings = settings; return this; } public Builder version(long version) { this.version = version; return this; } public Builder generateUuidIfNeeded() { if (uuid.equals("_na_")) { uuid = Strings.randomBase64UUID(); } return this; } public MetaData build() { return new MetaData(uuid, version, transientSettings, persistentSettings, indices.build(), templates.build(), customs.build()); } public static String toXContent(MetaData metaData) throws IOException { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.startObject(); toXContent(metaData, builder, ToXContent.EMPTY_PARAMS); builder.endObject(); return builder.string(); } public static void toXContent(MetaData metaData, XContentBuilder builder, ToXContent.Params params) throws IOException { boolean globalPersistentOnly = params.paramAsBoolean(GLOBAL_PERSISTENT_ONLY_PARAM, false); builder.startObject("meta-data"); builder.field("version", metaData.version()); builder.field("uuid", metaData.uuid); if (!metaData.persistentSettings().getAsMap().isEmpty()) { builder.startObject("settings"); for (Map.Entry<String, String> entry : metaData.persistentSettings().getAsMap().entrySet()) { builder.field(entry.getKey(), entry.getValue()); } builder.endObject(); } if (!globalPersistentOnly && !metaData.transientSettings().getAsMap().isEmpty()) { builder.startObject("transient_settings"); for (Map.Entry<String, String> entry : metaData.transientSettings().getAsMap().entrySet()) { builder.field(entry.getKey(), entry.getValue()); } builder.endObject(); } builder.startObject("templates"); for (ObjectCursor<IndexTemplateMetaData> cursor : metaData.templates().values()) { IndexTemplateMetaData.Builder.toXContent(cursor.value, builder, params); } builder.endObject(); if (!globalPersistentOnly && !metaData.indices().isEmpty()) { builder.startObject("indices"); for (IndexMetaData indexMetaData : metaData) { IndexMetaData.Builder.toXContent(indexMetaData, builder, params); } builder.endObject(); } for (ObjectObjectCursor<String, Custom> cursor : metaData.customs()) { Custom.Factory factory = lookupFactorySafe(cursor.key); if (!globalPersistentOnly || factory.isPersistent()) { builder.startObject(cursor.key); factory.toXContent(cursor.value, builder, params); builder.endObject(); } } builder.endObject(); } public static MetaData fromXContent(XContentParser parser) throws IOException { Builder builder = new Builder(); // we might get here after the meta-data element, or on a fresh parser XContentParser.Token token = parser.currentToken(); String currentFieldName = parser.currentName(); if (!"meta-data".equals(currentFieldName)) { token = parser.nextToken(); if (token == XContentParser.Token.START_OBJECT) { // move to the field name (meta-data) token = parser.nextToken(); // move to the next object token = parser.nextToken(); } currentFieldName = parser.currentName(); if (token == null) { // no data... return builder.build(); } } while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { if ("settings".equals(currentFieldName)) { builder.persistentSettings(ImmutableSettings.settingsBuilder().put(SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered())).build()); } else if ("indices".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { builder.put(IndexMetaData.Builder.fromXContent(parser), false); } } else if ("templates".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { builder.put(IndexTemplateMetaData.Builder.fromXContent(parser)); } } else { // check if its a custom index metadata Custom.Factory<Custom> factory = lookupFactory(currentFieldName); if (factory == null) { //TODO warn parser.skipChildren(); } else { builder.putCustom(factory.type(), factory.fromXContent(parser)); } } } else if (token.isValue()) { if ("version".equals(currentFieldName)) { builder.version = parser.longValue(); } else if ("uuid".equals(currentFieldName)) { builder.uuid = parser.text(); } } } return builder.build(); } public static MetaData readFrom(StreamInput in) throws IOException { Builder builder = new Builder(); builder.version = in.readLong(); builder.uuid = in.readString(); builder.transientSettings(readSettingsFromStream(in)); builder.persistentSettings(readSettingsFromStream(in)); int size = in.readVInt(); for (int i = 0; i < size; i++) { builder.put(IndexMetaData.Builder.readFrom(in), false); } size = in.readVInt(); for (int i = 0; i < size; i++) { builder.put(IndexTemplateMetaData.Builder.readFrom(in)); } int customSize = in.readVInt(); for (int i = 0; i < customSize; i++) { String type = in.readString(); Custom customIndexMetaData = lookupFactorySafe(type).readFrom(in); builder.putCustom(type, customIndexMetaData); } return builder.build(); } public static void writeTo(MetaData metaData, StreamOutput out) throws IOException { out.writeLong(metaData.version); out.writeString(metaData.uuid); writeSettingsToStream(metaData.transientSettings(), out); writeSettingsToStream(metaData.persistentSettings(), out); out.writeVInt(metaData.indices.size()); for (IndexMetaData indexMetaData : metaData) { IndexMetaData.Builder.writeTo(indexMetaData, out); } out.writeVInt(metaData.templates.size()); for (ObjectCursor<IndexTemplateMetaData> cursor : metaData.templates.values()) { IndexTemplateMetaData.Builder.writeTo(cursor.value, out); } out.writeVInt(metaData.customs().size()); for (ObjectObjectCursor<String, Custom> cursor : metaData.customs()) { out.writeString(cursor.key); lookupFactorySafe(cursor.key).writeTo(cursor.value, out); } } } }
1no label
src_main_java_org_elasticsearch_cluster_metadata_MetaData.java
3,169
private static class Empty extends DoubleValues { Empty() { super(false); } @Override public int setDocument(int docId) { return 0; } @Override public double nextValue() { throw new ElasticsearchIllegalStateException("Empty DoubleValues has no next value"); } }
0true
src_main_java_org_elasticsearch_index_fielddata_DoubleValues.java
3,569
public class DateFieldMapper extends NumberFieldMapper<Long> { public static final String CONTENT_TYPE = "date"; public static class Defaults extends NumberFieldMapper.Defaults { public static final FormatDateTimeFormatter DATE_TIME_FORMATTER = Joda.forPattern("dateOptionalTime", Locale.ROOT); public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.freeze(); } public static final String NULL_VALUE = null; public static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS; public static final boolean ROUND_CEIL = true; } public static class Builder extends NumberFieldMapper.Builder<Builder, DateFieldMapper> { protected TimeUnit timeUnit = Defaults.TIME_UNIT; protected String nullValue = Defaults.NULL_VALUE; protected FormatDateTimeFormatter dateTimeFormatter = Defaults.DATE_TIME_FORMATTER; private Locale locale; public Builder(String name) { super(name, new FieldType(Defaults.FIELD_TYPE)); builder = this; // do *NOT* rely on the default locale locale = Locale.ROOT; } public Builder timeUnit(TimeUnit timeUnit) { this.timeUnit = timeUnit; return this; } public Builder nullValue(String nullValue) { this.nullValue = nullValue; return this; } public Builder dateTimeFormatter(FormatDateTimeFormatter dateTimeFormatter) { this.dateTimeFormatter = dateTimeFormatter; return this; } @Override public DateFieldMapper build(BuilderContext context) { boolean roundCeil = Defaults.ROUND_CEIL; if (context.indexSettings() != null) { Settings settings = context.indexSettings(); roundCeil = settings.getAsBoolean("index.mapping.date.round_ceil", settings.getAsBoolean("index.mapping.date.parse_upper_inclusive", Defaults.ROUND_CEIL)); } fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f); if (!locale.equals(dateTimeFormatter.locale())) { dateTimeFormatter = new FormatDateTimeFormatter(dateTimeFormatter.format(), dateTimeFormatter.parser(), dateTimeFormatter.printer(), locale); } DateFieldMapper fieldMapper = new DateFieldMapper(buildNames(context), dateTimeFormatter, precisionStep, boost, fieldType, docValues, nullValue, timeUnit, roundCeil, ignoreMalformed(context), coerce(context), postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo); fieldMapper.includeInAll(includeInAll); return fieldMapper; } public Builder locale(Locale locale) { this.locale = locale; return this; } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { DateFieldMapper.Builder builder = dateField(name); parseNumberField(builder, name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("null_value")) { builder.nullValue(propNode.toString()); } else if (propName.equals("format")) { builder.dateTimeFormatter(parseDateTimeFormatter(propName, propNode)); } else if (propName.equals("numeric_resolution")) { builder.timeUnit(TimeUnit.valueOf(propNode.toString().toUpperCase(Locale.ROOT))); } else if (propName.equals("locale")) { builder.locale(parseLocale(propNode.toString())); } } return builder; } } // public for test public static Locale parseLocale(String locale) { final String[] parts = locale.split("_", -1); switch (parts.length) { case 3: // lang_country_variant return new Locale(parts[0], parts[1], parts[2]); case 2: // lang_country return new Locale(parts[0], parts[1]); case 1: if ("ROOT".equalsIgnoreCase(parts[0])) { return Locale.ROOT; } // lang return new Locale(parts[0]); default: throw new ElasticsearchIllegalArgumentException("Can't parse locale: [" + locale + "]"); } } protected FormatDateTimeFormatter dateTimeFormatter; // Triggers rounding up of the upper bound for range queries and filters if // set to true. // Rounding up a date here has the following meaning: If a date is not // defined with full precision, for example, no milliseconds given, the date // will be filled up to the next larger date with that precision. // Example: An upper bound given as "2000-01-01", will be converted to // "2000-01-01T23.59.59.999" private final boolean roundCeil; private final DateMathParser dateMathParser; private String nullValue; protected final TimeUnit timeUnit; protected DateFieldMapper(Names names, FormatDateTimeFormatter dateTimeFormatter, int precisionStep, float boost, FieldType fieldType, Boolean docValues, String nullValue, TimeUnit timeUnit, boolean roundCeil, Explicit<Boolean> ignoreMalformed,Explicit<Boolean> coerce, PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider, SimilarityProvider similarity, Loading normsLoading, @Nullable Settings fieldDataSettings, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) { super(names, precisionStep, boost, fieldType, docValues, ignoreMalformed, coerce, new NamedAnalyzer("_date/" + precisionStep, new NumericDateAnalyzer(precisionStep, dateTimeFormatter.parser())), new NamedAnalyzer("_date/max", new NumericDateAnalyzer(Integer.MAX_VALUE, dateTimeFormatter.parser())), postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, indexSettings, multiFields, copyTo); this.dateTimeFormatter = dateTimeFormatter; this.nullValue = nullValue; this.timeUnit = timeUnit; this.roundCeil = roundCeil; this.dateMathParser = new DateMathParser(dateTimeFormatter, timeUnit); } public FormatDateTimeFormatter dateTimeFormatter() { return dateTimeFormatter; } public DateMathParser dateMathParser() { return dateMathParser; } @Override public FieldType defaultFieldType() { return Defaults.FIELD_TYPE; } @Override public FieldDataType defaultFieldDataType() { return new FieldDataType("long"); } @Override protected int maxPrecisionStep() { return 64; } @Override public Long value(Object value) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof BytesRef) { return Numbers.bytesToLong((BytesRef) value); } return parseStringValue(value.toString()); } /** Dates should return as a string. */ @Override public Object valueForSearch(Object value) { if (value instanceof String) { // assume its the string that was indexed, just return it... (for example, with get) return value; } Long val = value(value); if (val == null) { return null; } return dateTimeFormatter.printer().print(val); } @Override public BytesRef indexedValueForSearch(Object value) { BytesRef bytesRef = new BytesRef(); NumericUtils.longToPrefixCoded(parseValue(value), 0, bytesRef); // 0 because of exact match return bytesRef; } private long parseValue(Object value) { if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof BytesRef) { return dateTimeFormatter.parser().parseMillis(((BytesRef) value).utf8ToString()); } return dateTimeFormatter.parser().parseMillis(value.toString()); } private String convertToString(Object value) { if (value instanceof BytesRef) { return ((BytesRef) value).utf8ToString(); } return value.toString(); } @Override public Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) { long iValue = dateMathParser.parse(value, System.currentTimeMillis()); long iSim; try { iSim = fuzziness.asTimeValue().millis(); } catch (Exception e) { // not a time format iSim = fuzziness.asLong(); } return NumericRangeQuery.newLongRange(names.indexName(), precisionStep, iValue - iSim, iValue + iSim, true, true); } @Override public Query termQuery(Object value, @Nullable QueryParseContext context) { long lValue = parseToMilliseconds(value, context); return NumericRangeQuery.newLongRange(names.indexName(), precisionStep, lValue, lValue, true, true); } public long parseToMilliseconds(Object value, @Nullable QueryParseContext context) { return parseToMilliseconds(value, context, false); } public long parseToMilliseconds(Object value, @Nullable QueryParseContext context, boolean includeUpper) { long now = context == null ? System.currentTimeMillis() : context.nowInMillis(); return includeUpper && roundCeil ? dateMathParser.parseRoundCeil(convertToString(value), now) : dateMathParser.parse(convertToString(value), now); } public long parseToMilliseconds(String value, @Nullable QueryParseContext context, boolean includeUpper) { long now = context == null ? System.currentTimeMillis() : context.nowInMillis(); return includeUpper && roundCeil ? dateMathParser.parseRoundCeil(value, now) : dateMathParser.parse(value, now); } @Override public Filter termFilter(Object value, @Nullable QueryParseContext context) { final long lValue = parseToMilliseconds(value, context); return NumericRangeFilter.newLongRange(names.indexName(), precisionStep, lValue, lValue, true, true); } @Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return NumericRangeQuery.newLongRange(names.indexName(), precisionStep, lowerTerm == null ? null : parseToMilliseconds(lowerTerm, context), upperTerm == null ? null : parseToMilliseconds(upperTerm, context, includeUpper), includeLower, includeUpper); } @Override public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return rangeFilter(lowerTerm, upperTerm, includeLower, includeUpper, context, false); } public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context, boolean explicitCaching) { boolean cache = explicitCaching; Long lowerVal = null; Long upperVal = null; if (lowerTerm != null) { String value = convertToString(lowerTerm); cache = explicitCaching || !hasNowExpressionWithNoRounding(value); lowerVal = parseToMilliseconds(value, context, false); } if (upperTerm != null) { String value = convertToString(upperTerm); cache = explicitCaching || !hasNowExpressionWithNoRounding(value); upperVal = parseToMilliseconds(value, context, includeUpper); } Filter filter = NumericRangeFilter.newLongRange( names.indexName(), precisionStep, lowerVal, upperVal, includeLower, includeUpper ); if (!cache) { // We don't cache range filter if `now` date expression is used and also when a compound filter wraps // a range filter with a `now` date expressions. return NoCacheFilter.wrap(filter); } else { return filter; } } @Override public Filter rangeFilter(IndexFieldDataService fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return rangeFilter(fieldData, lowerTerm, upperTerm, includeLower, includeUpper, context, false); } public Filter rangeFilter(IndexFieldDataService fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context, boolean explicitCaching) { boolean cache = explicitCaching; Long lowerVal = null; Long upperVal = null; if (lowerTerm != null) { String value = convertToString(lowerTerm); cache = explicitCaching || !hasNowExpressionWithNoRounding(value); lowerVal = parseToMilliseconds(value, context, false); } if (upperTerm != null) { String value = convertToString(upperTerm); cache = explicitCaching || !hasNowExpressionWithNoRounding(value); upperVal = parseToMilliseconds(value, context, includeUpper); } Filter filter = NumericRangeFieldDataFilter.newLongRange( (IndexNumericFieldData<?>) fieldData.getForField(this), lowerVal,upperVal, includeLower, includeUpper ); if (!cache) { // We don't cache range filter if `now` date expression is used and also when a compound filter wraps // a range filter with a `now` date expressions. return NoCacheFilter.wrap(filter); } else { return filter; } } private boolean hasNowExpressionWithNoRounding(String value) { int index = value.indexOf("now"); if (index != -1) { if (value.length() == 3) { return true; } else { int indexOfPotentialRounding = index + 3; if (indexOfPotentialRounding >= value.length()) { return true; } else { char potentialRoundingChar; do { potentialRoundingChar = value.charAt(indexOfPotentialRounding++); if (potentialRoundingChar == '/') { return false; // We found the rounding char, so we shouldn't forcefully disable caching } else if (potentialRoundingChar == ' ') { return true; // Next token in the date math expression and no rounding found, so we should not cache. } } while (indexOfPotentialRounding < value.length()); return true; // Couldn't find rounding char, so we should not cache } } } else { return false; } } @Override public Filter nullValueFilter() { if (nullValue == null) { return null; } long value = parseStringValue(nullValue); return NumericRangeFilter.newLongRange(names.indexName(), precisionStep, value, value, true, true); } @Override protected boolean customBoost() { return true; } @Override protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException { String dateAsString = null; Long value = null; float boost = this.boost; if (context.externalValueSet()) { Object externalValue = context.externalValue(); if (externalValue instanceof Number) { value = ((Number) externalValue).longValue(); } else { dateAsString = (String) externalValue; if (dateAsString == null) { dateAsString = nullValue; } } } else { XContentParser parser = context.parser(); XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.VALUE_NULL) { dateAsString = nullValue; } else if (token == XContentParser.Token.VALUE_NUMBER) { value = parser.longValue(coerce.value()); } else if (token == XContentParser.Token.START_OBJECT) { String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else { if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) { if (token == XContentParser.Token.VALUE_NULL) { dateAsString = nullValue; } else if (token == XContentParser.Token.VALUE_NUMBER) { value = parser.longValue(coerce.value()); } else { dateAsString = parser.text(); } } else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) { boost = parser.floatValue(); } else { throw new ElasticsearchIllegalArgumentException("unknown property [" + currentFieldName + "]"); } } } } else { dateAsString = parser.text(); } } if (dateAsString != null) { assert value == null; if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(names.fullName(), dateAsString, boost); } value = parseStringValue(dateAsString); } if (value != null) { if (fieldType.indexed() || fieldType.stored()) { CustomLongNumericField field = new CustomLongNumericField(this, value, fieldType); field.setBoost(boost); fields.add(field); } if (hasDocValues()) { addDocValue(context, value); } } } @Override protected String contentType() { return CONTENT_TYPE; } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { super.merge(mergeWith, mergeContext); if (!this.getClass().equals(mergeWith.getClass())) { return; } if (!mergeContext.mergeFlags().simulate()) { this.nullValue = ((DateFieldMapper) mergeWith).nullValue; this.dateTimeFormatter = ((DateFieldMapper) mergeWith).dateTimeFormatter; } } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || precisionStep != Defaults.PRECISION_STEP) { builder.field("precision_step", precisionStep); } builder.field("format", dateTimeFormatter.format()); if (includeDefaults || nullValue != null) { builder.field("null_value", nullValue); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } else if (includeDefaults) { builder.field("include_in_all", false); } if (includeDefaults || timeUnit != Defaults.TIME_UNIT) { builder.field("numeric_resolution", timeUnit.name().toLowerCase(Locale.ROOT)); } // only serialize locale if needed, ROOT is the default, so no need to serialize that case as well... if (dateTimeFormatter.locale() != null && dateTimeFormatter.locale() != Locale.ROOT) { builder.field("locale", dateTimeFormatter.locale()); } else if (includeDefaults) { if (dateTimeFormatter.locale() == null) { builder.field("locale", Locale.ROOT); } else { builder.field("locale", dateTimeFormatter.locale()); } } } private long parseStringValue(String value) { try { return dateTimeFormatter.parser().parseMillis(value); } catch (RuntimeException e) { try { long time = Long.parseLong(value); return timeUnit.toMillis(time); } catch (NumberFormatException e1) { throw new MapperParsingException("failed to parse date field [" + value + "], tried both date format [" + dateTimeFormatter.format() + "], and timestamp number with locale [" + dateTimeFormatter.locale() + "]", e); } } } }
1no label
src_main_java_org_elasticsearch_index_mapper_core_DateFieldMapper.java
1,370
public final class ShutdownOperation extends AbstractNamedOperation { public ShutdownOperation() { } public ShutdownOperation(String name) { super(name); } @Override public void run() throws Exception { DistributedExecutorService service = getService(); service.shutdownExecutor(getName()); } @Override public boolean returnsResponse() { return true; } @Override public Object getResponse() { return Boolean.TRUE; } }
0true
hazelcast_src_main_java_com_hazelcast_executor_ShutdownOperation.java
410
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { changed.value = true; } });
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java
1,250
new OProfilerHookValue() { public Object getValue() { return maxMemory; } });
0true
core_src_main_java_com_orientechnologies_orient_core_storage_fs_OMMapManagerOld.java
1,399
public class RDFInputFormat extends FileInputFormat<NullWritable, FaunusElement> implements MapReduceFormat { @Override public RecordReader<NullWritable, FaunusElement> createRecordReader(final InputSplit split, final TaskAttemptContext context) throws IOException { return new RDFRecordReader(ModifiableHadoopConfiguration.of(DEFAULT_COMPAT.getContextConfiguration(context))); } @Override protected boolean isSplitable(final JobContext context, final Path file) { return null == new CompressionCodecFactory(context.getConfiguration()).getCodec(file); } @Override public void addMapReduceJobs(final HadoopCompiler compiler) { compiler.addMapReduce(EdgeListInputMapReduce.Map.class, EdgeListInputMapReduce.Combiner.class, EdgeListInputMapReduce.Reduce.class, LongWritable.class, FaunusVertex.class, NullWritable.class, FaunusVertex.class, new EmptyConfiguration()); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_formats_edgelist_rdf_RDFInputFormat.java
5,094
transportService.sendRequest(node, SearchQueryFetchScrollTransportHandler.ACTION, request, new BaseTransportResponseHandler<ScrollQueryFetchSearchResult>() { @Override public ScrollQueryFetchSearchResult newInstance() { return new ScrollQueryFetchSearchResult(); } @Override public void handleResponse(ScrollQueryFetchSearchResult response) { listener.onResult(response.result()); } @Override public void handleException(TransportException exp) { listener.onFailure(exp); } @Override public String executor() { return ThreadPool.Names.SAME; } });
1no label
src_main_java_org_elasticsearch_search_action_SearchServiceTransportAction.java
534
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientTxnTest { static HazelcastInstance hz; static HazelcastInstance server; static HazelcastInstance second; @Before public void init(){ server = Hazelcast.newHazelcastInstance(); final ClientConfig config = new ClientConfig(); config.getNetworkConfig().setRedoOperation(true); hz = HazelcastClient.newHazelcastClient(config); second = Hazelcast.newHazelcastInstance(); } @After public void destroy() { hz.shutdown(); Hazelcast.shutdownAll(); } @Test public void testTxnRollback() throws Exception { final String queueName = "testTxnRollback"; final TransactionContext context = hz.newTransactionContext(); CountDownLatch latch = new CountDownLatch(1); try { context.beginTransaction(); assertNotNull(context.getTxnId()); final TransactionalQueue queue = context.getQueue(queueName); queue.offer("item"); server.shutdown(); context.commitTransaction(); fail("commit should throw exception!!!"); } catch (Exception e){ context.rollbackTransaction(); latch.countDown(); } assertTrue(latch.await(10, TimeUnit.SECONDS)); final IQueue<Object> q = hz.getQueue(queueName); assertNull(q.poll()); assertEquals(0, q.size()); } @Test public void testTxnRollbackOnServerCrash() throws Exception { final String queueName = "testTxnRollbackOnServerCrash"; final TransactionContext context = hz.newTransactionContext(); CountDownLatch latch = new CountDownLatch(1); context.beginTransaction(); final TransactionalQueue queue = context.getQueue(queueName); String key = HazelcastTestSupport.generateKeyOwnedBy(server); queue.offer(key); server.getLifecycleService().terminate(); try{ context.commitTransaction(); fail("commit should throw exception !"); } catch (Exception e){ context.rollbackTransaction(); latch.countDown(); } assertTrue(latch.await(10, TimeUnit.SECONDS)); final IQueue<Object> q = hz.getQueue(queueName); assertNull(q.poll()); assertEquals(0, q.size()); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientTxnTest.java
1,440
public class GetProductsByCategoryIdTag extends AbstractCatalogTag { private static final Log LOG = LogFactory.getLog(GetProductsByCategoryIdTag.class); private static final long serialVersionUID = 1L; private String var; private long categoryId; @Override public void doTag() throws JspException { catalogService = super.getCatalogService(); Category c = catalogService.findCategoryById(categoryId); if(c == null){ getJspContext().setAttribute(var, null); if(LOG.isDebugEnabled()){ LOG.debug("The category returned was null for categoryId: " + categoryId); } } List<Product> productList = catalogService.findActiveProductsByCategory(c); if(CollectionUtils.isEmpty(productList) && LOG.isDebugEnabled()){ LOG.debug("The productList returned was null for categoryId: " + categoryId); } getJspContext().setAttribute(var, productList); } public String getVar() { return var; } public void setVar(String var) { this.var = var; } public long getCategoryId() { return categoryId; } public void setCategoryId(long categoryId) { this.categoryId = categoryId; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_catalog_taglib_GetProductsByCategoryIdTag.java
1,734
@Deprecated public abstract class CompressedIndexInput<T extends CompressorContext> extends IndexInput { private IndexInput in; protected final T context; private int version; private long totalUncompressedLength; private LongArray offsets; private boolean closed; protected byte[] uncompressed; protected int uncompressedLength; private int position = 0; private int valid = 0; private int currentOffsetIdx; private long currentUncompressedChunkPointer; public CompressedIndexInput(IndexInput in, T context) throws IOException { super("compressed(" + in.toString() + ")"); this.in = in; this.context = context; readHeader(in); this.version = in.readInt(); long metaDataPosition = in.readLong(); long headerLength = in.getFilePointer(); in.seek(metaDataPosition); this.totalUncompressedLength = in.readVLong(); int size = in.readVInt(); offsets = BigArrays.newLongArray(size); for (int i = 0; i < size; i++) { offsets.set(i, in.readVLong()); } this.currentOffsetIdx = -1; this.currentUncompressedChunkPointer = 0; in.seek(headerLength); } /** * Method is overridden to report number of bytes that can now be read * from decoded data buffer, without reading bytes from the underlying * stream. * Never throws an exception; returns number of bytes available without * further reads from underlying source; -1 if stream has been closed, or * 0 if an actual read (and possible blocking) is needed to find out. */ public int available() throws IOException { // if closed, return -1; if (closed) { return -1; } int left = (valid - position); return (left <= 0) ? 0 : left; } @Override public byte readByte() throws IOException { if (!readyBuffer()) { throw new EOFException(); } return uncompressed[position++]; } public int read(byte[] buffer, int offset, int length, boolean fullRead) throws IOException { if (length < 1) { return 0; } if (!readyBuffer()) { return -1; } // First let's read however much data we happen to have... int chunkLength = Math.min(valid - position, length); System.arraycopy(uncompressed, position, buffer, offset, chunkLength); position += chunkLength; if (chunkLength == length || !fullRead) { return chunkLength; } // Need more data, then int totalRead = chunkLength; do { offset += chunkLength; if (!readyBuffer()) { break; } chunkLength = Math.min(valid - position, (length - totalRead)); System.arraycopy(uncompressed, position, buffer, offset, chunkLength); position += chunkLength; totalRead += chunkLength; } while (totalRead < length); return totalRead; } @Override public void readBytes(byte[] b, int offset, int len) throws IOException { int result = read(b, offset, len, true /* we want to have full reads, thats the contract... */); if (result < len) { throw new EOFException(); } } @Override public long getFilePointer() { return currentUncompressedChunkPointer + position; } @Override public void seek(long pos) throws IOException { int idx = (int) (pos / uncompressedLength); if (idx >= offsets.size()) { // set the next "readyBuffer" to EOF currentOffsetIdx = idx; position = 0; valid = 0; return; } // TODO: optimize so we won't have to readyBuffer on seek, can keep the position around, and set it on readyBuffer in this case if (idx != currentOffsetIdx) { long pointer = offsets.get(idx); in.seek(pointer); position = 0; valid = 0; currentOffsetIdx = idx - 1; // we are going to increase it in readyBuffer... readyBuffer(); } position = (int) (pos % uncompressedLength); } @Override public long length() { return totalUncompressedLength; } @Override public void close() throws IOException { position = valid = 0; if (!closed) { closed = true; doClose(); in.close(); } } protected abstract void doClose() throws IOException; protected boolean readyBuffer() throws IOException { if (position < valid) { return true; } if (closed) { return false; } // we reached the end... if (currentOffsetIdx + 1 >= offsets.size()) { return false; } valid = uncompress(in, uncompressed); if (valid < 0) { return false; } currentOffsetIdx++; currentUncompressedChunkPointer = ((long) currentOffsetIdx) * uncompressedLength; position = 0; return (position < valid); } protected abstract void readHeader(IndexInput in) throws IOException; /** * Uncompress the data into the out array, returning the size uncompressed */ protected abstract int uncompress(IndexInput in, byte[] out) throws IOException; @Override public IndexInput clone() { // we clone and we need to make sure we keep the same positions! CompressedIndexInput cloned = (CompressedIndexInput) super.clone(); cloned.uncompressed = new byte[uncompressedLength]; System.arraycopy(uncompressed, 0, cloned.uncompressed, 0, uncompressedLength); cloned.in = (IndexInput) cloned.in.clone(); return cloned; } }
0true
src_main_java_org_elasticsearch_common_compress_CompressedIndexInput.java
120
public class ExtractValueProposal implements ICompletionProposal { private CeylonEditor editor; public ExtractValueProposal(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 value"; } @Override public IContextInformation getContextInformation() { return null; } @Override public String getAdditionalProposalInfo() { return null; } @Override public void apply(IDocument doc) { if (useLinkedMode()) { new ExtractValueLinkedMode(editor).start(); } else { new ExtractValueRefactoringAction(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; } } ExtractValueRefactoring evr = new ExtractValueRefactoring(editor); if (evr.isEnabled()) { proposals.add(new ExtractValueProposal(editor)); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ExtractValueProposal.java
174
public interface EntryList extends List<Entry> { /** * Returns the same iterator as {@link #iterator()} with the only difference * that it reuses {@link Entry} objects when calling {@link java.util.Iterator#next()}. * Hence, this method should only be used if references to {@link Entry} objects are only * kept and accesed until the next {@link java.util.Iterator#next()} call. * * @return */ public Iterator<Entry> reuseIterator(); /** * Returns the total amount of bytes this entry consumes on the heap - including all object headers. * * @return */ public int getByteSize(); public static final EmptyList EMPTY_LIST = new EmptyList(); static class EmptyList extends AbstractList<Entry> implements EntryList { @Override public Entry get(int index) { throw new ArrayIndexOutOfBoundsException(); } @Override public int size() { return 0; } @Override public Iterator<Entry> reuseIterator() { return iterator(); } @Override public int getByteSize() { return 0; } } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_EntryList.java
846
CUSTOM("Custom", 20, new Class<?>[] { OSerializableStream.class }, new Class<?>[] { OSerializableStream.class }) { },
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OType.java
85
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_STATIC_ASSET_STRG") public class StaticAssetStorageImpl implements StaticAssetStorage { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "StaticAssetStorageId") @GenericGenerator( name="StaticAssetStorageId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="StaticAssetStorageImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.cms.file.domain.StaticAssetStorageImpl") } ) @Column(name = "STATIC_ASSET_STRG_ID") protected Long id; @Column(name ="STATIC_ASSET_ID", nullable = false) @Index(name="STATIC_ASSET_ID_INDEX", columnNames={"STATIC_ASSET_ID"}) protected Long staticAssetId; @Column (name = "FILE_DATA", length = Integer.MAX_VALUE - 1) @Lob protected Blob fileData; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public Blob getFileData() { return fileData; } @Override public void setFileData(Blob fileData) { this.fileData = fileData; } @Override public Long getStaticAssetId() { return staticAssetId; } @Override public void setStaticAssetId(Long staticAssetId) { this.staticAssetId = staticAssetId; } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetStorageImpl.java
1,573
public class AdminExporterDTO implements Serializable { private static final long serialVersionUID = 1L; protected String name; protected String friendlyName; protected List<Property> additionalCriteriaProperties; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFriendlyName() { return friendlyName; } public void setFriendlyName(String friendlyName) { this.friendlyName = friendlyName; } public List<Property> getAdditionalCriteriaProperties() { return additionalCriteriaProperties; } public void setAdditionalCriteriaProperties(List<Property> additionalCriteriaProperties) { this.additionalCriteriaProperties = additionalCriteriaProperties; } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_AdminExporterDTO.java
244
static final Comparator<Pair<Long,BytesRef>> weightComparator = new Comparator<Pair<Long,BytesRef>> () { @Override public int compare(Pair<Long,BytesRef> left, Pair<Long,BytesRef> right) { return left.output1.compareTo(right.output1); } };
0true
src_main_java_org_apache_lucene_search_suggest_analyzing_XAnalyzingSuggester.java
1,972
public final class ProviderInstanceBindingImpl<T> extends BindingImpl<T> implements ProviderInstanceBinding<T> { final Provider<? extends T> providerInstance; final ImmutableSet<InjectionPoint> injectionPoints; public ProviderInstanceBindingImpl(Injector injector, Key<T> key, Object source, InternalFactory<? extends T> internalFactory, Scoping scoping, Provider<? extends T> providerInstance, Set<InjectionPoint> injectionPoints) { super(injector, key, source, internalFactory, scoping); this.providerInstance = providerInstance; this.injectionPoints = ImmutableSet.copyOf(injectionPoints); } public ProviderInstanceBindingImpl(Object source, Key<T> key, Scoping scoping, Set<InjectionPoint> injectionPoints, Provider<? extends T> providerInstance) { super(source, key, scoping); this.injectionPoints = ImmutableSet.copyOf(injectionPoints); this.providerInstance = providerInstance; } public <V> V acceptTargetVisitor(BindingTargetVisitor<? super T, V> visitor) { return visitor.visit(this); } public Provider<? extends T> getProviderInstance() { return providerInstance; } public Set<InjectionPoint> getInjectionPoints() { return injectionPoints; } public Set<Dependency<?>> getDependencies() { return providerInstance instanceof HasDependencies ? ImmutableSet.copyOf(((HasDependencies) providerInstance).getDependencies()) : Dependency.forInjectionPoints(injectionPoints); } public BindingImpl<T> withScoping(Scoping scoping) { return new ProviderInstanceBindingImpl<T>( getSource(), getKey(), scoping, injectionPoints, providerInstance); } public BindingImpl<T> withKey(Key<T> key) { return new ProviderInstanceBindingImpl<T>( getSource(), key, getScoping(), injectionPoints, providerInstance); } public void applyTo(Binder binder) { getScoping().applyTo( binder.withSource(getSource()).bind(getKey()).toProvider(getProviderInstance())); } @Override public String toString() { return new ToStringBuilder(ProviderInstanceBinding.class) .add("key", getKey()) .add("source", getSource()) .add("scope", getScoping()) .add("provider", providerInstance) .toString(); } }
0true
src_main_java_org_elasticsearch_common_inject_internal_ProviderInstanceBindingImpl.java
1,329
@ClusterScope(scope = Scope.TEST, numNodes = 0) public class SpecificMasterNodesTests extends ElasticsearchIntegrationTest { protected final ImmutableSettings.Builder settingsBuilder() { return ImmutableSettings.builder().put("discovery.type", "zen"); } @Test public void simpleOnlyMasterNodeElection() { logger.info("--> start data node / non master node"); cluster().startNode(settingsBuilder().put("node.data", true).put("node.master", false).put("discovery.initial_state_timeout", "1s")); try { assertThat(client().admin().cluster().prepareState().setMasterNodeTimeout("100ms").execute().actionGet().getState().nodes().masterNodeId(), nullValue()); fail("should not be able to find master"); } catch (MasterNotDiscoveredException e) { // all is well, no master elected } logger.info("--> start master node"); final String masterNodeName = cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true)); assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName)); assertThat(cluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName)); logger.info("--> stop master node"); cluster().stopCurrentMasterNode(); try { assertThat(client().admin().cluster().prepareState().setMasterNodeTimeout("100ms").execute().actionGet().getState().nodes().masterNodeId(), nullValue()); fail("should not be able to find master"); } catch (MasterNotDiscoveredException e) { // all is well, no master elected } logger.info("--> start master node"); final String nextMasterEligableNodeName = cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true)); assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(nextMasterEligableNodeName)); assertThat(cluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(nextMasterEligableNodeName)); } @Test public void electOnlyBetweenMasterNodes() { logger.info("--> start data node / non master node"); cluster().startNode(settingsBuilder().put("node.data", true).put("node.master", false).put("discovery.initial_state_timeout", "1s")); try { assertThat(client().admin().cluster().prepareState().setMasterNodeTimeout("100ms").execute().actionGet().getState().nodes().masterNodeId(), nullValue()); fail("should not be able to find master"); } catch (MasterNotDiscoveredException e) { // all is well, no master elected } logger.info("--> start master node (1)"); final String masterNodeName = cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true)); assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName)); assertThat(cluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName)); logger.info("--> start master node (2)"); final String nextMasterEligableNodeName = cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true)); assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName)); assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName)); assertThat(cluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName)); logger.info("--> closing master node (1)"); cluster().stopCurrentMasterNode(); assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(nextMasterEligableNodeName)); assertThat(cluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(nextMasterEligableNodeName)); } /** * Tests that putting custom default mapping and then putting a type mapping will have the default mapping merged * to the type mapping. */ @Test public void testCustomDefaultMapping() throws Exception { logger.info("--> start master node / non data"); cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true)); logger.info("--> start data node / non master node"); cluster().startNode(settingsBuilder().put("node.data", true).put("node.master", false)); assertAcked(client().admin().indices().prepareCreate("test").setSettings("number_of_shards", 1).get()); assertAcked(client().admin().indices().preparePutMapping("test").setType("_default_").setSource("_timestamp", "enabled=true")); MappingMetaData defaultMapping = client().admin().cluster().prepareState().get().getState().getMetaData().getIndices().get("test").getMappings().get("_default_"); assertThat(defaultMapping.getSourceAsMap().get("_timestamp"), notNullValue()); assertAcked(client().admin().indices().preparePutMapping("test").setType("_default_").setSource("_timestamp", "enabled=true")); assertAcked(client().admin().indices().preparePutMapping("test").setType("type1").setSource("foo", "enabled=true")); MappingMetaData type1Mapping = client().admin().cluster().prepareState().get().getState().getMetaData().getIndices().get("test").getMappings().get("type1"); assertThat(type1Mapping.getSourceAsMap().get("_timestamp"), notNullValue()); } @Test public void testAliasFilterValidation() throws Exception { logger.info("--> start master node / non data"); cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true)); logger.info("--> start data node / non master node"); cluster().startNode(settingsBuilder().put("node.data", true).put("node.master", false)); assertAcked(prepareCreate("test").addMapping("type1", "{\"type1\" : {\"properties\" : {\"table_a\" : { \"type\" : \"nested\", \"properties\" : {\"field_a\" : { \"type\" : \"string\" },\"field_b\" :{ \"type\" : \"string\" }}}}}}")); client().admin().indices().prepareAliases().addAlias("test", "a_test", FilterBuilders.nestedFilter("table_a", FilterBuilders.termFilter("table_a.field_b", "y"))).get(); } }
0true
src_test_java_org_elasticsearch_cluster_SpecificMasterNodesTests.java
3,092
static enum Type { CREATE, INDEX, DELETE }
0true
src_main_java_org_elasticsearch_index_engine_Engine.java
469
BackendOperation.execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { manager.mutateMany(subMutations, tx); return true; } @Override public String toString() { return "CacheMutation"; } }, maxWriteTime);
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_cache_CacheTransaction.java
3,022
public class PerFieldMappingPostingFormatCodec extends Lucene46Codec { private final ESLogger logger; private final MapperService mapperService; private final PostingsFormat defaultPostingFormat; private final DocValuesFormat defaultDocValuesFormat; public PerFieldMappingPostingFormatCodec(MapperService mapperService, PostingsFormat defaultPostingFormat, DocValuesFormat defaultDocValuesFormat, ESLogger logger) { this.mapperService = mapperService; this.logger = logger; this.defaultPostingFormat = defaultPostingFormat; this.defaultDocValuesFormat = defaultDocValuesFormat; } @Override public PostingsFormat getPostingsFormatForField(String field) { final FieldMappers indexName = mapperService.indexName(field); if (indexName == null) { logger.warn("no index mapper found for field: [{}] returning default postings format", field); return defaultPostingFormat; } PostingsFormatProvider postingsFormat = indexName.mapper().postingsFormatProvider(); return postingsFormat != null ? postingsFormat.get() : defaultPostingFormat; } @Override public DocValuesFormat getDocValuesFormatForField(String field) { final FieldMappers indexName = mapperService.indexName(field); if (indexName == null) { logger.warn("no index mapper found for field: [{}] returning default doc values format", field); return defaultDocValuesFormat; } DocValuesFormatProvider docValuesFormat = indexName.mapper().docValuesFormatProvider(); return docValuesFormat != null ? docValuesFormat.get() : defaultDocValuesFormat; } }
0true
src_main_java_org_elasticsearch_index_codec_PerFieldMappingPostingFormatCodec.java
863
public class AtomicReferenceReplicationOperation extends AbstractOperation implements IdentifiedDataSerializable { private Map<String, Data> migrationData; public AtomicReferenceReplicationOperation() { } public AtomicReferenceReplicationOperation(Map<String, Data> migrationData) { this.migrationData = migrationData; } @Override public void run() throws Exception { AtomicReferenceService atomicReferenceService = getService(); for (Map.Entry<String, Data> entry : migrationData.entrySet()) { String name = entry.getKey(); ReferenceWrapper reference = atomicReferenceService.getReference(name); Data value = entry.getValue(); reference.set(value); } } @Override public String getServiceName() { return AtomicReferenceService.SERVICE_NAME; } @Override public int getFactoryId() { return AtomicReferenceDataSerializerHook.F_ID; } @Override public int getId() { return AtomicReferenceDataSerializerHook.REPLICATION; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { out.writeInt(migrationData.size()); for (Map.Entry<String, Data> entry : migrationData.entrySet()) { out.writeUTF(entry.getKey()); out.writeObject(entry.getValue()); } } @Override protected void readInternal(ObjectDataInput in) throws IOException { int mapSize = in.readInt(); migrationData = new HashMap<String, Data>(mapSize); for (int i = 0; i < mapSize; i++) { String name = in.readUTF(); Data data = in.readObject(); migrationData.put(name, data); } } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_operations_AtomicReferenceReplicationOperation.java
720
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name="BLC_SKU_ATTRIBUTE") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") public class SkuAttributeImpl implements SkuAttribute { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The id. */ @Id @GeneratedValue(generator= "SkuAttributeId") @GenericGenerator( name="SkuAttributeId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="SkuAttributeImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.catalog.domain.SkuAttributeImpl") } ) @Column(name = "SKU_ATTR_ID") protected Long id; /** The name. */ @Column(name = "NAME", nullable=false) @Index(name="SKUATTR_NAME_INDEX", columnNames={"NAME"}) @AdminPresentation(visibility = VisibilityEnum.HIDDEN_ALL) protected String name; /** The value. */ @Column(name = "VALUE", nullable=false) @AdminPresentation(friendlyName = "SkuAttributeImpl_Attribute_Value", order=2, group = "SkuAttributeImpl_Description", prominent=true) protected String value; /** The searchable. */ @Column(name = "SEARCHABLE") @AdminPresentation(excluded = true) protected Boolean searchable = false; /** The sku. */ @ManyToOne(targetEntity = SkuImpl.class, optional=false) @JoinColumn(name = "SKU_ID") @Index(name="SKUATTR_SKU_INDEX", columnNames={"SKU_ID"}) protected Sku sku; /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.SkuAttribute#getId() */ @Override public Long getId() { return id; } /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.SkuAttribute#setId(java.lang.Long) */ @Override public void setId(Long id) { this.id = id; } /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.SkuAttribute#getValue() */ @Override public String getValue() { return value; } /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.SkuAttribute#setValue(java.lang.String) */ @Override public void setValue(String value) { this.value = value; } /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.SkuAttribute#getSearchable() */ @Override public Boolean getSearchable() { if (searchable == null) { return Boolean.FALSE; } else { return searchable; } } /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.SkuAttribute#setSearchable(java.lang.Boolean) */ @Override public void setSearchable(Boolean searchable) { this.searchable = searchable; } /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.SkuAttribute#getName() */ @Override public String getName() { return name; } /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.SkuAttribute#setName(java.lang.String) */ @Override public void setName(String name) { this.name = name; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return value; } /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.SkuAttribute#getSku() */ @Override public Sku getSku() { return sku; } /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.SkuAttribute#setSku(org.broadleafcommerce.core.catalog.domain.Sku) */ @Override public void setSku(Sku sku) { this.sku = sku; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((sku == null) ? 0 : sku.hashCode()); result = prime * result + ((value == null) ? 0 : value.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; SkuAttributeImpl other = (SkuAttributeImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (sku == null) { if (other.sku != null) return false; } else if (!sku.equals(other.sku)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_SkuAttributeImpl.java
324
public class ModifiableConfiguration extends BasicConfiguration { private final WriteConfiguration config; public ModifiableConfiguration(ConfigNamespace root, WriteConfiguration config, Restriction restriction) { super(root, config, restriction); Preconditions.checkNotNull(config); this.config = config; } public<O> ModifiableConfiguration set(ConfigOption<O> option, O value, String... umbrellaElements) { verifyOption(option); Preconditions.checkArgument(!option.isFixed() || !isFrozen(), "Cannot change configuration option: %s", option); String key = super.getPath(option,umbrellaElements); value = option.verify(value); config.set(key,value); return this; } public void setAll(Map<ConfigElement.PathIdentifier,Object> options) { for (Map.Entry<ConfigElement.PathIdentifier,Object> entry : options.entrySet()) { Preconditions.checkArgument(entry.getKey().element.isOption()); set((ConfigOption) entry.getKey().element, entry.getValue(), entry.getKey().umbrellaElements); } } public<O> void remove(ConfigOption<O> option, String... umbrellaElements) { verifyOption(option); Preconditions.checkArgument(!option.isFixed() || !isFrozen(), "Cannot change configuration option: %s", option); String key = super.getPath(option,umbrellaElements); config.remove(key); } public void freezeConfiguration() { config.set(FROZEN_KEY, Boolean.TRUE); if (!isFrozen()) setFrozen(); } @Override public WriteConfiguration getConfiguration() { return config; } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_ModifiableConfiguration.java
814
public class AddBackupOperation extends AtomicLongBaseOperation implements BackupOperation { private long delta; public AddBackupOperation() { } public AddBackupOperation(String name, long delta) { super(name); this.delta = delta; } @Override public void run() throws Exception { LongWrapper number = getNumber(); number.addAndGet(delta); } @Override public int getId() { return AtomicLongDataSerializerHook.ADD_BACKUP; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeLong(delta); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); delta = in.readLong(); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_operations_AddBackupOperation.java
856
public class SetRequest extends ModifyRequest { public SetRequest() { } public SetRequest(String name, Data update) { super(name, update); } @Override protected Operation prepareOperation() { return new SetOperation(name, update); } @Override public int getClassId() { return AtomicReferencePortableHook.SET; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_SetRequest.java
1,604
public class SystemObjectLog extends SystemLog { final Object obj; public SystemObjectLog(Object obj) { this.obj = obj; } @Override public String toString() { if (obj == null) { return "NULL"; } else { return obj.toString(); } } }
0true
hazelcast_src_main_java_com_hazelcast_logging_SystemObjectLog.java
131
public interface SchemaInspector { /* --------------------------------------------------------------- * Schema * --------------------------------------------------------------- */ /** * Checks whether a type with the specified name exists. * * @param name name of the type * @return true, if a type with the given name exists, else false */ public boolean containsRelationType(String name); /** * Returns the type with the given name. * Note, that type names must be unique. * * @param name name of the type to return * @return The type with the given name, or null if such does not exist * @see RelationType */ public RelationType getRelationType(String name); /** * Checks whether a property key of the given name has been defined in the Titan schema. * * @param name name of the property key * @return true, if the property key exists, else false */ public boolean containsPropertyKey(String name); /** * Returns the property key with the given name. If automatic type making is enabled, it will make the property key * using the configured default type maker if a key with the given name does not exist. * * @param name name of the property key to return * @return the property key with the given name * @throws IllegalArgumentException if a property key with the given name does not exist or if the * type with the given name is not a property key * @see PropertyKey */ public PropertyKey getOrCreatePropertyKey(String name); /** * Returns the property key with the given name. If it does not exist, NULL is returned * * @param name * @return */ public PropertyKey getPropertyKey(String name); /** * Checks whether an edge label of the given name has been defined in the Titan schema. * * @param name name of the edge label * @return true, if the edge label exists, else false */ public boolean containsEdgeLabel(String name); /** * Returns the edge label with the given name. If automatic type making is enabled, it will make the edge label * using the configured default type maker if a label with the given name does not exist. * * @param name name of the edge label to return * @return the edge label with the given name * @throws IllegalArgumentException if an edge label with the given name does not exist or if the * type with the given name is not an edge label * @see EdgeLabel */ public EdgeLabel getOrCreateEdgeLabel(String name); /** * Returns the edge label with the given name. If it does not exist, NULL is returned * @param name * @return */ public EdgeLabel getEdgeLabel(String name); /** * Whether a vertex label with the given name exists in the graph. * * @param name * @return */ public boolean containsVertexLabel(String name); /** * Returns the vertex label with the given name. If a vertex label with this name does not exist, the label is * automatically created through the registered {@link com.thinkaurelius.titan.core.schema.DefaultSchemaMaker}. * <p /> * Attempting to automatically create a vertex label might cause an exception depending on the configuration. * * @param name * @return */ public VertexLabel getVertexLabel(String name); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_schema_SchemaInspector.java
1,640
public class OHazelcastDistributedRequest implements ODistributedRequest, Externalizable { private static AtomicLong serialId = new AtomicLong(); private long id; private EXECUTION_MODE executionMode; private String senderNodeName; private String databaseName; private String clusterName; private long senderThreadId; private OAbstractRemoteTask task; /** * Constructor used by serializer. */ public OHazelcastDistributedRequest() { } public OHazelcastDistributedRequest(final String senderNodeName, final String databaseName, final String clusterName, final OAbstractRemoteTask payload, EXECUTION_MODE iExecutionMode) { this.senderNodeName = senderNodeName; this.databaseName = databaseName; this.clusterName = clusterName; this.senderThreadId = Thread.currentThread().getId(); this.task = payload; this.executionMode = iExecutionMode; id = serialId.incrementAndGet(); } @Override public void undo() { task.undo(); } public long getId() { return id; } @Override public String getDatabaseName() { return databaseName; } @Override public String getClusterName() { return clusterName; } @Override public OAbstractRemoteTask getTask() { return task; } @Override public OHazelcastDistributedRequest setDatabaseName(final String databaseName) { this.databaseName = databaseName; return this; } @Override public OHazelcastDistributedRequest setClusterName(final String clusterName) { this.clusterName = clusterName; return this; } @Override public OHazelcastDistributedRequest setTask(final OAbstractRemoteTask payload) { this.task = payload; return this; } public String getSenderNodeName() { return senderNodeName; } public OHazelcastDistributedRequest setSenderNodeName(final String senderNodeName) { this.senderNodeName = senderNodeName; return this; } @Override public EXECUTION_MODE getExecutionMode() { return executionMode; } public OHazelcastDistributedRequest setExecutionMode(final EXECUTION_MODE executionMode) { this.executionMode = executionMode; return this; } @Override public void writeExternal(final ObjectOutput out) throws IOException { out.writeLong(id); out.writeUTF(senderNodeName); out.writeLong(senderThreadId); out.writeUTF(databaseName); out.writeUTF(clusterName != null ? clusterName : ""); out.writeObject(task); } @Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { id = in.readLong(); senderNodeName = in.readUTF(); senderThreadId = in.readLong(); databaseName = in.readUTF(); clusterName = in.readUTF(); if (clusterName.length() == 0) clusterName = null; task = (OAbstractRemoteTask) in.readObject(); } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append("id="); buffer.append(id); if (task != null) { buffer.append(" task="); buffer.append(task.toString()); } return buffer.toString(); } }
1no label
distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_OHazelcastDistributedRequest.java
604
public enum MemberAttributeOperationType { PUT(1), REMOVE(2); private final int id; MemberAttributeOperationType(int i) { this.id = i; } public int getId() { return id; } public static MemberAttributeOperationType getValue(int id) { for (MemberAttributeOperationType operationType : values()) { if (operationType.id == id) { return operationType; } } throw new IllegalArgumentException("No OperationType for id: " + id); } }
0true
hazelcast_src_main_java_com_hazelcast_cluster_MemberAttributeOperationType.java
247
public interface BroadleafCurrencyService { /** * Returns the default Broadleaf currency * @return The default currency */ public BroadleafCurrency findDefaultBroadleafCurrency(); /** * Returns a Broadleaf currency found by a code * @return The currency */ public BroadleafCurrency findCurrencyByCode(String currencyCode); /** * Returns a list of all the Broadleaf Currencies * @return List of currencies */ public List<BroadleafCurrency> getAllCurrencies(); public BroadleafCurrency save(BroadleafCurrency currency); }
0true
common_src_main_java_org_broadleafcommerce_common_currency_service_BroadleafCurrencyService.java
219
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientCountDownLatchTest { static final String name = "test"; static HazelcastInstance hz; static ICountDownLatch l; @Before public void init() { Hazelcast.newHazelcastInstance(); hz = HazelcastClient.newHazelcastClient(); l = hz.getCountDownLatch(name); } @After public void stop(){ hz.shutdown(); Hazelcast.shutdownAll(); } @Test public void testLatch() throws Exception { assertTrue(l.trySetCount(20)); assertFalse(l.trySetCount(10)); assertEquals(20, l.getCount()); new Thread(){ public void run() { for (int i=0; i<20; i++){ l.countDown(); try { Thread.sleep(60); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); assertFalse(l.await(1, TimeUnit.SECONDS)); assertTrue(l.await(5, TimeUnit.SECONDS)); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_countdownlatch_ClientCountDownLatchTest.java
381
public class ClusterRerouteRequestBuilder extends AcknowledgedRequestBuilder<ClusterRerouteRequest, ClusterRerouteResponse, ClusterRerouteRequestBuilder> { public ClusterRerouteRequestBuilder(ClusterAdminClient clusterClient) { super((InternalClusterAdminClient) clusterClient, new ClusterRerouteRequest()); } /** * Adds allocation commands to be applied to the cluster. Note, can be empty, in which case * will simply run a simple "reroute". */ public ClusterRerouteRequestBuilder add(AllocationCommand... commands) { request.add(commands); return this; } /** * Sets a dry run flag (defaults to <tt>false</tt>) allowing to run the commands without * actually applying them to the cluster state, and getting the resulting cluster state back. */ public ClusterRerouteRequestBuilder setDryRun(boolean dryRun) { request.dryRun(dryRun); return this; } /** * Sets the source for the request */ public ClusterRerouteRequestBuilder setSource(BytesReference source) throws Exception { request.source(source); return this; } @Override protected void doExecute(ActionListener<ClusterRerouteResponse> listener) { ((ClusterAdminClient) client).reroute(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_reroute_ClusterRerouteRequestBuilder.java
1,916
class AssistedConstructor<T> { private final Constructor<T> constructor; private final ParameterListKey assistedParameters; private final List<Parameter> allParameters; @SuppressWarnings("unchecked") public AssistedConstructor(Constructor<T> constructor, List<TypeLiteral<?>> parameterTypes) { this.constructor = constructor; Annotation[][] annotations = constructor.getParameterAnnotations(); List<Type> typeList = Lists.newArrayList(); allParameters = new ArrayList<Parameter>(); // categorize params as @Assisted or @Injected for (int i = 0; i < parameterTypes.size(); i++) { Parameter parameter = new Parameter(parameterTypes.get(i).getType(), annotations[i]); allParameters.add(parameter); if (parameter.isProvidedByFactory()) { typeList.add(parameter.getType()); } } this.assistedParameters = new ParameterListKey(typeList); } /** * Returns the {@link ParameterListKey} for this constructor. The * {@link ParameterListKey} is created from the ordered list of {@link Assisted} * constructor parameters. */ public ParameterListKey getAssistedParameters() { return assistedParameters; } /** * Returns an ordered list of all constructor parameters (both * {@link Assisted} and {@link Inject}ed). */ public List<Parameter> getAllParameters() { return allParameters; } public Set<Class<?>> getDeclaredExceptions() { return new HashSet<Class<?>>(Arrays.asList(constructor.getExceptionTypes())); } /** * Returns an instance of T, constructed using this constructor, with the * supplied arguments. */ public T newInstance(Object[] args) throws Throwable { constructor.setAccessible(true); try { return constructor.newInstance(args); } catch (InvocationTargetException e) { throw e.getCause(); } } @Override public String toString() { return constructor.toString(); } }
0true
src_main_java_org_elasticsearch_common_inject_assistedinject_AssistedConstructor.java
660
@Repository("blProductDao") public class ProductDaoImpl implements ProductDao { @PersistenceContext(unitName="blPU") protected EntityManager em; @Resource(name="blEntityConfiguration") protected EntityConfiguration entityConfiguration; protected Long currentDateResolution = 10000L; protected Date cachedDate = SystemTime.asDate(); @Override public Product save(Product product) { return em.merge(product); } @Override public Product readProductById(Long productId) { return em.find(ProductImpl.class, productId); } @Override public List<Product> readProductsByIds(List<Long> productIds) { if (productIds == null || productIds.size() == 0) { return null; } // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = builder.createQuery(Product.class); Root<ProductImpl> product = criteria.from(ProductImpl.class); criteria.select(product); // We only want results that match the product IDs criteria.where(product.get("id").as(Long.class).in(productIds)); TypedQuery<Product> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); } @Override public List<Product> readProductsByName(String searchName) { TypedQuery<Product> query = em.createNamedQuery("BC_READ_PRODUCTS_BY_NAME", Product.class); query.setParameter("name", searchName + '%'); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); } @Override public List<Product> readProductsByName(@Nonnull String searchName, @Nonnull int limit, @Nonnull int offset) { TypedQuery<Product> query = em.createNamedQuery("BC_READ_PRODUCTS_BY_NAME", Product.class); query.setParameter("name", searchName + '%'); query.setFirstResult(offset); query.setMaxResults(limit); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); } protected Date getCurrentDateAfterFactoringInDateResolution() { Date returnDate = SystemTime.getCurrentDateWithinTimeResolution(cachedDate, currentDateResolution); if (returnDate != cachedDate) { if (SystemTime.shouldCacheDate()) { cachedDate = returnDate; } } return returnDate; } @Override public List<Product> readActiveProductsByCategory(Long categoryId) { Date currentDate = getCurrentDateAfterFactoringInDateResolution(); return readActiveProductsByCategoryInternal(categoryId, currentDate); } @Override @Deprecated public List<Product> readActiveProductsByCategory(Long categoryId, Date currentDate) { return readActiveProductsByCategoryInternal(categoryId, currentDate); } protected List<Product> readActiveProductsByCategoryInternal(Long categoryId, Date currentDate) { TypedQuery<Product> query = em.createNamedQuery("BC_READ_ACTIVE_PRODUCTS_BY_CATEGORY", Product.class); query.setParameter("categoryId", categoryId); query.setParameter("currentDate", currentDate); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); } @Override public List<Product> readFilteredActiveProductsByQuery(String query, ProductSearchCriteria searchCriteria) { Date currentDate = getCurrentDateAfterFactoringInDateResolution(); return readFilteredActiveProductsByQueryInternal(query, currentDate, searchCriteria); } @Override @Deprecated public List<Product> readFilteredActiveProductsByQuery(String query, Date currentDate, ProductSearchCriteria searchCriteria) { return readFilteredActiveProductsByQueryInternal(query, currentDate, searchCriteria); } protected List<Product> readFilteredActiveProductsByQueryInternal(String query, Date currentDate, ProductSearchCriteria searchCriteria) { // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = builder.createQuery(Product.class); // The root of our search is Product since we are searching Root<ProductImpl> product = criteria.from(ProductImpl.class); // We also want to filter on attributes from sku and productAttributes Join<Product, Sku> sku = product.join("defaultSku"); // Product objects are what we want back criteria.select(product); // We only want results that match the search query List<Predicate> restrictions = new ArrayList<Predicate>(); String lq = query.toLowerCase(); restrictions.add( builder.or( builder.like(builder.lower(sku.get("name").as(String.class)), '%' + lq + '%'), builder.like(builder.lower(sku.get("longDescription").as(String.class)), '%' + lq + '%') ) ); attachProductSearchCriteria(searchCriteria, product, sku, restrictions); attachActiveRestriction(currentDate, product, sku, restrictions); attachOrderBy(searchCriteria, product, sku, criteria); // Execute the query with the restrictions criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<Product> typedQuery = em.createQuery(criteria); //don't cache - not really practical for open ended search return typedQuery.getResultList(); } @Override public List<Product> readFilteredActiveProductsByCategory(Long categoryId, ProductSearchCriteria searchCriteria) { Date currentDate = getCurrentDateAfterFactoringInDateResolution(); return readFilteredActiveProductsByCategoryInternal(categoryId, currentDate, searchCriteria); } @Override @Deprecated public List<Product> readFilteredActiveProductsByCategory(Long categoryId, Date currentDate, ProductSearchCriteria searchCriteria) { return readFilteredActiveProductsByCategoryInternal(categoryId, currentDate, searchCriteria); } protected List<Product> readFilteredActiveProductsByCategoryInternal(Long categoryId, Date currentDate, ProductSearchCriteria searchCriteria) { // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = builder.createQuery(Product.class); Root<ProductImpl> product = criteria.from(ProductImpl.class); // We want to filter on attributes from product and sku Join<Product, Sku> sku = product.join("defaultSku"); ListJoin<Product, CategoryProductXref> categoryXref = product.joinList("allParentCategoryXrefs"); // Product objects are what we want back criteria.select(product); // We only want results from the selected category List<Predicate> restrictions = new ArrayList<Predicate>(); restrictions.add(builder.equal(categoryXref.get("categoryProductXref").get("category").get("id"), categoryId)); attachProductSearchCriteria(searchCriteria, product, sku, restrictions); attachActiveRestriction(currentDate, product, sku, restrictions); attachOrderBy(searchCriteria, product, sku, criteria); // Execute the query with the restrictions criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<Product> typedQuery = em.createQuery(criteria); //don't cache - not really practical for open ended search return typedQuery.getResultList(); } protected void attachActiveRestriction(Date currentDate, Path<? extends Product> product, Path<? extends Sku> sku, List<Predicate> restrictions) { CriteriaBuilder builder = em.getCriteriaBuilder(); // Add the product archived status flag restriction restrictions.add(builder.or( builder.isNull(product.get("archiveStatus").get("archived")), builder.equal(product.get("archiveStatus").get("archived"), 'N'))); // Add the active start/end date restrictions restrictions.add(builder.lessThan(sku.get("activeStartDate").as(Date.class), currentDate)); restrictions.add(builder.or( builder.isNull(sku.get("activeEndDate")), builder.greaterThan(sku.get("activeEndDate").as(Date.class), currentDate))); } protected void attachOrderBy(ProductSearchCriteria searchCriteria, From<?, ? extends Product> product, Path<? extends Sku> sku, CriteriaQuery<?> criteria) { if (StringUtils.isNotBlank(searchCriteria.getSortQuery())) { CriteriaBuilder builder = em.getCriteriaBuilder(); List<Order> sorts = new ArrayList<Order>(); String sortQueries = searchCriteria.getSortQuery(); for (String sortQuery : sortQueries.split(",")) { String[] sort = sortQuery.split(" "); if (sort.length == 2) { String key = sort[0]; boolean asc = sort[1].toLowerCase().contains("asc"); // Determine whether we should use the product path or the sku path Path<?> pathToUse; if (key.contains("defaultSku.")) { pathToUse = sku; key = key.substring("defaultSku.".length()); } else if (key.contains("product.")) { pathToUse = product; key = key.substring("product.".length()); } else { // We don't know which path this facet is built on - resolves previous bug that attempted // to attach search facet to any query parameter continue; } if (asc) { sorts.add(builder.asc(pathToUse.get(key))); } else { sorts.add(builder.desc(pathToUse.get(key))); } } } criteria.orderBy(sorts.toArray(new Order[sorts.size()])); } } protected void attachProductSearchCriteria(ProductSearchCriteria searchCriteria, From<?, ? extends Product> product, From<?, ? extends Sku> sku, List<Predicate> restrictions) { CriteriaBuilder builder = em.getCriteriaBuilder(); // Build out the filter criteria from the users request for (Entry<String, String[]> entry : searchCriteria.getFilterCriteria().entrySet()) { String key = entry.getKey(); List<String> eqValues = new ArrayList<String>(); List<String[]> rangeValues = new ArrayList<String[]>(); // Determine which path is the appropriate one to use Path<?> pathToUse; if (key.contains("defaultSku.")) { pathToUse = sku; key = key.substring("defaultSku.".length()); } else if (key.contains("productAttributes.")) { pathToUse = product.join("productAttributes"); key = key.substring("productAttributes.".length()); restrictions.add(builder.equal(pathToUse.get("name").as(String.class), key)); key = "value"; } else if (key.contains("product.")) { pathToUse = product; key = key.substring("product.".length()); } else { // We don't know which path this facet is built on - resolves previous bug that attempted // to attach search facet to any query parameter continue; } // Values can be equality checks (ie manufacturer=Dave's) or range checks, which take the form // key=range[minRange:maxRange]. Figure out what type of check this is for (String value : entry.getValue()) { if (value.contains("range[")) { String[] rangeValue = new String[] { value.substring(value.indexOf("[") + 1, value.indexOf(":")), value.substring(value.indexOf(":") + 1, value.indexOf("]")) }; rangeValues.add(rangeValue); } else { eqValues.add(value); } } // Add the equality range restriction with the "in" builder. That means that the query string // ?manufacturer=Dave&manufacturer=Bob would match either Dave or Bob if (eqValues.size() > 0) { restrictions.add(pathToUse.get(key).in(eqValues)); } // If we have any range restrictions, we need to build those too. Ranges are also "or"ed together, // such that specifying range[0:5] and range[10:null] for the same field would match items // that were valued between 0 and 5 OR over 10 for that field List<Predicate> rangeRestrictions = new ArrayList<Predicate>(); for (String[] range : rangeValues) { BigDecimal min = new BigDecimal(range[0]); BigDecimal max = null; if (range[1] != null && !range[1].equals("null")) { max = new BigDecimal(range[1]); } Predicate minRange = builder.greaterThan(pathToUse.get(key).as(BigDecimal.class), min); Predicate maxRange = null; if (max != null) { maxRange = builder.lessThan(pathToUse.get(key).as(BigDecimal.class), max); rangeRestrictions.add(builder.and(minRange, maxRange)); } else { rangeRestrictions.add(minRange); } } if (rangeRestrictions.size() > 0) { restrictions.add(builder.or(rangeRestrictions.toArray(new Predicate[rangeRestrictions.size()]))); } } } @Override public List<Product> readActiveProductsByCategory(Long categoryId, int limit, int offset) { Date currentDate = getCurrentDateAfterFactoringInDateResolution(); return readActiveProductsByCategoryInternal(categoryId, currentDate, limit, offset); } @Override @Deprecated public List<Product> readActiveProductsByCategory(Long categoryId, Date currentDate, int limit, int offset) { return readActiveProductsByCategoryInternal(categoryId, currentDate, limit, offset); } public List<Product> readActiveProductsByCategoryInternal(Long categoryId, Date currentDate, int limit, int offset) { TypedQuery<Product> query = em.createNamedQuery("BC_READ_ACTIVE_PRODUCTS_BY_CATEGORY", Product.class); query.setParameter("categoryId", categoryId); query.setParameter("currentDate", currentDate); query.setFirstResult(offset); query.setMaxResults(limit); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); } @Override public List<Product> readProductsByCategory(Long categoryId) { TypedQuery<Product> query = em.createNamedQuery("BC_READ_PRODUCTS_BY_CATEGORY", Product.class); query.setParameter("categoryId", categoryId); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); } @Override public List<Product> readProductsByCategory(Long categoryId, int limit, int offset) { TypedQuery<Product> query = em.createNamedQuery("BC_READ_PRODUCTS_BY_CATEGORY", Product.class); query.setParameter("categoryId", categoryId); query.setFirstResult(offset); query.setMaxResults(limit); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); } @Override public void delete(Product product){ ((Status) product).setArchived('Y'); em.merge(product); } @Override public Product create(ProductType productType) { return (Product) entityConfiguration.createEntityInstance(productType.getType()); } @Override public List<ProductBundle> readAutomaticProductBundles() { Date currentDate = getCurrentDateAfterFactoringInDateResolution(); TypedQuery<ProductBundle> query = em.createNamedQuery("BC_READ_AUTOMATIC_PRODUCT_BUNDLES", ProductBundle.class); query.setParameter("currentDate", currentDate); query.setParameter("autoBundle", Boolean.TRUE); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); } @Override public Long getCurrentDateResolution() { return currentDateResolution; } @Override public void setCurrentDateResolution(Long currentDateResolution) { this.currentDateResolution = currentDateResolution; } @Override public List<Product> findProductByURI(String uri) { String urlKey = uri.substring(uri.lastIndexOf('/')); Query query; query = em.createNamedQuery("BC_READ_PRODUCTS_BY_OUTGOING_URL"); query.setParameter("url", uri); query.setParameter("urlKey", urlKey); query.setParameter("currentDate", getCurrentDateAfterFactoringInDateResolution()); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); @SuppressWarnings("unchecked") List<Product> results = (List<Product>) query.getResultList(); return results; } @Override public List<Product> readAllActiveProducts(int page, int pageSize) { Date currentDate = getCurrentDateAfterFactoringInDateResolution(); return readAllActiveProductsInternal(page, pageSize, currentDate); } @Override @Deprecated public List<Product> readAllActiveProducts(int page, int pageSize, Date currentDate) { return readAllActiveProductsInternal(page, pageSize, currentDate); } protected List<Product> readAllActiveProductsInternal(int page, int pageSize, Date currentDate) { CriteriaQuery<Product> criteria = getCriteriaForActiveProducts(currentDate); int firstResult = page * pageSize; TypedQuery<Product> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.setFirstResult(firstResult).setMaxResults(pageSize).getResultList(); } @Override public List<Product> readAllActiveProducts() { Date currentDate = getCurrentDateAfterFactoringInDateResolution(); return readAllActiveProductsInternal(currentDate); } @Override @Deprecated public List<Product> readAllActiveProducts(Date currentDate) { return readAllActiveProductsInternal(currentDate); } protected List<Product> readAllActiveProductsInternal(Date currentDate) { CriteriaQuery<Product> criteria = getCriteriaForActiveProducts(currentDate); TypedQuery<Product> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); } @Override public Long readCountAllActiveProducts() { Date currentDate = getCurrentDateAfterFactoringInDateResolution(); return readCountAllActiveProductsInternal(currentDate); } @Override @Deprecated public Long readCountAllActiveProducts(Date currentDate) { return readCountAllActiveProductsInternal(currentDate); } protected Long readCountAllActiveProductsInternal(Date currentDate) { // Set up the criteria query that specifies we want to return a Long CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.class); // The root of our search is Product Root<ProductImpl> product = criteria.from(ProductImpl.class); // We need to filter on active date on the sku Join<Product, Sku> sku = product.join("defaultSku"); // We want the count of products criteria.select(builder.count(product)); // Ensure the product is currently active List<Predicate> restrictions = new ArrayList<Predicate>(); attachActiveRestriction(currentDate, product, sku, restrictions); // Add the restrictions to the criteria query criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<Long> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getSingleResult(); } protected CriteriaQuery<Product> getCriteriaForActiveProducts(Date currentDate) { // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = builder.createQuery(Product.class); // The root of our search is Product Root<ProductImpl> product = criteria.from(ProductImpl.class); // We need to filter on active date on the sku Join<Product, Sku> sku = product.join("defaultSku"); product.fetch("defaultSku"); // Product objects are what we want back criteria.select(product); // Ensure the product is currently active List<Predicate> restrictions = new ArrayList<Predicate>(); attachActiveRestriction(currentDate, product, sku, restrictions); // Add the restrictions to the criteria query criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); return criteria; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_dao_ProductDaoImpl.java
5,290
public class IpRangeParser implements Aggregator.Parser { @Override public String type() { return InternalIPv4Range.TYPE.name(); } @Override public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException { ValuesSourceConfig<NumericValuesSource> config = new ValuesSourceConfig<NumericValuesSource>(NumericValuesSource.class); String field = null; List<RangeAggregator.Range> ranges = null; String script = null; String scriptLang = null; Map<String, Object> scriptParams = null; boolean keyed = false; boolean assumeSorted = false; XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_STRING) { if ("field".equals(currentFieldName)) { field = parser.text(); } else if ("script".equals(currentFieldName)) { script = parser.text(); } else if ("lang".equals(currentFieldName)) { scriptLang = parser.text(); } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else if (token == XContentParser.Token.START_ARRAY) { if ("ranges".equals(currentFieldName)) { ranges = new ArrayList<RangeAggregator.Range>(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { double from = Double.NEGATIVE_INFINITY; String fromAsStr = null; double to = Double.POSITIVE_INFINITY; String toAsStr = null; String key = null; String mask = null; String toOrFromOrMaskOrKey = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { toOrFromOrMaskOrKey = parser.currentName(); } else if (token == XContentParser.Token.VALUE_NUMBER) { if ("from".equals(toOrFromOrMaskOrKey)) { from = parser.doubleValue(); } else if ("to".equals(toOrFromOrMaskOrKey)) { to = parser.doubleValue(); } } else if (token == XContentParser.Token.VALUE_STRING) { if ("from".equals(toOrFromOrMaskOrKey)) { fromAsStr = parser.text(); } else if ("to".equals(toOrFromOrMaskOrKey)) { toAsStr = parser.text(); } else if ("key".equals(toOrFromOrMaskOrKey)) { key = parser.text(); } else if ("mask".equals(toOrFromOrMaskOrKey)) { mask = parser.text(); } } } RangeAggregator.Range range = new RangeAggregator.Range(key, from, fromAsStr, to, toAsStr); if (mask != null) { parseMaskRange(mask, range, aggregationName, context); } ranges.add(range); } } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else if (token == XContentParser.Token.START_OBJECT) { if ("params".equals(currentFieldName)) { scriptParams = parser.map(); } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else if (token == XContentParser.Token.VALUE_BOOLEAN) { if ("keyed".equals(currentFieldName)) { keyed = parser.booleanValue(); } else if ("script_values_sorted".equals(currentFieldName)) { assumeSorted = parser.booleanValue(); } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else { throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "]."); } } if (ranges == null) { throw new SearchParseException(context, "Missing [ranges] in ranges aggregator [" + aggregationName + "]"); } if (script != null) { config.script(context.scriptService().search(context.lookup(), scriptLang, script, scriptParams)); } if (!assumeSorted) { // we need values to be sorted and unique for efficiency config.ensureSorted(true); } config.formatter(ValueFormatter.IPv4); config.parser(ValueParser.IPv4); if (field == null) { return new RangeAggregator.Factory(aggregationName, config, InternalIPv4Range.FACTORY, ranges, keyed); } FieldMapper<?> mapper = context.smartNameFieldMapper(field); if (mapper == null) { config.unmapped(true); return new RangeAggregator.Factory(aggregationName, config, InternalIPv4Range.FACTORY, ranges, keyed); } if (!(mapper instanceof IpFieldMapper)) { throw new AggregationExecutionException("ip_range aggregation can only be applied to ip fields which is not the case with field [" + field + "]"); } IndexFieldData<?> indexFieldData = context.fieldData().getForField(mapper); config.fieldContext(new FieldContext(field, indexFieldData)); return new RangeAggregator.Factory(aggregationName, config, InternalIPv4Range.FACTORY, ranges, keyed); } private static void parseMaskRange(String cidr, RangeAggregator.Range range, String aggregationName, SearchContext ctx) { long[] fromTo = IPv4RangeBuilder.cidrMaskToMinMax(cidr); if (fromTo == null) { throw new SearchParseException(ctx, "invalid CIDR mask [" + cidr + "] in aggregation [" + aggregationName + "]"); } range.from = fromTo[0] < 0 ? Double.NEGATIVE_INFINITY : fromTo[0]; range.to = fromTo[1] < 0 ? Double.POSITIVE_INFINITY : fromTo[1]; if (range.key == null) { range.key = cidr; } } }
1no label
src_main_java_org_elasticsearch_search_aggregations_bucket_range_ipv4_IpRangeParser.java
2,881
public class LengthTokenFilterFactory extends AbstractTokenFilterFactory { private final int min; private final int max; private final boolean enablePositionIncrements; private static final String ENABLE_POS_INC_KEY = "enable_position_increments"; @Inject public LengthTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); min = settings.getAsInt("min", 0); max = settings.getAsInt("max", Integer.MAX_VALUE); if (version.onOrAfter(Version.LUCENE_44) && settings.get(ENABLE_POS_INC_KEY) != null) { throw new ElasticsearchIllegalArgumentException(ENABLE_POS_INC_KEY + " is not supported anymore. Please fix your analysis chain or use" + " an older compatibility version (<=4.3) but beware that it might cause highlighting bugs."); } enablePositionIncrements = version.onOrAfter(Version.LUCENE_44) ? true : settings.getAsBoolean(ENABLE_POS_INC_KEY, true); } @Override public TokenStream create(TokenStream tokenStream) { if (version.onOrAfter(Version.LUCENE_44)) { return new LengthFilter(version, tokenStream, min, max); } return new LengthFilter(version, enablePositionIncrements, tokenStream, min, max); } }
0true
src_main_java_org_elasticsearch_index_analysis_LengthTokenFilterFactory.java
1,649
public class AddMetadataRequest { private final Field requestedField; private final Class<?> parentClass; private final Class<?> targetClass; private final DynamicEntityDao dynamicEntityDao; private final String prefix; public AddMetadataRequest(Field requestedField, Class<?> parentClass, Class<?> targetClass, DynamicEntityDao dynamicEntityDao, String prefix) { this.requestedField = requestedField; this.parentClass = parentClass; this.targetClass = targetClass; this.dynamicEntityDao = dynamicEntityDao; this.prefix = prefix; } public Field getRequestedField() { return requestedField; } public Class<?> getParentClass() { return parentClass; } public Class<?> getTargetClass() { return targetClass; } public DynamicEntityDao getDynamicEntityDao() { return dynamicEntityDao; } public String getPrefix() { return prefix; } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_dao_provider_metadata_request_AddMetadataRequest.java
1,292
private class Stats { private AtomicLong gets = new AtomicLong(); private AtomicLong puts = new AtomicLong(); private AtomicLong removes = new AtomicLong(); public void printAndReset() { long getsNow = gets.getAndSet(0); long putsNow = puts.getAndSet(0); long removesNow = removes.getAndSet(0); long total = getsNow + putsNow + removesNow; logger.info("total= " + total + ", gets:" + getsNow + ", puts:" + putsNow + ", removes:" + removesNow); logger.info("Operations per Second : " + total / STATS_SECONDS); } }
0true
hazelcast_src_main_java_com_hazelcast_examples_SimpleMapTest.java
597
interface EntriesResultListener { boolean addResult(ODocument entry); }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndexEngine.java
1,107
public class SerializerConfig { private String className; private Serializer implementation; private Class typeClass; private String typeClassName; public SerializerConfig() { super(); } public String getClassName() { return className; } public SerializerConfig setClass(final Class<? extends Serializer> clazz) { String className = clazz == null?null:clazz.getName(); return setClassName(className); } public SerializerConfig setClassName(final String className) { this.className = className; return this; } public Serializer getImplementation() { return implementation; } /** * Sets the serializer implementation instance. * <br/> * Serializer must be instance of either {@link com.hazelcast.nio.serialization.StreamSerializer} * or {@link com.hazelcast.nio.serialization.ByteArraySerializer}. * * @param implementation serializer instance * @return SerializerConfig */ public SerializerConfig setImplementation(final Serializer implementation) { this.implementation = implementation; return this; } public Class getTypeClass() { return typeClass; } public SerializerConfig setTypeClass(final Class typeClass) { this.typeClass = typeClass; return this; } public String getTypeClassName() { return typeClassName; } public SerializerConfig setTypeClassName(final String typeClassName) { this.typeClassName = typeClassName; return this; } @Override public String toString() { final StringBuilder sb = new StringBuilder("SerializerConfig{"); sb.append("className='").append(className).append('\''); sb.append(", implementation=").append(implementation); sb.append(", typeClass=").append(typeClass); sb.append(", typeClassName='").append(typeClassName).append('\''); sb.append('}'); return sb.toString(); } }
0true
hazelcast_src_main_java_com_hazelcast_config_SerializerConfig.java
242
public interface BroadleafCurrencyDao { /** * Returns the default Broadleaf currency * @return The default currency */ public BroadleafCurrency findDefaultBroadleafCurrency(); /** * Returns a Broadleaf currency found by a code * @return The currency */ public BroadleafCurrency findCurrencyByCode(String currencyCode); /** * Returns a list of all the Broadleaf Currencies * @return List of currencies */ public List<BroadleafCurrency> getAllCurrencies(); public BroadleafCurrency save(BroadleafCurrency currency); }
0true
common_src_main_java_org_broadleafcommerce_common_currency_dao_BroadleafCurrencyDao.java
1,614
public class OFixDeleteRecordTask extends OAbstractRemoteTask { private static final long serialVersionUID = 1L; private ORecordId rid; private ORecordVersion version; public OFixDeleteRecordTask() { } public OFixDeleteRecordTask(final ORecordId iRid, final ORecordVersion iVersion) { rid = iRid; version = iVersion; } @Override public Object execute(final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentTx database) throws Exception { ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "fixing delete record %s/%s v.%s", database.getName(), rid.toString(), version.toString()); final ORecordInternal<?> record = rid.getRecord(); if (record.getVersion() != version.getCounter()) { // DIFFERENT VERSIONS, UPDATE IT BEFORE TO DELETE version.setRollbackMode(); record.setVersion(version.getCounter()); record.setDirty(); record.save(); } record.delete(); ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "+-> fixed delete record %s/%s v.%s", database.getName(), record.getIdentity().toString(), record.getRecordVersion() .toString()); return Boolean.TRUE; } public QUORUM_TYPE getQuorumType() { return QUORUM_TYPE.NONE; } @Override public void writeExternal(final ObjectOutput out) throws IOException { out.writeUTF(rid.toString()); if (version == null) version = OVersionFactory.instance().createUntrackedVersion(); version.getSerializer().writeTo(out, version); } @Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { rid = new ORecordId(in.readUTF()); if (version == null) version = OVersionFactory.instance().createUntrackedVersion(); version.getSerializer().readFrom(in, version); } @Override public String getName() { return "fix_record_update"; } }
0true
server_src_main_java_com_orientechnologies_orient_server_distributed_task_OFixDeleteRecordTask.java