Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
115 |
assertTrueEventually(new AssertTask() {
public void run() throws Exception {
NearCacheStats stats = clientMap.getLocalMapStats().getNearCacheStats();
assertEquals(0, stats.getOwnedEntryCount());
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_ClientNearCacheTest.java
|
810 |
@SuppressWarnings("serial")
public class PlotViewManifestation extends FeedView implements RenderingCallback {
private final static Logger logger = LoggerFactory.getLogger(PlotViewManifestation.class);
private AbbreviatingPlotLabelingAlgorithm plotLabelingAlgorithm = new AbbreviatingPlotLabelingAlgorithm();
private JPanel theView;
private List<String> canvasContextTitleList = new ArrayList<String>();
private List<String> panelContextTitleList = new ArrayList<String>();
private Color plotFrameBackground;
PlotView thePlot;
PlotDataAssigner plotDataAssigner = new PlotDataAssigner(this);
PlotDataFeedUpdateHandler plotDataFedUpdateHandler = new PlotDataFeedUpdateHandler(this);
PlotPersistanceHandler plotPersistanceHandler = new PlotPersistanceHandler(this);
SwingWorker<Map<String, List<Map<String, String>>>, Map<String, List<Map<String, String>>>> currentDataRequest;
SwingWorker<Map<String, List<Map<String, String>>>, Map<String, List<Map<String, String>>>> currentPredictionRequest;
PlotSettingsControlPanel controlPanel;
public static final String VIEW_ROLE_NAME = "Plot";
public PlotViewManifestation(AbstractComponent component, ViewInfo vi) {
super(component,vi);
plotFrameBackground = getColor("plotFrame.background");
if (plotFrameBackground == null) plotFrameBackground = PlotConstants.DEFAULT_PLOT_FRAME_BACKGROUND_COLOR;
plotLabelingAlgorithm.setName("plotLabelingAlgorithm");
setLabelingContext(plotLabelingAlgorithm, getNamingContext());
// Generate the plot (& connect it to feeds, etc)
generatePlot();
assert thePlot != null : "Plot should not be null at this point";
}
@Override
protected void handleNamingContextChange() {
updateMonitoredGUI();
}
private Color getColor(String name) {
return UIManager.getColor(name);
}
@Override
protected JComponent initializeControlManifestation() {
controlPanel = new PlotSettingsControlPanel(this);
return controlPanel;
}
/**
* Create plot with specified settings and persist setting.
*/
public void setupPlot(AxisOrientationSetting timeAxisSetting,
XAxisMaximumLocationSetting xAxisMaximumLocation,
YAxisMaximumLocationSetting yAxisMaximumLocation,
TimeAxisSubsequentBoundsSetting timeAxisSubsequentSetting,
NonTimeAxisSubsequentBoundsSetting nonTimeAxisSubsequentMinSetting,
NonTimeAxisSubsequentBoundsSetting nonTimeAxisSubsequentMaxSetting,
double nonTimeMax, double nonTimeMin, GregorianCalendar minTime,
GregorianCalendar maxTime,
double timePadding,
double nonTimeMaxPadding,
double nonTimeMinPadding,
boolean groupByOrdinalPosition,
boolean timeAxisPinned,
PlotLineDrawingFlags plotLineDraw,
PlotLineConnectionType plotLineConnectionType) {
// Persist plot setting and rely on updatedMoinitoredGUI to update this (and all other) manifestations.
plotPersistanceHandler.persistPlotSettings(timeAxisSetting, xAxisMaximumLocation, yAxisMaximumLocation,
timeAxisSubsequentSetting, nonTimeAxisSubsequentMinSetting,
nonTimeAxisSubsequentMaxSetting, nonTimeMax, nonTimeMin,
minTime, maxTime, timePadding, nonTimeMaxPadding, nonTimeMinPadding, groupByOrdinalPosition, timeAxisPinned,
plotLineDraw, plotLineConnectionType);
}
/**
* Persist plot line settings (color, etc)
*/
public void persistPlotLineSettings() {
if (thePlot != null)
plotPersistanceHandler.persistLineSettings(thePlot.getLineSettings());
}
@Override
public void updateMonitoredGUI() {
setLabelingContext(plotLabelingAlgorithm, getNamingContext());
if (thePlot != null) {
// the ordinal position may have changed so ensure the children are also up to date
respondToSettingsChange();
}
}
@Override
public void updateMonitoredGUI(PropertyChangeEvent evt) {
updateMonitoredGUI();
}
@Override
public void updateMonitoredGUI(AddChildEvent event) {
setLabelingContext(plotLabelingAlgorithm, getNamingContext());
respondToChildChangeEvent();
}
@Override
public void updateMonitoredGUI(RemoveChildEvent event) {
setLabelingContext(plotLabelingAlgorithm, getNamingContext());
respondToChildChangeEvent();
}
private void respondToChildChangeEvent() {
generatePlot();
}
private void respondToSettingsChange() {
generatePlot();
if (controlPanel != null) {
controlPanel.updateControlsToMatchPlot();
}
}
private void generatePlot() {
plotDataAssigner.informFeedProvidersHaveChanged();
createPlotAndAddItToPanel();
plotDataAssigner.assignFeedsToSubPlots();
enforceBackgroundColor(plotFrameBackground);
thePlot.addPopupMenus();
thePlot.setLineSettings(plotPersistanceHandler.loadLineSettingsFromPersistence());
//thePlot.setRegressionPointAssignments(plotPersistanceHandler.loadRegressionSettingsFromPersistence());
}
@Override
public Collection<FeedProvider> getVisibleFeedProviders() {
return plotDataAssigner.getVisibleFeedProviders();
}
private long getPointTime(Map<String,String> data) {
return Long.parseLong(data.get(FeedProvider.NORMALIZED_TIME_KEY));
}
/*
* This method expands the data points before compression. This ensures the plot looks the
* same when retrieving data from the buffer which may be sparse and when getting data
* directly in the stream which is returned in one second intervals. Differences occur when the data has few changes, as the data are
* far apart in time and may not connect. For example, if there is a data point at time 1 and then
* another data point at time 100, if there was a loss of service between the points there would be no
* connection (it is not possible to connect two points with an intervening LOS). This method will
* duplicate the points at one second intervals, which is what happens in the live stream.
*/
private void expandData(Map<String, List<Map<String, String>>> expandedData,
final long startTime, final long endTime) {
for (FeedProvider fp:getVisibleFeedProviders()) {
List<Map<String,String>> points = expandedData.get(fp.getSubscriptionId());
if (points != null && !points.isEmpty()) {
List<Map<String,String>> expandedPoints = new ArrayList<Map<String,String>>();
expandedData.put(fp.getSubscriptionId(), expandedPoints);
long now = fp.getTimeService().getCurrentTime();
for (int i = 0; i < points.size(); i++) {
Map<String,String> point = points.get(i);
expandedPoints.add(point);
long pointTime = getPointTime(point);
assert pointTime >= startTime: "point time is less than start time";
pointTime = Math.max(pointTime, startTime);
long nextPointTime = (points.size() > i+1) ? getPointTime(points.get(i+1)) : Math.min(now, endTime) + 1000;
// go through each point get the starting value and then repeat the last
// point at one second intervals
for (long currentTime = pointTime+1000; currentTime <= nextPointTime - 1000; currentTime+=1000) {
Map<String,String> newPoint = new HashMap<String, String>(point);
newPoint.put(FeedProvider.NORMALIZED_TIME_KEY, Long.toString(currentTime));
expandedPoints.add(newPoint);
}
}
}
}
}
private DataTransformation getTransformation() {
return new DataTransformation() {
@Override
public void transform(
Map<String, List<Map<String, String>>> data,
long startTime, long endTime) {
expandData(data, startTime, endTime);
}
};
}
/**
* Request new data for the prediction lines in the plot. The prediction lines are assumed to have data from the start of time (or
* at least the earliest possible useful time in the plot) to the end of time (again based on the plot). The plot assumes
* that predictive feeds not stream data, but instead only retrieve data when the plot needs to request data (when the time changes, either
* due to an axis time change event, jump for example) or when the compression ratio changes, when {@link #requestDataRefresh(GregorianCalendar, GregorianCalendar)} is
* called.
* @param startTime to request predictive data in
* @param endTime to bound predictive data with
*/
public void requestPredictiveData(GregorianCalendar startTime, GregorianCalendar endTime) {
assert currentPredictionRequest == null : "prediction request should not be outstanding";
if (plotDataAssigner.getPredictiveFeedProviders().isEmpty()) {
return;
}
currentPredictionRequest = this.requestData(plotDataAssigner.getPredictiveFeedProviders(), startTime.getTimeInMillis(), endTime.getTimeInMillis(),
getTransformation(),
new RenderingCallback() {
@Override
public void render(Map<String, List<Map<String, String>>> data) {
plotDataFedUpdateHandler.updateFromFeed(data, true);
}
}, false);
currentPredictionRequest.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(java.beans.PropertyChangeEvent evt) {
if (currentPredictionRequest == evt.getSource() && evt.getNewValue() == SwingWorker.StateValue.DONE) {
assert SwingUtilities.isEventDispatchThread();
currentPredictionRequest = null;
}
}
});
}
/**
* Request new data for the plot
* @param startTime of the data requested
* @param endTime of the data requested
*/
public void requestDataRefresh(GregorianCalendar startTime, GregorianCalendar endTime) {
// request data.
if (plotDataAssigner.hasFeeds()) {
cancelAnyOutstandingRequests();
if (logger.isDebugEnabled()) {
logger.debug("\n\n\n ***** Requesting data from central MCT buffer {} -> {} ******\n",
PlotSettingsControlPanel.CalendarDump.dumpDateAndTime(startTime), PlotSettingsControlPanel.CalendarDump.dumpDateAndTime(endTime));
}
currentDataRequest = this.requestData(null, startTime.getTimeInMillis(), endTime.getTimeInMillis(), getTransformation(), this, true);
currentDataRequest.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(java.beans.PropertyChangeEvent evt) {
if (currentDataRequest.getState() == SwingWorker.StateValue.STARTED && evt.getOldValue()==SwingWorker.StateValue.PENDING) {
plotDataFedUpdateHandler.startDataRequest();
}
if (currentDataRequest == evt.getSource() && evt.getNewValue() == SwingWorker.StateValue.DONE) {
assert SwingUtilities.isEventDispatchThread();
currentDataRequest = null;
plotDataFedUpdateHandler.endDataRequest();
}
}
});
}
}
private void cancelOutstandingPredictionRequests() {
logger.debug("PlotViewRole.cancelOutstandingPredictionRequests()");
if (currentPredictionRequest !=null) {
currentPredictionRequest.cancel(false);
currentPredictionRequest = null;
}
}
private void cancelAnyOutstandingRequests() {
logger.debug("PlotViewRole.cancelAnyOutstandingRequests()");
if (currentDataRequest !=null) {
currentDataRequest.cancel(false);
}
cancelOutstandingPredictionRequests();
}
@Override
public void synchronizeTime(
Map<String, List<Map<String, String>>> data, long syncTime) {
plotDataFedUpdateHandler.synchronizeTime(data, syncTime);
}
@Override
protected void synchronizationDone() {
thePlot.removeTimeSyncLine();
}
@Override
public void clear(Collection<FeedProvider> feedProviders) {
updateMonitoredGUI();
}
/**
* Extract data from the feed and push it to the plot. We support three states.
*/
@Override
public void updateFromFeed(Map<String, List<Map<String, String>>> data) {
plotDataFedUpdateHandler.updateFromFeed(data, false);
}
// Requests to MCT data buffer call back here.
@Override
public void render(Map<String, List<Map<String, String>>> data) {
plotDataFedUpdateHandler.processData(data);
}
/**
* Returns the maximum value feed to this plot view role.
* @return
*/
public double getMaxFeedValue() {
return thePlot.getNonTimeMaxCurrentlyDisplayed();
}
/**
* Returns the minimum value feed to this plot view role.
* @return
*/
public double getMinFeedValue() {
return thePlot.getNonTimeMinCurrentlyDisplayed();
}
/**
* Returns the current MCT time
* @return
*/
public long getCurrentMCTTime() {
long cachedTime = System.currentTimeMillis();
AbstractComponent manifestedComponent = getManifestedComponent();
if (manifestedComponent!=null) {
Collection<FeedProvider> feedproviders = getVisibleFeedProviders();
if (!feedproviders.isEmpty()) {
/* We want to get our "current time" from the feeds we're plotting */
Iterator<FeedProvider> feedIterator = feedproviders.iterator();
FeedProvider firstProvider = feedIterator.next();
FeedProvider fp = firstProvider;
/* Find the first non-predictive feed provider;
* predictive feeds may not have useful time values */
while (fp.isPrediction() && feedIterator.hasNext()) {
fp = feedIterator.next();
}
/* If none is available, use the first predictive provider for consistency */
if (fp.isPrediction()) fp = firstProvider;
long currentTimeInMillis = fp.getTimeService().getCurrentTime();
if (currentTimeInMillis >= 0) {
cachedTime = currentTimeInMillis;
} else {
logger.error("FeedProvider currentTimeMillis() returned a time less than zero: {}", currentTimeInMillis);
}
} else {
logger.debug("No feed providers. Returning cached time: {}", cachedTime);
}
}
return cachedTime;
}
private void createPlotAndAddItToPanel() {
createPlot();
assert thePlot!=null: "Plot must be created";
addPlotToPanel();
}
private void createPlot(){
thePlot = PlotViewFactory.createPlot(plotPersistanceHandler.loadPlotSettingsFromPersistance(),
getCurrentMCTTime(),
this, plotDataAssigner.returnNumberOfSubPlots(), null, plotLabelingAlgorithm);
}
private void addPlotToPanel() {
// Remove previous plot if there was one.
if (theView!=null) {
remove(theView);
}
theView = thePlot.getPlotPanel();
add(theView);
refreshPlotPanel();
}
private void enforceBackgroundColor (final Color bg) {
// Enforce a background color
this.setBackground(bg);
thePlot.getPlotPanel().setBackground(bg);
//TODO: Construct a less brute-force solution?
ComponentTraverser.traverse(theView, new ComponentTraverser.ComponentProcedure() {
@Override
public void run(Component c) {
if ((PlotConstants.DEFAULT_PLOT_FRAME_BACKGROUND_COLOR).equals(c.getBackground())) {
c.setBackground(bg);
}
}
});
}
private void refreshPlotPanel() {
thePlot.refreshDisplay();
enforceBackgroundColor(plotFrameBackground);
revalidate();
}
PlotView getPlot() {
return thePlot;
}
/**
* Only for use during testing.
*/
public void setPlot(PlotView plot) {
thePlot = plot;
}
private void clearArrayList() {
canvasContextTitleList.clear();
panelContextTitleList.clear();
}
private void setLabelingContext(AbbreviatingPlotLabelingAlgorithm plotLabelingAlgorithm, NamingContext context) {
clearArrayList();
String surroundingName = "";
if (context != null) {
/* Is some name being shown by the labeling context? */
if (context.getContextualName() != null) {
surroundingName = context.getContextualName(); /* Get that name. */
logger.debug("getPanelTitle surroundingName={}",surroundingName);
if (surroundingName.isEmpty()) {
/* A title bar or similar is displayed, but it's not overriding our *
* base displayed name */
surroundingName = getManifestedComponent().getDisplayName();
}
}
canvasContextTitleList.add(surroundingName);
} else {
/* Labeling context is null, so we are in our own window or inspector */
surroundingName = getManifestedComponent().getDisplayName();
panelContextTitleList.add(surroundingName);
}
plotLabelingAlgorithm.setPanelOrWindowTitle(surroundingName);
plotLabelingAlgorithm.setCanvasContextTitleList(canvasContextTitleList);
plotLabelingAlgorithm.setPanelContextTitleList(panelContextTitleList);
if (logger.isDebugEnabled()) {
printTitleArrayLists("*** DEBUG 2 *** panelContextTitleList", panelContextTitleList);
printTitleArrayLists("*** DEBUG 2 *** canvasContextTitleList", canvasContextTitleList);
}
}
private void printTitleArrayLists(String name, List<String> arrayList) {
for (int i=0; i < arrayList.size(); i++) {
logger.debug(name + ".get(" + i + ")=" + arrayList.get(i));
}
}
}
| 1no label
|
fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_view_PlotViewManifestation.java
|
488 |
public final class ClientClusterServiceImpl implements ClientClusterService {
private static final ILogger LOGGER = Logger.getLogger(ClientClusterService.class);
private static final int SLEEP_TIME = 1000;
private final HazelcastClient client;
private final ClientConnectionManagerImpl connectionManager;
private final ClusterListenerThread clusterThread;
private final AtomicReference<Map<Address, MemberImpl>> membersRef = new AtomicReference<Map<Address, MemberImpl>>();
private final ConcurrentMap<String, MembershipListener> listeners = new ConcurrentHashMap<String, MembershipListener>();
public ClientClusterServiceImpl(HazelcastClient client) {
this.client = client;
this.connectionManager = (ClientConnectionManagerImpl) client.getConnectionManager();
clusterThread = new ClusterListenerThread(client.getThreadGroup(), client.getName() + ".cluster-listener");
final ClientConfig clientConfig = getClientConfig();
final List<ListenerConfig> listenerConfigs = client.getClientConfig().getListenerConfigs();
if (listenerConfigs != null && !listenerConfigs.isEmpty()) {
for (ListenerConfig listenerConfig : listenerConfigs) {
EventListener listener = listenerConfig.getImplementation();
if (listener == null) {
try {
listener = ClassLoaderUtil.newInstance(clientConfig.getClassLoader(), listenerConfig.getClassName());
} catch (Exception e) {
LOGGER.severe(e);
}
}
if (listener instanceof MembershipListener) {
addMembershipListenerWithoutInit((MembershipListener) listener);
}
}
}
}
public MemberImpl getMember(Address address) {
final Map<Address, MemberImpl> members = membersRef.get();
return members != null ? members.get(address) : null;
}
public MemberImpl getMember(String uuid) {
final Collection<MemberImpl> memberList = getMemberList();
for (MemberImpl member : memberList) {
if (uuid.equals(member.getUuid())) {
return member;
}
}
return null;
}
public Collection<MemberImpl> getMemberList() {
final Map<Address, MemberImpl> members = membersRef.get();
return members != null ? members.values() : Collections.<MemberImpl>emptySet();
}
public Address getMasterAddress() {
final Collection<MemberImpl> memberList = getMemberList();
return !memberList.isEmpty() ? memberList.iterator().next().getAddress() : null;
}
public int getSize() {
return getMemberList().size();
}
public long getClusterTime() {
return Clock.currentTimeMillis();
}
public Client getLocalClient() {
ClientPrincipal cp = connectionManager.getPrincipal();
ClientConnection conn = clusterThread.conn;
return new ClientImpl(cp != null ? cp.getUuid() : null, conn != null ? conn.getLocalSocketAddress() : null);
}
private SerializationService getSerializationService() {
return client.getSerializationService();
}
public String addMembershipListenerWithInit(MembershipListener listener) {
final String id = UuidUtil.buildRandomUuidString();
listeners.put(id, listener);
if (listener instanceof InitialMembershipListener) {
// TODO: needs sync with membership events...
final Cluster cluster = client.getCluster();
((InitialMembershipListener) listener).init(new InitialMembershipEvent(cluster, cluster.getMembers()));
}
return id;
}
public String addMembershipListenerWithoutInit(MembershipListener listener) {
final String id = UUID.randomUUID().toString();
listeners.put(id, listener);
return id;
}
private void initMembershipListener() {
for (MembershipListener membershipListener : listeners.values()) {
if (membershipListener instanceof InitialMembershipListener) {
// TODO: needs sync with membership events...
final Cluster cluster = client.getCluster();
((InitialMembershipListener) membershipListener).init(new InitialMembershipEvent(cluster, cluster.getMembers()));
}
}
}
public boolean removeMembershipListener(String registrationId) {
return listeners.remove(registrationId) != null;
}
public void start() {
clusterThread.start();
try {
clusterThread.await();
} catch (InterruptedException e) {
throw new HazelcastException(e);
}
initMembershipListener();
// started
}
public void stop() {
clusterThread.shutdown();
}
private final class ClusterListenerThread extends Thread {
private volatile ClientConnection conn;
private final List<MemberImpl> members = new LinkedList<MemberImpl>();
private final CountDownLatch latch = new CountDownLatch(1);
private ClusterListenerThread(ThreadGroup group, String name) {
super(group, name);
}
public void await() throws InterruptedException {
latch.await();
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
if (conn == null) {
try {
conn = pickConnection();
} catch (Exception e) {
LOGGER.severe("Error while connecting to cluster!", e);
client.getLifecycleService().shutdown();
latch.countDown();
return;
}
}
getInvocationService().triggerFailedListeners();
loadInitialMemberList();
listenMembershipEvents();
} catch (Exception e) {
if (client.getLifecycleService().isRunning()) {
if (LOGGER.isFinestEnabled()) {
LOGGER.warning("Error while listening cluster events! -> " + conn, e);
} else {
LOGGER.warning("Error while listening cluster events! -> " + conn + ", Error: " + e.toString());
}
}
connectionManager.markOwnerConnectionAsClosed();
IOUtil.closeResource(conn);
conn = null;
fireConnectionEvent(true);
}
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
latch.countDown();
break;
}
}
}
private ClientInvocationServiceImpl getInvocationService() {
return (ClientInvocationServiceImpl) client.getInvocationService();
}
private ClientConnection pickConnection() throws Exception {
final List<InetSocketAddress> socketAddresses = new LinkedList<InetSocketAddress>();
if (!members.isEmpty()) {
for (MemberImpl member : members) {
socketAddresses.add(member.getInetSocketAddress());
}
Collections.shuffle(socketAddresses);
}
socketAddresses.addAll(getConfigAddresses());
return connectToOne(socketAddresses);
}
private void loadInitialMemberList() throws Exception {
final SerializationService serializationService = getSerializationService();
final AddMembershipListenerRequest request = new AddMembershipListenerRequest();
final SerializableCollection coll = (SerializableCollection) connectionManager.sendAndReceive(request, conn);
Map<String, MemberImpl> prevMembers = Collections.emptyMap();
if (!members.isEmpty()) {
prevMembers = new HashMap<String, MemberImpl>(members.size());
for (MemberImpl member : members) {
prevMembers.put(member.getUuid(), member);
}
members.clear();
}
for (Data data : coll) {
members.add((MemberImpl) serializationService.toObject(data));
}
updateMembersRef();
LOGGER.info(membersString());
final List<MembershipEvent> events = new LinkedList<MembershipEvent>();
final Set<Member> eventMembers = Collections.unmodifiableSet(new LinkedHashSet<Member>(members));
for (MemberImpl member : members) {
final MemberImpl former = prevMembers.remove(member.getUuid());
if (former == null) {
events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_ADDED, eventMembers));
}
}
for (MemberImpl member : prevMembers.values()) {
events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_REMOVED, eventMembers));
}
for (MembershipEvent event : events) {
fireMembershipEvent(event);
}
latch.countDown();
}
private void listenMembershipEvents() throws IOException {
final SerializationService serializationService = getSerializationService();
while (!Thread.currentThread().isInterrupted()) {
final Data clientResponseData = conn.read();
final ClientResponse clientResponse = serializationService.toObject(clientResponseData);
final Object eventObject = serializationService.toObject(clientResponse.getResponse());
final ClientMembershipEvent event = (ClientMembershipEvent) eventObject;
final MemberImpl member = (MemberImpl) event.getMember();
boolean membersUpdated = false;
if (event.getEventType() == MembershipEvent.MEMBER_ADDED) {
members.add(member);
membersUpdated = true;
} else if (event.getEventType() == ClientMembershipEvent.MEMBER_REMOVED) {
members.remove(member);
membersUpdated = true;
// getConnectionManager().removeConnectionPool(member.getAddress()); //TODO
} else if (event.getEventType() == ClientMembershipEvent.MEMBER_ATTRIBUTE_CHANGED) {
MemberAttributeChange memberAttributeChange = event.getMemberAttributeChange();
Map<Address, MemberImpl> memberMap = membersRef.get();
if (memberMap != null) {
for (MemberImpl target : memberMap.values()) {
if (target.getUuid().equals(memberAttributeChange.getUuid())) {
final MemberAttributeOperationType operationType = memberAttributeChange.getOperationType();
final String key = memberAttributeChange.getKey();
final Object value = memberAttributeChange.getValue();
target.updateAttribute(operationType, key, value);
MemberAttributeEvent memberAttributeEvent = new MemberAttributeEvent(
client.getCluster(), target, operationType, key, value);
fireMemberAttributeEvent(memberAttributeEvent);
break;
}
}
}
}
if (membersUpdated) {
((ClientPartitionServiceImpl) client.getClientPartitionService()).refreshPartitions();
updateMembersRef();
LOGGER.info(membersString());
fireMembershipEvent(new MembershipEvent(client.getCluster(), member, event.getEventType(),
Collections.unmodifiableSet(new LinkedHashSet<Member>(members))));
}
}
}
private void fireMembershipEvent(final MembershipEvent event) {
client.getClientExecutionService().executeInternal(new Runnable() {
public void run() {
for (MembershipListener listener : listeners.values()) {
if (event.getEventType() == MembershipEvent.MEMBER_ADDED) {
listener.memberAdded(event);
} else {
listener.memberRemoved(event);
}
}
}
});
}
private void fireMemberAttributeEvent(final MemberAttributeEvent event) {
client.getClientExecutionService().executeInternal(new Runnable() {
@Override
public void run() {
for (MembershipListener listener : listeners.values()) {
listener.memberAttributeChanged(event);
}
}
});
}
private void updateMembersRef() {
final Map<Address, MemberImpl> map = new LinkedHashMap<Address, MemberImpl>(members.size());
for (MemberImpl member : members) {
map.put(member.getAddress(), member);
}
membersRef.set(Collections.unmodifiableMap(map));
}
void shutdown() {
interrupt();
final ClientConnection c = conn;
if (c != null) {
c.close();
}
}
}
private ClientConnection connectToOne(final Collection<InetSocketAddress> socketAddresses) throws Exception {
final ClientNetworkConfig networkConfig = getClientConfig().getNetworkConfig();
final int connectionAttemptLimit = networkConfig.getConnectionAttemptLimit();
final int connectionAttemptPeriod = networkConfig.getConnectionAttemptPeriod();
int attempt = 0;
Throwable lastError = null;
while (true) {
final long nextTry = Clock.currentTimeMillis() + connectionAttemptPeriod;
for (InetSocketAddress isa : socketAddresses) {
Address address = new Address(isa);
try {
final ClientConnection connection = connectionManager.ownerConnection(address);
fireConnectionEvent(false);
return connection;
} catch (IOException e) {
lastError = e;
LOGGER.finest("IO error during initial connection...", e);
} catch (AuthenticationException e) {
lastError = e;
LOGGER.warning("Authentication error on " + address, e);
}
}
if (attempt++ >= connectionAttemptLimit) {
break;
}
final long remainingTime = nextTry - Clock.currentTimeMillis();
LOGGER.warning(
String.format("Unable to get alive cluster connection,"
+ " try in %d ms later, attempt %d of %d.",
Math.max(0, remainingTime), attempt, connectionAttemptLimit));
if (remainingTime > 0) {
try {
Thread.sleep(remainingTime);
} catch (InterruptedException e) {
break;
}
}
}
throw new IllegalStateException("Unable to connect to any address in the config!", lastError);
}
private void fireConnectionEvent(boolean disconnected) {
final LifecycleServiceImpl lifecycleService = (LifecycleServiceImpl) client.getLifecycleService();
final LifecycleState state = disconnected ? LifecycleState.CLIENT_DISCONNECTED : LifecycleState.CLIENT_CONNECTED;
lifecycleService.fireLifecycleEvent(state);
}
private Collection<InetSocketAddress> getConfigAddresses() {
final List<InetSocketAddress> socketAddresses = new LinkedList<InetSocketAddress>();
final List<String> addresses = getClientConfig().getAddresses();
Collections.shuffle(addresses);
for (String address : addresses) {
socketAddresses.addAll(AddressHelper.getSocketAddresses(address));
}
return socketAddresses;
}
private ClientConfig getClientConfig() {
return client.getClientConfig();
}
private String membersString() {
StringBuilder sb = new StringBuilder("\n\nMembers [");
final Collection<MemberImpl> members = getMemberList();
sb.append(members != null ? members.size() : 0);
sb.append("] {");
if (members != null) {
for (Member member : members) {
sb.append("\n\t").append(member);
}
}
sb.append("\n}\n");
return sb.toString();
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientClusterServiceImpl.java
|
2,597 |
private class MasterPingRequestHandler extends BaseTransportRequestHandler<MasterPingRequest> {
public static final String ACTION = "discovery/zen/fd/masterPing";
@Override
public MasterPingRequest newInstance() {
return new MasterPingRequest();
}
@Override
public void messageReceived(MasterPingRequest request, TransportChannel channel) throws Exception {
DiscoveryNodes nodes = nodesProvider.nodes();
// check if we are really the same master as the one we seemed to be think we are
// this can happen if the master got "kill -9" and then another node started using the same port
if (!request.masterNodeId.equals(nodes.localNodeId())) {
throw new NotMasterException();
}
// if we are no longer master, fail...
if (!nodes.localNodeMaster()) {
throw new NoLongerMasterException();
}
if (!nodes.nodeExists(request.nodeId)) {
throw new NodeDoesNotExistOnMasterException();
}
// send a response, and note if we are connected to the master or not
channel.sendResponse(new MasterPingResponseResponse(nodes.nodeExists(request.nodeId)));
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
| 1no label
|
src_main_java_org_elasticsearch_discovery_zen_fd_MasterFaultDetection.java
|
2,572 |
clusterService.submitStateUpdateTask("zen-disco-node_left(" + node + ")", Priority.URGENT, new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
DiscoveryNodes.Builder builder = DiscoveryNodes.builder(currentState.nodes()).remove(node.id());
latestDiscoNodes = builder.build();
currentState = ClusterState.builder(currentState).nodes(latestDiscoNodes).build();
// check if we have enough master nodes, if not, we need to move into joining the cluster again
if (!electMaster.hasEnoughMasterNodes(currentState.nodes())) {
return rejoin(currentState, "not enough master nodes");
}
// eagerly run reroute to remove dead nodes from routing table
RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder(currentState).build());
return ClusterState.builder(currentState).routingResult(routingResult).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
}
});
| 1no label
|
src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java
|
63 |
public class ONoLock extends OAbstractLock {
public void lock() {
}
public void unlock() {
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_concur_lock_ONoLock.java
|
262 |
public interface EmailService {
public boolean sendTemplateEmail(String emailAddress, EmailInfo emailInfo, HashMap<String,Object> props);
public boolean sendTemplateEmail(EmailTarget emailTarget, EmailInfo emailInfo, HashMap<String,Object> props);
public boolean sendBasicEmail(EmailInfo emailInfo, EmailTarget emailTarget, HashMap<String,Object> props);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_email_service_EmailService.java
|
22 |
public interface Fun<A,T> { T apply(A a); }
| 0true
|
src_main_java_jsr166e_CompletableFuture.java
|
363 |
public class DeleteRepositoryRequest extends AcknowledgedRequest<DeleteRepositoryRequest> {
private String name;
DeleteRepositoryRequest() {
}
/**
* Constructs a new unregister repository request with the provided name.
*
* @param name name of the repository
*/
public DeleteRepositoryRequest(String name) {
this.name = name;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (name == null) {
validationException = addValidationError("name is missing", validationException);
}
return validationException;
}
/**
* Sets the name of the repository to unregister.
*
* @param name name of the repository
*/
public DeleteRepositoryRequest name(String name) {
this.name = name;
return this;
}
/**
* The name of the repository.
*
* @return the name of the repository
*/
public String name() {
return this.name;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
name = in.readString();
readTimeout(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(name);
writeTimeout(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_repositories_delete_DeleteRepositoryRequest.java
|
314 |
LOG_FILE_LEVEL("log.file.level", "File logging level", String.class, "fine", new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
OLogManager.instance().setLevel((String) iNewValue, FileHandler.class);
}
}),
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_config_OGlobalConfiguration.java
|
614 |
public static enum Flag {
// Do not change the order of these flags we use
// the ordinal for encoding! Only append to the end!
Store("store"),
Indexing("indexing"),
Get("get"),
Search("search"),
Merge("merge"),
Flush("flush"),
Refresh("refresh"),
FilterCache("filter_cache"),
IdCache("id_cache"),
FieldData("fielddata"),
Docs("docs"),
Warmer("warmer"),
Percolate("percolate"),
Completion("completion"),
Segments("segments"),
Translog("translog");
private final String restName;
Flag(String restName) {
this.restName = restName;
}
public String getRestName() {
return restName;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_stats_CommonStatsFlags.java
|
1,534 |
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> {
private Direction direction;
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
this.direction = Direction.valueOf(context.getConfiguration().get(DIRECTION));
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
if (this.direction.equals(IN) || this.direction.equals(BOTH)) {
long edgesProcessed = 0;
for (final Edge e : value.getEdges(IN)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
value.getPaths(edge, true);
edgesProcessed++;
edge.clearPaths();
}
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.IN_EDGES_PROCESSED, edgesProcessed);
} else {
for (final Edge e : value.getEdges(IN)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
edge.clearPaths();
}
}
}
if (this.direction.equals(OUT) || this.direction.equals(BOTH)) {
long edgesProcessed = 0;
for (final Edge e : value.getEdges(OUT)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
value.getPaths(edge, true);
edgesProcessed++;
edge.clearPaths();
}
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_PROCESSED, edgesProcessed);
} else {
for (final Edge e : value.getEdges(OUT)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
edge.clearPaths();
}
}
}
context.write(NullWritable.get(), value);
}
}
| 1no label
|
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_transform_EdgesVerticesMap.java
|
3,442 |
public class TraceableIsStillExecutingOperation extends AbstractOperation {
private String serviceName;
private Object identifier;
TraceableIsStillExecutingOperation() {
}
public TraceableIsStillExecutingOperation(String serviceName, Object identifier) {
this.serviceName = serviceName;
this.identifier = identifier;
}
@Override
public void run() throws Exception {
NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine();
BasicOperationService operationService = (BasicOperationService) nodeEngine.operationService;
boolean executing = operationService.isOperationExecuting(getCallerAddress(), getCallerUuid(),
serviceName, identifier);
getResponseHandler().sendResponse(executing);
}
@Override
public boolean returnsResponse() {
return false;
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
serviceName = in.readUTF();
identifier = in.readObject();
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeUTF(serviceName);
out.writeObject(identifier);
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_spi_impl_TraceableIsStillExecutingOperation.java
|
588 |
class ShardRefreshResponse extends BroadcastShardOperationResponse {
ShardRefreshResponse() {
}
public ShardRefreshResponse(String index, int shardId) {
super(index, shardId);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_refresh_ShardRefreshResponse.java
|
577 |
public static final class Defaults {
public static final boolean WAIT_FOR_MERGE = true;
public static final int MAX_NUM_SEGMENTS = -1;
public static final boolean ONLY_EXPUNGE_DELETES = false;
public static final boolean FLUSH = true;
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_optimize_OptimizeRequest.java
|
346 |
public class SpaceDelimitedNodeValueMerge extends NodeValueMerge {
@Override
public String getDelimiter() {
return " ";
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_SpaceDelimitedNodeValueMerge.java
|
377 |
public interface LocaleDao {
/**
* @return The locale for the passed in code
*/
public Locale findLocaleByCode(String localeCode);
/**
* Returns the page template with the passed in id.
*
* @return The default locale
*/
public Locale findDefaultLocale();
/**
* Returns all supported BLC locales.
* @return
*/
public List<Locale> findAllLocales();
public Locale save(Locale locale);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_locale_dao_LocaleDao.java
|
578 |
public class OptimizeRequestBuilder extends BroadcastOperationRequestBuilder<OptimizeRequest, OptimizeResponse, OptimizeRequestBuilder> {
public OptimizeRequestBuilder(IndicesAdminClient indicesClient) {
super((InternalIndicesAdminClient) indicesClient, new OptimizeRequest());
}
/**
* Should the call block until the optimize completes. Defaults to <tt>true</tt>.
*/
public OptimizeRequestBuilder setWaitForMerge(boolean waitForMerge) {
request.waitForMerge(waitForMerge);
return this;
}
/**
* Will optimize the index down to <= maxNumSegments. By default, will cause the optimize
* process to optimize down to half the configured number of segments.
*/
public OptimizeRequestBuilder setMaxNumSegments(int maxNumSegments) {
request.maxNumSegments(maxNumSegments);
return this;
}
/**
* Should the optimization only expunge deletes from the index, without full optimization.
* Defaults to full optimization (<tt>false</tt>).
*/
public OptimizeRequestBuilder setOnlyExpungeDeletes(boolean onlyExpungeDeletes) {
request.onlyExpungeDeletes(onlyExpungeDeletes);
return this;
}
/**
* Should flush be performed after the optimization. Defaults to <tt>true</tt>.
*/
public OptimizeRequestBuilder setFlush(boolean flush) {
request.flush(flush);
return this;
}
@Override
protected void doExecute(ActionListener<OptimizeResponse> listener) {
((IndicesAdminClient) client).optimize(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_optimize_OptimizeRequestBuilder.java
|
862 |
public class OSecurityShared extends OSharedResourceAdaptive implements OSecurity, OCloseable {
public static final String RESTRICTED_CLASSNAME = "ORestricted";
public static final String IDENTITY_CLASSNAME = "OIdentity";
public static final String ALLOW_ALL_FIELD = "_allow";
public static final String ALLOW_READ_FIELD = "_allowRead";
public static final String ALLOW_UPDATE_FIELD = "_allowUpdate";
public static final String ALLOW_DELETE_FIELD = "_allowDelete";
public static final String ONCREATE_IDENTITY_TYPE = "onCreate.identityType";
public static final String ONCREATE_FIELD = "onCreate.fields";
public OSecurityShared() {
super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean(), OGlobalConfiguration.STORAGE_LOCK_TIMEOUT
.getValueAsInteger(), true);
}
public OIdentifiable allowUser(final ODocument iDocument, final String iAllowFieldName, final String iUserName) {
final OUser user = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSecurity().getUser(iUserName);
if (user == null)
throw new IllegalArgumentException("User '" + iUserName + "' not found");
return allowIdentity(iDocument, iAllowFieldName, user.getDocument().getIdentity());
}
public OIdentifiable allowRole(final ODocument iDocument, final String iAllowFieldName, final String iRoleName) {
final ORole role = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSecurity().getRole(iRoleName);
if (role == null)
throw new IllegalArgumentException("Role '" + iRoleName + "' not found");
return allowIdentity(iDocument, iAllowFieldName, role.getDocument().getIdentity());
}
public OIdentifiable allowIdentity(final ODocument iDocument, final String iAllowFieldName, final OIdentifiable iId) {
Set<OIdentifiable> field = iDocument.field(iAllowFieldName);
if (field == null) {
field = new OMVRBTreeRIDSet(iDocument);
iDocument.field(iAllowFieldName, field);
}
field.add(iId);
return iId;
}
public OIdentifiable disallowUser(final ODocument iDocument, final String iAllowFieldName, final String iUserName) {
final OUser user = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSecurity().getUser(iUserName);
if (user == null)
throw new IllegalArgumentException("User '" + iUserName + "' not found");
return disallowIdentity(iDocument, iAllowFieldName, user.getDocument().getIdentity());
}
public OIdentifiable disallowRole(final ODocument iDocument, final String iAllowFieldName, final String iRoleName) {
final ORole role = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSecurity().getRole(iRoleName);
if (role == null)
throw new IllegalArgumentException("Role '" + iRoleName + "' not found");
return disallowIdentity(iDocument, iAllowFieldName, role.getDocument().getIdentity());
}
public OIdentifiable disallowIdentity(final ODocument iDocument, final String iAllowFieldName, final OIdentifiable iId) {
Set<OIdentifiable> field = iDocument.field(iAllowFieldName);
if (field != null)
field.remove(iId);
return iId;
}
public boolean isAllowed(final Set<OIdentifiable> iAllowAll, final Set<OIdentifiable> iAllowOperation) {
if (iAllowAll == null || iAllowAll.isEmpty())
return true;
final OUser currentUser = ODatabaseRecordThreadLocal.INSTANCE.get().getUser();
if (currentUser != null) {
// CHECK IF CURRENT USER IS ENLISTED
if (!iAllowAll.contains(currentUser.getDocument().getIdentity())) {
// CHECK AGAINST SPECIFIC _ALLOW OPERATION
if (iAllowOperation != null && iAllowOperation.contains(currentUser.getDocument().getIdentity()))
return true;
// CHECK IF AT LEAST ONE OF THE USER'S ROLES IS ENLISTED
for (ORole r : currentUser.getRoles()) {
// CHECK AGAINST GENERIC _ALLOW
if (iAllowAll.contains(r.getDocument().getIdentity()))
return true;
// CHECK AGAINST SPECIFIC _ALLOW OPERATION
if (iAllowOperation != null && iAllowOperation.contains(r.getDocument().getIdentity()))
return true;
}
return false;
}
}
return true;
}
public OUser authenticate(final String iUserName, final String iUserPassword) {
acquireExclusiveLock();
try {
final String dbName = getDatabase().getName();
final OUser user = getUser(iUserName);
if (user == null)
throw new OSecurityAccessException(dbName, "User or password not valid for database: '" + dbName + "'");
if (user.getAccountStatus() != STATUSES.ACTIVE)
throw new OSecurityAccessException(dbName, "User '" + iUserName + "' is not active");
if (!(getDatabase().getStorage() instanceof OStorageProxy)) {
// CHECK USER & PASSWORD
if (!user.checkPassword(iUserPassword)) {
// WAIT A BIT TO AVOID BRUTE FORCE
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
throw new OSecurityAccessException(dbName, "User or password not valid for database: '" + dbName + "'");
}
}
return user;
} finally {
releaseExclusiveLock();
}
}
public OUser getUser(final String iUserName) {
acquireExclusiveLock();
try {
final List<ODocument> result = getDatabase().<OCommandRequest> command(
new OSQLSynchQuery<ODocument>("select from OUser where name = '" + iUserName + "' limit 1").setFetchPlan("roles:1"))
.execute();
if (result != null && !result.isEmpty())
return new OUser(result.get(0));
return null;
} finally {
releaseExclusiveLock();
}
}
public OUser createUser(final String iUserName, final String iUserPassword, final String... iRoles) {
acquireExclusiveLock();
try {
final OUser user = new OUser(iUserName, iUserPassword);
if (iRoles != null)
for (String r : iRoles) {
user.addRole(r);
}
return user.save();
} finally {
releaseExclusiveLock();
}
}
public OUser createUser(final String iUserName, final String iUserPassword, final ORole... iRoles) {
acquireExclusiveLock();
try {
final OUser user = new OUser(iUserName, iUserPassword);
if (iRoles != null)
for (ORole r : iRoles) {
user.addRole(r);
}
return user.save();
} finally {
releaseExclusiveLock();
}
}
public boolean dropUser(final String iUserName) {
acquireExclusiveLock();
try {
final Number removed = getDatabase().<OCommandRequest> command(
new OCommandSQL("delete from OUser where name = '" + iUserName + "'")).execute();
return removed != null && removed.intValue() > 0;
} finally {
releaseExclusiveLock();
}
}
public ORole getRole(final OIdentifiable iRole) {
acquireExclusiveLock();
try {
final ODocument doc = iRole.getRecord();
if ("ORole".equals(doc.getClassName()))
return new ORole(doc);
return null;
} finally {
releaseExclusiveLock();
}
}
public ORole getRole(final String iRoleName) {
acquireExclusiveLock();
try {
final List<ODocument> result = getDatabase().<OCommandRequest> command(
new OSQLSynchQuery<ODocument>("select from ORole where name = '" + iRoleName + "' limit 1")).execute();
if (result != null && !result.isEmpty())
return new ORole(result.get(0));
return null;
} catch (Exception ex) {
OLogManager.instance().error(this, "Failed to get role : " + iRoleName + " " + ex.getMessage());
return null;
} finally {
releaseExclusiveLock();
}
}
public ORole createRole(final String iRoleName, final ORole.ALLOW_MODES iAllowMode) {
return createRole(iRoleName, null, iAllowMode);
}
public ORole createRole(final String iRoleName, final ORole iParent, final ORole.ALLOW_MODES iAllowMode) {
acquireExclusiveLock();
try {
final ORole role = new ORole(iRoleName, iParent, iAllowMode);
return role.save();
} finally {
releaseExclusiveLock();
}
}
public boolean dropRole(final String iRoleName) {
acquireExclusiveLock();
try {
final Number removed = getDatabase().<OCommandRequest> command(
new OCommandSQL("delete from ORole where name = '" + iRoleName + "'")).execute();
return removed != null && removed.intValue() > 0;
} finally {
releaseExclusiveLock();
}
}
public List<ODocument> getAllUsers() {
acquireExclusiveLock();
try {
return getDatabase().<OCommandRequest> command(new OSQLSynchQuery<ODocument>("select from OUser")).execute();
} finally {
releaseExclusiveLock();
}
}
public List<ODocument> getAllRoles() {
acquireExclusiveLock();
try {
return getDatabase().<OCommandRequest> command(new OSQLSynchQuery<ODocument>("select from ORole")).execute();
} finally {
releaseExclusiveLock();
}
}
public OUser create() {
acquireExclusiveLock();
try {
if (!getDatabase().getMetadata().getSchema().getClasses().isEmpty())
return null;
final OUser adminUser = createMetadata();
final ORole readerRole = createRole("reader", ORole.ALLOW_MODES.DENY_ALL_BUT);
readerRole.addRule(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.CLUSTER + "." + OMetadataDefault.CLUSTER_INTERNAL_NAME, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".orole", ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".ouser", ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.ALL_CLASSES, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.ALL_CLUSTERS, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.RECORD_HOOK, ORole.PERMISSION_READ);
readerRole.save();
createUser("reader", "reader", new String[] { readerRole.getName() });
final ORole writerRole = createRole("writer", ORole.ALLOW_MODES.DENY_ALL_BUT);
writerRole.addRule(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_READ);
writerRole.addRule(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ + ORole.PERMISSION_CREATE
+ ORole.PERMISSION_UPDATE);
writerRole.addRule(ODatabaseSecurityResources.CLUSTER + "." + OMetadataDefault.CLUSTER_INTERNAL_NAME, ORole.PERMISSION_READ);
writerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".orole", ORole.PERMISSION_READ);
writerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".ouser", ORole.PERMISSION_READ);
writerRole.addRule(ODatabaseSecurityResources.ALL_CLASSES, ORole.PERMISSION_ALL);
writerRole.addRule(ODatabaseSecurityResources.ALL_CLUSTERS, ORole.PERMISSION_ALL);
writerRole.addRule(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_ALL);
writerRole.addRule(ODatabaseSecurityResources.RECORD_HOOK, ORole.PERMISSION_ALL);
writerRole.save();
createUser("writer", "writer", new String[] { writerRole.getName() });
return adminUser;
} finally {
releaseExclusiveLock();
}
}
/**
* Repairs the security structure if broken by creating the ADMIN role and user with default password.
*
* @return
*/
public OUser repair() {
acquireExclusiveLock();
try {
getDatabase().getMetadata().getIndexManager().dropIndex("OUser.name");
getDatabase().getMetadata().getIndexManager().dropIndex("ORole.name");
return createMetadata();
} finally {
releaseExclusiveLock();
}
}
public OUser createMetadata() {
final ODatabaseRecord database = getDatabase();
OClass identityClass = database.getMetadata().getSchema().getClass(IDENTITY_CLASSNAME); // SINCE 1.2.0
if (identityClass == null)
identityClass = database.getMetadata().getSchema().createAbstractClass(IDENTITY_CLASSNAME);
OClass roleClass = database.getMetadata().getSchema().getClass("ORole");
if (roleClass == null)
roleClass = database.getMetadata().getSchema().createClass("ORole", identityClass);
else if (roleClass.getSuperClass() == null)
// MIGRATE AUTOMATICALLY TO 1.2.0
roleClass.setSuperClass(identityClass);
if (!roleClass.existsProperty("name")) {
roleClass.createProperty("name", OType.STRING).setMandatory(true).setNotNull(true).setCollate("ci");
roleClass.createIndex("ORole.name", INDEX_TYPE.UNIQUE, ONullOutputListener.INSTANCE, "name");
} else {
final Set<OIndex<?>> indexes = roleClass.getInvolvedIndexes("name");
if (indexes.isEmpty())
roleClass.createIndex("ORole.name", INDEX_TYPE.UNIQUE, ONullOutputListener.INSTANCE, "name");
}
if (!roleClass.existsProperty("mode"))
roleClass.createProperty("mode", OType.BYTE);
if (!roleClass.existsProperty("rules"))
roleClass.createProperty("rules", OType.EMBEDDEDMAP, OType.BYTE);
if (!roleClass.existsProperty("inheritedRole"))
roleClass.createProperty("inheritedRole", OType.LINK, roleClass);
OClass userClass = database.getMetadata().getSchema().getClass("OUser");
if (userClass == null)
userClass = database.getMetadata().getSchema().createClass("OUser", identityClass);
else if (userClass.getSuperClass() == null)
// MIGRATE AUTOMATICALLY TO 1.2.0
userClass.setSuperClass(identityClass);
if (!userClass.existsProperty("name")) {
userClass.createProperty("name", OType.STRING).setMandatory(true).setNotNull(true).setCollate("ci");
userClass.createIndex("OUser.name", INDEX_TYPE.UNIQUE, ONullOutputListener.INSTANCE, "name");
}
if (!userClass.existsProperty("password"))
userClass.createProperty("password", OType.STRING).setMandatory(true).setNotNull(true);
if (!userClass.existsProperty("roles"))
userClass.createProperty("roles", OType.LINKSET, roleClass);
if (!userClass.existsProperty("status"))
userClass.createProperty("status", OType.STRING).setMandatory(true).setNotNull(true);
// CREATE ROLES AND USERS
ORole adminRole = getRole(ORole.ADMIN);
if (adminRole == null) {
adminRole = createRole(ORole.ADMIN, ORole.ALLOW_MODES.ALLOW_ALL_BUT);
adminRole.addRule(ODatabaseSecurityResources.BYPASS_RESTRICTED, ORole.PERMISSION_ALL).save();
}
OUser adminUser = getUser(OUser.ADMIN);
if (adminUser == null)
adminUser = createUser(OUser.ADMIN, OUser.ADMIN, adminRole);
// SINCE 1.2.0
OClass restrictedClass = database.getMetadata().getSchema().getClass(RESTRICTED_CLASSNAME);
if (restrictedClass == null)
restrictedClass = database.getMetadata().getSchema().createAbstractClass(RESTRICTED_CLASSNAME);
if (!restrictedClass.existsProperty(ALLOW_ALL_FIELD))
restrictedClass.createProperty(ALLOW_ALL_FIELD, OType.LINKSET, database.getMetadata().getSchema()
.getClass(IDENTITY_CLASSNAME));
if (!restrictedClass.existsProperty(ALLOW_READ_FIELD))
restrictedClass.createProperty(ALLOW_READ_FIELD, OType.LINKSET,
database.getMetadata().getSchema().getClass(IDENTITY_CLASSNAME));
if (!restrictedClass.existsProperty(ALLOW_UPDATE_FIELD))
restrictedClass.createProperty(ALLOW_UPDATE_FIELD, OType.LINKSET,
database.getMetadata().getSchema().getClass(IDENTITY_CLASSNAME));
if (!restrictedClass.existsProperty(ALLOW_DELETE_FIELD))
restrictedClass.createProperty(ALLOW_DELETE_FIELD, OType.LINKSET,
database.getMetadata().getSchema().getClass(IDENTITY_CLASSNAME));
return adminUser;
}
public void close() {
}
public void load() {
final OClass userClass = getDatabase().getMetadata().getSchema().getClass("OUser");
if (userClass != null) {
// @COMPATIBILITY <1.3.0
if (!userClass.existsProperty("status")) {
userClass.createProperty("status", OType.STRING).setMandatory(true).setNotNull(true);
}
OProperty p = userClass.getProperty("name");
if (p == null)
p = userClass.createProperty("name", OType.STRING).setMandatory(true).setNotNull(true);
if (userClass.getInvolvedIndexes("name") == null)
p.createIndex(INDEX_TYPE.UNIQUE);
// ROLE
final OClass roleClass = getDatabase().getMetadata().getSchema().getClass("ORole");
if (!roleClass.existsProperty("inheritedRole")) {
roleClass.createProperty("inheritedRole", OType.LINK, roleClass);
}
p = roleClass.getProperty("name");
if (p == null)
p = roleClass.createProperty("name", OType.STRING).setMandatory(true).setNotNull(true);
if (roleClass.getInvolvedIndexes("name") == null)
p.createIndex(INDEX_TYPE.UNIQUE);
}
}
private ODatabaseRecord getDatabase() {
return ODatabaseRecordThreadLocal.INSTANCE.get();
}
public void createClassTrigger() {
final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.get();
OClass classTrigger = db.getMetadata().getSchema().getClass(OClassTrigger.CLASSNAME);
if (classTrigger == null)
classTrigger = db.getMetadata().getSchema().createAbstractClass(OClassTrigger.CLASSNAME);
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_metadata_security_OSecurityShared.java
|
272 |
public class ServerInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String serverName;
private Integer serverPort;
private Integer securePort;
private String appName;
public String getSecureHost() {
StringBuffer sb = new StringBuffer();
sb.append(serverName);
if (!securePort.equals("443")) {
sb.append(":");
sb.append(securePort);
}
return sb.toString();
}
public String getHost() {
StringBuffer sb = new StringBuffer();
sb.append(serverName);
if (!serverPort.equals("80")) {
sb.append(":");
sb.append(serverPort);
}
return sb.toString();
}
/**
* @return the serverName
*/
public String getServerName() {
return serverName;
}
/**
* @param serverName the serverName to set
*/
public void setServerName(String serverName) {
this.serverName = serverName;
}
/**
* @return the serverPort
*/
public Integer getServerPort() {
return serverPort;
}
/**
* @param serverPort the serverPort to set
*/
public void setServerPort(Integer serverPort) {
this.serverPort = serverPort;
}
/**
* @return the securePort
*/
public Integer getSecurePort() {
return securePort;
}
/**
* @param securePort the securePort to set
*/
public void setSecurePort(Integer securePort) {
this.securePort = securePort;
}
/**
* @return the appName
*/
public String getAppName() {
return appName;
}
/**
* @param appName the appName to set
*/
public void setAppName(String appName) {
this.appName = appName;
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_email_service_info_ServerInfo.java
|
336 |
public interface MergeHandler {
/**
* Perform the merge using the supplied list of nodes from the source and
* patch documents, respectively. Also, a list of nodes that have already
* been merged is provided and may be used by the implementation when
* necessary.
*
* @param nodeList1 list of nodes to be merged from the source document
* @param nodeList2 list of nodes to be merged form the patch document
* @param exhaustedNodes already merged nodes
* @return list of merged nodes
*/
public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes);
/**
* Retrieve the priority for the handler. Priorities are used by the MergeManager
* to establish the order of operations for performing merges.
*
* @return the priority value
*/
public int getPriority();
/**
* Set the priority for this handler
* @param priority
*/
public void setPriority(int priority);
/**
* Retrieve the XPath query associated with this handler. XPath is used by the handler
* to define to section of the source and patch documents that will be merged.
*
* @return the xpath query
*/
public String getXPath();
/**
* Set the xpath query
*
* @param xpath
*/
public void setXPath(String xpath);
/**
* Retrieve any child merge handlers associated with this handler. Child merge handlers
* may be added alter merge behavior for a subsection of the merge area defined
* by this merge handler.
*
* @return child merge handlers
*/
public MergeHandler[] getChildren();
/**
* Set the child merge handlers
*
* @param children
*/
public void setChildren(MergeHandler[] children);
/**
* Retrieve the name associated with this merge handlers. Merge handler names are
* period-delimited numeric strings that define the hierarchical relationship of mergehandlers
* and their children. For example, "2" could be used to define the second handler in the configuration
* list and "2.1" would be the name describing the first child handler of "2".
*
* @return the period-delimited numeric string that names this handler
*/
public String getName();
/**
* Set the period-delimited numeric string that names this handler
*
* @param name
*/
public void setName(String name);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_MergeHandler.java
|
1,616 |
private class TaskPollThread extends Thread {
private final Map<Integer, Class<? extends ConsoleRequest>> consoleRequests =
new HashMap<Integer, Class<? extends ConsoleRequest>>();
private final Random rand = new Random();
TaskPollThread() {
super(instance.node.threadGroup, instance.node.getThreadNamePrefix("MC.Task.Poller"));
register(new RuntimeStateRequest());
register(new ThreadDumpRequest());
register(new ExecuteScriptRequest());
register(new EvictLocalMapRequest());
register(new ConsoleCommandRequest());
register(new MapConfigRequest());
register(new MemberConfigRequest());
register(new ClusterPropsRequest());
register(new GetLogsRequest());
register(new RunGcRequest());
register(new GetMemberSystemPropertiesRequest());
register(new GetMapEntryRequest());
register(new VersionMismatchLogRequest());
register(new ShutdownMemberRequest());
register(new GetSystemWarningsRequest());
}
public void register(ConsoleRequest consoleRequest) {
consoleRequests.put(consoleRequest.getType(), consoleRequest.getClass());
}
public void processTaskAndPostResponse(int taskId, ConsoleRequest task) {
try {
//todo: don't we need to close this connection?
HttpURLConnection connection = openPostResponseConnection();
OutputStream outputStream = connection.getOutputStream();
try {
identifier.write(outputStream);
ObjectDataOutputStream out = serializationService.createObjectDataOutputStream(outputStream);
out.writeInt(taskId);
out.writeInt(task.getType());
task.writeResponse(ManagementCenterService.this, out);
out.flush();
post(connection);
} finally {
closeResource(outputStream);
}
} catch (Exception e) {
logger.warning("Failed process task:" + task, e);
}
}
private HttpURLConnection openPostResponseConnection() throws IOException {
URL url = newPostResponseUrl();
if (logger.isFinestEnabled()) {
logger.finest("Opening sendResponse connection:" + url);
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
return connection;
}
private URL newPostResponseUrl() throws MalformedURLException {
return new URL(cleanupUrl(managementCenterUrl) + "putResponse.do");
}
@Override
public void run() {
try {
while (isRunning()) {
sleepOnVersionMismatch();
processTask();
sleep();
}
} catch (Throwable throwable) {
inspectOutputMemoryError(throwable);
logger.warning("Problem on Hazelcast Management Center Service while polling for a task.", throwable);
}
}
private void sleep() throws InterruptedException {
//todo: magic numbers are no good.
//todo: why the random part
//todo: we want configurable frequency for task polling
Thread.sleep(700 + rand.nextInt(300));
}
private void processTask() {
ObjectDataInputStream inputStream = null;
try {
//todo: don't we need to close the connection?
inputStream = openTaskInputStream();
int taskId = inputStream.readInt();
if (taskId <= 0) {
return;
}
ConsoleRequest task = newTask(inputStream);
processTaskAndPostResponse(taskId, task);
} catch (Exception e) {
//todo: even if there is an internal error with the task, we don't see it. That is kinda shitty
logger.finest(e);
} finally {
IOUtil.closeResource(inputStream);
}
}
private ObjectDataInputStream openTaskInputStream() throws IOException {
URLConnection connection = openGetTaskConnection();
InputStream inputStream = connection.getInputStream();
return serializationService.createObjectDataInputStream(inputStream);
}
private ConsoleRequest newTask(ObjectDataInputStream inputStream)
throws InstantiationException, IllegalAccessException, IOException {
int requestType = inputStream.readInt();
Class<? extends ConsoleRequest> requestClass = consoleRequests.get(requestType);
if (requestClass == null) {
throw new RuntimeException("Failed to find a request for requestType:" + requestType);
}
ConsoleRequest task = requestClass.newInstance();
task.readData(inputStream);
return task;
}
private URLConnection openGetTaskConnection() throws IOException {
URL url = newGetTaskUrl();
if (logger.isFinestEnabled()) {
logger.finest("Opening getTask connection:" + url);
}
URLConnection connection = url.openConnection();
//todo: why do we set this property if the connection is not going to be re-used?
connection.setRequestProperty("Connection", "keep-alive");
return connection;
}
private URL newGetTaskUrl() throws MalformedURLException {
GroupConfig groupConfig = instance.getConfig().getGroupConfig();
Address localAddress = ((MemberImpl) instance.node.getClusterService().getLocalMember()).getAddress();
String urlString = cleanupUrl(managementCenterUrl) + "getTask.do?member=" + localAddress.getHost()
+ ":" + localAddress.getPort() + "&cluster=" + groupConfig.getName();
if (clusterId != null) {
urlString += "&clusterid=" + clusterId;
}
if (securityToken != null) {
urlString += "&securitytoken=" + securityToken;
}
return new URL(urlString);
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_management_ManagementCenterService.java
|
581 |
class ShardOptimizeResponse extends BroadcastShardOperationResponse {
ShardOptimizeResponse() {
}
public ShardOptimizeResponse(String index, int shardId) {
super(index, shardId);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_optimize_ShardOptimizeResponse.java
|
680 |
constructors[SET_REPLICATION] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new SetReplicationOperation();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
|
444 |
public static class OsStats implements ToXContent, Streamable {
int availableProcessors;
long availableMemory;
ObjectIntOpenHashMap<OsInfo.Cpu> cpus;
public OsStats() {
cpus = new ObjectIntOpenHashMap<org.elasticsearch.monitor.os.OsInfo.Cpu>();
}
public void addNodeInfo(NodeInfo nodeInfo) {
availableProcessors += nodeInfo.getOs().availableProcessors();
if (nodeInfo.getOs() == null) {
return;
}
if (nodeInfo.getOs().cpu() != null) {
cpus.addTo(nodeInfo.getOs().cpu(), 1);
}
if (nodeInfo.getOs().getMem() != null && nodeInfo.getOs().getMem().getTotal().bytes() != -1) {
availableMemory += nodeInfo.getOs().getMem().getTotal().bytes();
}
}
public int getAvailableProcessors() {
return availableProcessors;
}
public ByteSizeValue getAvailableMemory() {
return new ByteSizeValue(availableMemory);
}
public ObjectIntOpenHashMap<OsInfo.Cpu> getCpus() {
return cpus;
}
@Override
public void readFrom(StreamInput in) throws IOException {
availableProcessors = in.readVInt();
availableMemory = in.readLong();
int size = in.readVInt();
cpus = new ObjectIntOpenHashMap<OsInfo.Cpu>(size);
for (; size > 0; size--) {
cpus.addTo(OsInfo.Cpu.readCpu(in), in.readVInt());
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(availableProcessors);
out.writeLong(availableMemory);
out.writeVInt(cpus.size());
for (ObjectIntCursor<OsInfo.Cpu> c : cpus) {
c.key.writeTo(out);
out.writeVInt(c.value);
}
}
public static OsStats readOsStats(StreamInput in) throws IOException {
OsStats os = new OsStats();
os.readFrom(in);
return os;
}
static final class Fields {
static final XContentBuilderString AVAILABLE_PROCESSORS = new XContentBuilderString("available_processors");
static final XContentBuilderString MEM = new XContentBuilderString("mem");
static final XContentBuilderString TOTAL = new XContentBuilderString("total");
static final XContentBuilderString TOTAL_IN_BYTES = new XContentBuilderString("total_in_bytes");
static final XContentBuilderString CPU = new XContentBuilderString("cpu");
static final XContentBuilderString COUNT = new XContentBuilderString("count");
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.field(Fields.AVAILABLE_PROCESSORS, availableProcessors);
builder.startObject(Fields.MEM);
builder.byteSizeField(Fields.TOTAL_IN_BYTES, Fields.TOTAL, availableMemory);
builder.endObject();
builder.startArray(Fields.CPU);
for (ObjectIntCursor<OsInfo.Cpu> cpu : cpus) {
builder.startObject();
cpu.key.toXContent(builder, params);
builder.field(Fields.COUNT, cpu.value);
builder.endObject();
}
builder.endArray();
return builder;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsNodes.java
|
340 |
private static class IncrementorEntryProcessor extends AbstractEntryProcessor implements DataSerializable {
IncrementorEntryProcessor() {
super(true);
}
public Object process(Map.Entry entry) {
Integer value = (Integer) entry.getValue();
if (value == null) {
value = 0;
}
if (value == -1) {
entry.setValue(null);
return null;
}
value++;
entry.setValue(value);
return value;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
}
@Override
public void readData(ObjectDataInput in) throws IOException {
}
public void processBackup(Map.Entry entry) {
entry.setValue((Integer) entry.getValue() + 1);
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java
|
346 |
@PreInitializeConfigOptions
public class ElasticSearchIndex implements IndexProvider {
private static final Logger log = LoggerFactory.getLogger(ElasticSearchIndex.class);
private static final String TTL_FIELD = "_ttl";
private static final String STRING_MAPPING_SUFFIX = "$STRING";
public static final ImmutableList<String> DATA_SUBDIRS = ImmutableList.of("data", "work", "logs");
public static final ConfigNamespace ELASTICSEARCH_NS =
new ConfigNamespace(INDEX_NS, "elasticsearch", "Elasticsearch index configuration");
public static final ConfigOption<Boolean> CLIENT_ONLY =
new ConfigOption<Boolean>(ELASTICSEARCH_NS, "client-only",
"The Elasticsearch node.client option is set to this boolean value, and the Elasticsearch node.data " +
"option is set to the negation of this value. True creates a thin client which holds no data. False " +
"creates a regular Elasticsearch cluster node that may store data.",
ConfigOption.Type.GLOBAL_OFFLINE, true);
public static final ConfigOption<String> CLUSTER_NAME =
new ConfigOption<String>(ELASTICSEARCH_NS, "cluster-name",
"The name of the Elasticsearch cluster. This should match the \"cluster.name\" setting " +
"in the Elasticsearch nodes' configuration.", ConfigOption.Type.GLOBAL_OFFLINE, "elasticsearch");
public static final ConfigOption<Boolean> LOCAL_MODE =
new ConfigOption<Boolean>(ELASTICSEARCH_NS, "local-mode",
"On the legacy config track, this option chooses between starting a TransportClient (false) or " +
"a Node with JVM-local transport and local data (true). On the interface config track, this option " +
"is considered by (but optional for) the Node client and ignored by the TransportClient. See the manual " +
"for more information about ES config tracks.",
ConfigOption.Type.GLOBAL_OFFLINE, false);
public static final ConfigOption<Boolean> CLIENT_SNIFF =
new ConfigOption<Boolean>(ELASTICSEARCH_NS, "sniff",
"Whether to enable cluster sniffing. This option only applies to the TransportClient. " +
"Enabling this option makes the TransportClient attempt to discover other cluster nodes " +
"besides those in the initial host list provided at startup.", ConfigOption.Type.MASKABLE, true);
public static final ConfigOption<ElasticSearchSetup> INTERFACE =
new ConfigOption<ElasticSearchSetup>(ELASTICSEARCH_NS, "interface",
"Whether to connect to ES using the Node or Transport client (see the \"Talking to Elasticsearch\" " +
"section of the ES manual for discussion of the difference). Setting this option enables the " +
"interface config track (see manual for more information about ES config tracks).",
ConfigOption.Type.MASKABLE, ElasticSearchSetup.class, ElasticSearchSetup.TRANSPORT_CLIENT);
public static final ConfigOption<Boolean> IGNORE_CLUSTER_NAME =
new ConfigOption<Boolean>(ELASTICSEARCH_NS, "ignore-cluster-name",
"Whether to bypass validation of the cluster name of connected nodes. " +
"This option is only used on the interface configuration track (see manual for " +
"information about ES config tracks).", ConfigOption.Type.MASKABLE, true);
public static final ConfigOption<String> TTL_INTERVAL =
new ConfigOption<String>(ELASTICSEARCH_NS, "ttl-interval",
"The period of time between runs of ES's bulit-in expired document deleter. " +
"This string will become the value of ES's indices.ttl.interval setting and should " +
"be formatted accordingly, e.g. 5s or 60s.", ConfigOption.Type.MASKABLE, "5s");
public static final ConfigOption<String> HEALTH_REQUEST_TIMEOUT =
new ConfigOption<String>(ELASTICSEARCH_NS, "health-request-timeout",
"When Titan initializes its ES backend, Titan waits up to this duration for the " +
"ES cluster health to reach at least yellow status. " +
"This string should be formatted as a natural number followed by the lowercase letter " +
"\"s\", e.g. 3s or 60s.", ConfigOption.Type.MASKABLE, "30s");
public static final ConfigOption<Boolean> LOAD_DEFAULT_NODE_SETTINGS =
new ConfigOption<Boolean>(ELASTICSEARCH_NS, "load-default-node-settings",
"Whether ES's Node client will internally attempt to load default configuration settings " +
"from system properties/process environment variables. Only meaningful when using the Node " +
"client (has no effect with TransportClient).", ConfigOption.Type.MASKABLE, true);
public static final ConfigNamespace ES_EXTRAS_NS =
new ConfigNamespace(ELASTICSEARCH_NS, "ext", "Overrides for arbitrary elasticsearch.yaml settings", true);
private static final IndexFeatures ES_FEATURES = new IndexFeatures.Builder().supportsDocumentTTL()
.setDefaultStringMapping(Mapping.TEXT).supportedStringMappings(Mapping.TEXT, Mapping.TEXTSTRING, Mapping.STRING).build();
public static final int HOST_PORT_DEFAULT = 9300;
private final Node node;
private final Client client;
private final String indexName;
private final int maxResultsSize;
public ElasticSearchIndex(Configuration config) {
indexName = config.get(INDEX_NAME);
checkExpectedClientVersion();
final ElasticSearchSetup.Connection c;
if (!config.has(INTERFACE)) {
c = legacyConfiguration(config);
} else {
c = interfaceConfiguration(config);
}
node = c.getNode();
client = c.getClient();
maxResultsSize = config.get(INDEX_MAX_RESULT_SET_SIZE);
log.debug("Configured ES query result set max size to {}", maxResultsSize);
client.admin().cluster().prepareHealth().setTimeout(config.get(HEALTH_REQUEST_TIMEOUT))
.setWaitForYellowStatus().execute().actionGet();
//Create index if it does not already exist
IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest(indexName)).actionGet();
if (!response.isExists()) {
CreateIndexResponse create = client.admin().indices().prepareCreate(indexName).execute().actionGet();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new TitanException("Interrupted while waiting for index to settle in", e);
}
if (!create.isAcknowledged()) throw new IllegalArgumentException("Could not create index: " + indexName);
}
}
/**
* Configure ElasticSearchIndex's ES client according to semantics introduced in
* 0.5.1. Allows greater flexibility than the previous config semantics. See
* {@link com.thinkaurelius.titan.diskstorage.es.ElasticSearchSetup} for more
* information.
* <p>
* This is activated by setting an explicit value for {@link #INTERFACE} in
* the Titan configuration.
*
* @see #legacyConfiguration(com.thinkaurelius.titan.diskstorage.configuration.Configuration)
* @param config a config passed to ElasticSearchIndex's constructor
* @return a node and client object open and ready for use
*/
private ElasticSearchSetup.Connection interfaceConfiguration(Configuration config) {
ElasticSearchSetup clientMode = config.get(INTERFACE);
try {
return clientMode.connect(config);
} catch (IOException e) {
throw new TitanException(e);
}
}
/**
* Configure ElasticSearchIndex's ES client according to 0.4.x - 0.5.0 semantics.
* This checks local-mode first. If local-mode is true, then it creates a Node that
* uses JVM local transport and can't talk over the network. If local-mode is
* false, then it creates a TransportClient that can talk over the network and
* uses {@link com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration#INDEX_HOSTS}
* as the server addresses. Note that this configuration method
* does not allow creating a Node that talks over the network.
* <p>
* This is activated by <b>not</b> setting an explicit value for {@link #INTERFACE} in the
* Titan configuration.
*
* @see #interfaceConfiguration(com.thinkaurelius.titan.diskstorage.configuration.Configuration)
* @param config a config passed to ElasticSearchIndex's constructor
* @return a node and client object open and ready for use
*/
private ElasticSearchSetup.Connection legacyConfiguration(Configuration config) {
Node node;
Client client;
if (config.get(LOCAL_MODE)) {
log.debug("Configuring ES for JVM local transport");
boolean clientOnly = config.get(CLIENT_ONLY);
boolean local = config.get(LOCAL_MODE);
NodeBuilder builder = NodeBuilder.nodeBuilder();
Preconditions.checkArgument(config.has(INDEX_CONF_FILE) || config.has(INDEX_DIRECTORY),
"Must either configure configuration file or base directory");
if (config.has(INDEX_CONF_FILE)) {
String configFile = config.get(INDEX_CONF_FILE);
ImmutableSettings.Builder sb = ImmutableSettings.settingsBuilder();
log.debug("Configuring ES from YML file [{}]", configFile);
FileInputStream fis = null;
try {
fis = new FileInputStream(configFile);
sb.loadFromStream(configFile, fis);
builder.settings(sb.build());
} catch (FileNotFoundException e) {
throw new TitanException(e);
} finally {
IOUtils.closeQuietly(fis);
}
} else {
String dataDirectory = config.get(INDEX_DIRECTORY);
log.debug("Configuring ES with data directory [{}]", dataDirectory);
File f = new File(dataDirectory);
if (!f.exists()) f.mkdirs();
ImmutableSettings.Builder b = ImmutableSettings.settingsBuilder();
for (String sub : DATA_SUBDIRS) {
String subdir = dataDirectory + File.separator + sub;
f = new File(subdir);
if (!f.exists()) f.mkdirs();
b.put("path." + sub, subdir);
}
b.put("script.disable_dynamic", false);
b.put("indices.ttl.interval", "5s");
builder.settings(b.build());
String clustername = config.get(CLUSTER_NAME);
Preconditions.checkArgument(StringUtils.isNotBlank(clustername), "Invalid cluster name: %s", clustername);
builder.clusterName(clustername);
}
node = builder.client(clientOnly).data(!clientOnly).local(local).node();
client = node.client();
} else {
log.debug("Configuring ES for network transport");
ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder();
if (config.has(CLUSTER_NAME)) {
String clustername = config.get(CLUSTER_NAME);
Preconditions.checkArgument(StringUtils.isNotBlank(clustername), "Invalid cluster name: %s", clustername);
settings.put("cluster.name", clustername);
} else {
settings.put("client.transport.ignore_cluster_name", true);
}
log.debug("Transport sniffing enabled: {}", config.get(CLIENT_SNIFF));
settings.put("client.transport.sniff", config.get(CLIENT_SNIFF));
settings.put("script.disable_dynamic", false);
TransportClient tc = new TransportClient(settings.build());
int defaultPort = config.has(INDEX_PORT)?config.get(INDEX_PORT):HOST_PORT_DEFAULT;
for (String host : config.get(INDEX_HOSTS)) {
String[] hostparts = host.split(":");
String hostname = hostparts[0];
int hostport = defaultPort;
if (hostparts.length == 2) hostport = Integer.parseInt(hostparts[1]);
log.info("Configured remote host: {} : {}", hostname, hostport);
tc.addTransportAddress(new InetSocketTransportAddress(hostname, hostport));
}
client = tc;
node = null;
}
return new ElasticSearchSetup.Connection(node, client);
}
private BackendException convert(Exception esException) {
if (esException instanceof InterruptedException) {
return new TemporaryBackendException("Interrupted while waiting for response", esException);
} else {
return new PermanentBackendException("Unknown exception while executing index operation", esException);
}
}
private static String getDualMappingName(String key) {
return key + STRING_MAPPING_SUFFIX;
}
@Override
public void register(String store, String key, KeyInformation information, BaseTransaction tx) throws BackendException {
XContentBuilder mapping;
Class<?> dataType = information.getDataType();
Mapping map = Mapping.getMapping(information);
Preconditions.checkArgument(map==Mapping.DEFAULT || AttributeUtil.isString(dataType),
"Specified illegal mapping [%s] for data type [%s]",map,dataType);
try {
mapping = XContentFactory.jsonBuilder().
startObject().
startObject(store).
field(TTL_FIELD, new HashMap<String, Object>() {{
put("enabled", true);
}}).
startObject("properties").
startObject(key);
if (AttributeUtil.isString(dataType)) {
if (map==Mapping.DEFAULT) map=Mapping.TEXT;
log.debug("Registering string type for {} with mapping {}", key, map);
mapping.field("type", "string");
switch (map) {
case STRING:
mapping.field("index","not_analyzed");
break;
case TEXT:
//default, do nothing
case TEXTSTRING:
mapping.endObject();
//add string mapping
mapping.startObject(getDualMappingName(key));
mapping.field("type", "string");
mapping.field("index","not_analyzed");
break;
default: throw new AssertionError("Unexpected mapping: "+map);
}
} else if (dataType == Float.class) {
log.debug("Registering float type for {}", key);
mapping.field("type", "float");
} else if (dataType == Double.class || dataType == Decimal.class || dataType == Precision.class) {
log.debug("Registering double type for {}", key);
mapping.field("type", "double");
} else if (dataType == Byte.class) {
log.debug("Registering byte type for {}", key);
mapping.field("type", "byte");
} else if (dataType == Short.class) {
log.debug("Registering short type for {}", key);
mapping.field("type", "short");
} else if (dataType == Integer.class) {
log.debug("Registering integer type for {}", key);
mapping.field("type", "integer");
} else if (dataType == Long.class) {
log.debug("Registering long type for {}", key);
mapping.field("type", "long");
} else if (dataType == Boolean.class) {
log.debug("Registering boolean type for {}", key);
mapping.field("type", "boolean");
} else if (dataType == Geoshape.class) {
log.debug("Registering geo_point type for {}", key);
mapping.field("type", "geo_point");
}
mapping.endObject().endObject().endObject().endObject();
} catch (IOException e) {
throw new PermanentBackendException("Could not render json for put mapping request", e);
}
try {
PutMappingResponse response = client.admin().indices().preparePutMapping(indexName).
setIgnoreConflicts(false).setType(store).setSource(mapping).execute().actionGet();
} catch (Exception e) {
throw convert(e);
}
}
private static Mapping getStringMapping(KeyInformation information) {
assert AttributeUtil.isString(information.getDataType());
Mapping map = Mapping.getMapping(information);
if (map==Mapping.DEFAULT) map = Mapping.TEXT;
return map;
}
private static boolean hasDualStringMapping(KeyInformation information) {
return AttributeUtil.isString(information.getDataType()) && getStringMapping(information)==Mapping.TEXTSTRING;
}
public XContentBuilder getContent(final List<IndexEntry> additions, KeyInformation.StoreRetriever informations, int ttl) throws BackendException {
Preconditions.checkArgument(ttl>=0);
try {
XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
// JSON writes duplicate fields one after another, which forces us
// at this stage to make de-duplication on the IndexEntry list. We don't want to pay the
// price map storage on the Mutation level because non of other backends need that.
Map<String, IndexEntry> uniq = new HashMap<String, IndexEntry>(additions.size()) {{
for (IndexEntry e : additions)
put(e.field, e);
}};
for (IndexEntry add : uniq.values()) {
if (add.value instanceof Number) {
if (AttributeUtil.isWholeNumber((Number) add.value)) {
builder.field(add.field, ((Number) add.value).longValue());
} else { //double or float
builder.field(add.field, ((Number) add.value).doubleValue());
}
} else if (AttributeUtil.isString(add.value)) {
builder.field(add.field, (String) add.value);
if (hasDualStringMapping(informations.get(add.field))) {
builder.field(getDualMappingName(add.field), (String) add.value);
}
} else if (add.value instanceof Geoshape) {
Geoshape shape = (Geoshape) add.value;
if (shape.getType() == Geoshape.Type.POINT) {
Geoshape.Point p = shape.getPoint();
builder.field(add.field, new double[]{p.getLongitude(), p.getLatitude()});
} else throw new UnsupportedOperationException("Geo type is not supported: " + shape.getType());
// builder.startObject(add.key);
// switch (shape.getType()) {
// case POINT:
// Geoshape.Point p = shape.getPoint();
// builder.field("type","point");
// builder.field("coordinates",new double[]{p.getLongitude(),p.getLatitude()});
// break;
// case BOX:
// Geoshape.Point southwest = shape.getPoint(0), northeast = shape.getPoint(1);
// builder.field("type","envelope");
// builder.field("coordinates",new double[][]{
// {southwest.getLongitude(),northeast.getLatitude()},
// {northeast.getLongitude(),southwest.getLatitude()}});
// break;
// default: throw new UnsupportedOperationException("Geo type is not supported: " + shape.getType());
// }
// builder.endObject();
} else throw new IllegalArgumentException("Unsupported type: " + add.value);
}
if (ttl>0) builder.field(TTL_FIELD, TimeUnit.MILLISECONDS.convert(ttl,TimeUnit.SECONDS));
builder.endObject();
return builder;
} catch (IOException e) {
throw new PermanentBackendException("Could not write json");
}
}
@Override
public void mutate(Map<String, Map<String, IndexMutation>> mutations, KeyInformation.IndexRetriever informations, BaseTransaction tx) throws BackendException {
BulkRequestBuilder brb = client.prepareBulk();
int bulkrequests = 0;
try {
for (Map.Entry<String, Map<String, IndexMutation>> stores : mutations.entrySet()) {
String storename = stores.getKey();
for (Map.Entry<String, IndexMutation> entry : stores.getValue().entrySet()) {
String docid = entry.getKey();
IndexMutation mutation = entry.getValue();
assert mutation.isConsolidated();
Preconditions.checkArgument(!(mutation.isNew() && mutation.isDeleted()));
Preconditions.checkArgument(!mutation.isNew() || !mutation.hasDeletions());
Preconditions.checkArgument(!mutation.isDeleted() || !mutation.hasAdditions());
//Deletions first
if (mutation.hasDeletions()) {
if (mutation.isDeleted()) {
log.trace("Deleting entire document {}", docid);
brb.add(new DeleteRequest(indexName, storename, docid));
} else {
StringBuilder script = new StringBuilder();
for (String key : Iterables.transform(mutation.getDeletions(),IndexMutation.ENTRY2FIELD_FCT)) {
script.append("ctx._source.remove(\"" + key + "\"); ");
if (hasDualStringMapping(informations.get(storename,key))) {
script.append("ctx._source.remove(\"" + getDualMappingName(key) + "\"); ");
}
log.trace("Deleting individual field [{}] for document {}", key, docid);
}
brb.add(client.prepareUpdate(indexName, storename, docid).setScript(script.toString()));
bulkrequests++;
}
bulkrequests++;
}
if (mutation.hasAdditions()) {
int ttl = mutation.determineTTL();
if (mutation.isNew()) { //Index
log.trace("Adding entire document {}", docid);
brb.add(new IndexRequest(indexName, storename, docid)
.source(getContent(mutation.getAdditions(), informations.get(storename), ttl)));
} else {
Preconditions.checkArgument(ttl==0,"Elasticsearch only supports TTL on new documents [%s]",docid);
boolean needUpsert = !mutation.hasDeletions();
XContentBuilder builder = getContent(mutation.getAdditions(),informations.get(storename),ttl);
UpdateRequestBuilder update = client.prepareUpdate(indexName, storename, docid).setDoc(builder);
if (needUpsert) update.setUpsert(builder);
log.trace("Updating document {} with upsert {}", docid, needUpsert);
brb.add(update);
bulkrequests++;
}
bulkrequests++;
}
}
}
if (bulkrequests > 0) brb.execute().actionGet();
} catch (Exception e) {
throw convert(e);
}
}
public void restore(Map<String,Map<String, List<IndexEntry>>> documents, KeyInformation.IndexRetriever informations, BaseTransaction tx) throws BackendException {
BulkRequestBuilder bulk = client.prepareBulk();
int requests = 0;
try {
for (Map.Entry<String, Map<String, List<IndexEntry>>> stores : documents.entrySet()) {
String store = stores.getKey();
for (Map.Entry<String, List<IndexEntry>> entry : stores.getValue().entrySet()) {
String docID = entry.getKey();
List<IndexEntry> content = entry.getValue();
if (content == null || content.size() == 0) {
// delete
if (log.isTraceEnabled())
log.trace("Deleting entire document {}", docID);
bulk.add(new DeleteRequest(indexName, store, docID));
requests++;
} else {
// Add
if (log.isTraceEnabled())
log.trace("Adding entire document {}", docID);
bulk.add(new IndexRequest(indexName, store, docID).source(getContent(content, informations.get(store), IndexMutation.determineTTL(content))));
requests++;
}
}
}
if (requests > 0)
bulk.execute().actionGet();
} catch (Exception e) {
throw convert(e);
}
}
public FilterBuilder getFilter(Condition<?> condition, KeyInformation.StoreRetriever informations) {
if (condition instanceof PredicateCondition) {
PredicateCondition<String, ?> atom = (PredicateCondition) condition;
Object value = atom.getValue();
String key = atom.getKey();
TitanPredicate titanPredicate = atom.getPredicate();
if (value instanceof Number) {
Preconditions.checkArgument(titanPredicate instanceof Cmp, "Relation not supported on numeric types: " + titanPredicate);
Cmp numRel = (Cmp) titanPredicate;
Preconditions.checkArgument(value instanceof Number);
switch (numRel) {
case EQUAL:
return FilterBuilders.inFilter(key, value);
case NOT_EQUAL:
return FilterBuilders.notFilter(FilterBuilders.inFilter(key, value));
case LESS_THAN:
return FilterBuilders.rangeFilter(key).lt(value);
case LESS_THAN_EQUAL:
return FilterBuilders.rangeFilter(key).lte(value);
case GREATER_THAN:
return FilterBuilders.rangeFilter(key).gt(value);
case GREATER_THAN_EQUAL:
return FilterBuilders.rangeFilter(key).gte(value);
default:
throw new IllegalArgumentException("Unexpected relation: " + numRel);
}
} else if (value instanceof String) {
Mapping map = getStringMapping(informations.get(key));
String fieldName = key;
if (map==Mapping.TEXT && !titanPredicate.toString().startsWith("CONTAINS"))
throw new IllegalArgumentException("Text mapped string values only support CONTAINS queries and not: " + titanPredicate);
if (map==Mapping.STRING && titanPredicate.toString().startsWith("CONTAINS"))
throw new IllegalArgumentException("String mapped string values do not support CONTAINS queries: " + titanPredicate);
if (map==Mapping.TEXTSTRING && !titanPredicate.toString().startsWith("CONTAINS"))
fieldName = getDualMappingName(key);
if (titanPredicate == Text.CONTAINS) {
value = ((String) value).toLowerCase();
AndFilterBuilder b = FilterBuilders.andFilter();
for (String term : Text.tokenize((String)value)) {
b.add(FilterBuilders.termFilter(fieldName, term));
}
return b;
} else if (titanPredicate == Text.CONTAINS_PREFIX) {
value = ((String) value).toLowerCase();
return FilterBuilders.prefixFilter(fieldName, (String) value);
} else if (titanPredicate == Text.CONTAINS_REGEX) {
value = ((String) value).toLowerCase();
return FilterBuilders.regexpFilter(fieldName, (String) value);
} else if (titanPredicate == Text.PREFIX) {
return FilterBuilders.prefixFilter(fieldName, (String) value);
} else if (titanPredicate == Text.REGEX) {
return FilterBuilders.regexpFilter(fieldName, (String) value);
} else if (titanPredicate == Cmp.EQUAL) {
return FilterBuilders.termFilter(fieldName, (String) value);
} else if (titanPredicate == Cmp.NOT_EQUAL) {
return FilterBuilders.notFilter(FilterBuilders.termFilter(fieldName, (String) value));
} else
throw new IllegalArgumentException("Predicate is not supported for string value: " + titanPredicate);
} else if (value instanceof Geoshape) {
Preconditions.checkArgument(titanPredicate == Geo.WITHIN, "Relation is not supported for geo value: " + titanPredicate);
Geoshape shape = (Geoshape) value;
if (shape.getType() == Geoshape.Type.CIRCLE) {
Geoshape.Point center = shape.getPoint();
return FilterBuilders.geoDistanceFilter(key).lat(center.getLatitude()).lon(center.getLongitude()).distance(shape.getRadius(), DistanceUnit.KILOMETERS);
} else if (shape.getType() == Geoshape.Type.BOX) {
Geoshape.Point southwest = shape.getPoint(0);
Geoshape.Point northeast = shape.getPoint(1);
return FilterBuilders.geoBoundingBoxFilter(key).bottomRight(southwest.getLatitude(), northeast.getLongitude()).topLeft(northeast.getLatitude(), southwest.getLongitude());
} else
throw new IllegalArgumentException("Unsupported or invalid search shape type: " + shape.getType());
} else throw new IllegalArgumentException("Unsupported type: " + value);
} else if (condition instanceof Not) {
return FilterBuilders.notFilter(getFilter(((Not) condition).getChild(),informations));
} else if (condition instanceof And) {
AndFilterBuilder b = FilterBuilders.andFilter();
for (Condition c : condition.getChildren()) {
b.add(getFilter(c,informations));
}
return b;
} else if (condition instanceof Or) {
OrFilterBuilder b = FilterBuilders.orFilter();
for (Condition c : condition.getChildren()) {
b.add(getFilter(c,informations));
}
return b;
} else throw new IllegalArgumentException("Invalid condition: " + condition);
}
@Override
public List<String> query(IndexQuery query, KeyInformation.IndexRetriever informations, BaseTransaction tx) throws BackendException {
SearchRequestBuilder srb = client.prepareSearch(indexName);
srb.setTypes(query.getStore());
srb.setQuery(QueryBuilders.matchAllQuery());
srb.setPostFilter(getFilter(query.getCondition(),informations.get(query.getStore())));
if (!query.getOrder().isEmpty()) {
List<IndexQuery.OrderEntry> orders = query.getOrder();
for (int i = 0; i < orders.size(); i++) {
srb.addSort(new FieldSortBuilder(orders.get(i).getKey())
.order(orders.get(i).getOrder() == Order.ASC ? SortOrder.ASC : SortOrder.DESC)
.ignoreUnmapped(true));
}
}
srb.setFrom(0);
if (query.hasLimit()) srb.setSize(query.getLimit());
else srb.setSize(maxResultsSize);
srb.setNoFields();
//srb.setExplain(true);
SearchResponse response = srb.execute().actionGet();
log.debug("Executed query [{}] in {} ms", query.getCondition(), response.getTookInMillis());
SearchHits hits = response.getHits();
if (!query.hasLimit() && hits.totalHits() >= maxResultsSize)
log.warn("Query result set truncated to first [{}] elements for query: {}", maxResultsSize, query);
List<String> result = new ArrayList<String>(hits.hits().length);
for (SearchHit hit : hits) {
result.add(hit.id());
}
return result;
}
@Override
public Iterable<RawQuery.Result<String>> query(RawQuery query, KeyInformation.IndexRetriever informations, BaseTransaction tx) throws BackendException {
SearchRequestBuilder srb = client.prepareSearch(indexName);
srb.setTypes(query.getStore());
srb.setQuery(QueryBuilders.queryString(query.getQuery()));
srb.setFrom(query.getOffset());
if (query.hasLimit()) srb.setSize(query.getLimit());
else srb.setSize(maxResultsSize);
srb.setNoFields();
//srb.setExplain(true);
SearchResponse response = srb.execute().actionGet();
log.debug("Executed query [{}] in {} ms", query.getQuery(), response.getTookInMillis());
SearchHits hits = response.getHits();
if (!query.hasLimit() && hits.totalHits() >= maxResultsSize)
log.warn("Query result set truncated to first [{}] elements for query: {}", maxResultsSize, query);
List<RawQuery.Result<String>> result = new ArrayList<RawQuery.Result<String>>(hits.hits().length);
for (SearchHit hit : hits) {
result.add(new RawQuery.Result<String>(hit.id(),hit.getScore()));
}
return result;
}
@Override
public boolean supports(KeyInformation information, TitanPredicate titanPredicate) {
Class<?> dataType = information.getDataType();
Mapping mapping = Mapping.getMapping(information);
if (mapping!=Mapping.DEFAULT && !AttributeUtil.isString(dataType)) return false;
if (Number.class.isAssignableFrom(dataType)) {
if (titanPredicate instanceof Cmp) return true;
} else if (dataType == Geoshape.class) {
return titanPredicate == Geo.WITHIN;
} else if (AttributeUtil.isString(dataType)) {
switch(mapping) {
case DEFAULT:
case TEXT:
return titanPredicate == Text.CONTAINS || titanPredicate == Text.CONTAINS_PREFIX || titanPredicate == Text.CONTAINS_REGEX;
case STRING:
return titanPredicate == Cmp.EQUAL || titanPredicate==Cmp.NOT_EQUAL || titanPredicate==Text.REGEX || titanPredicate==Text.PREFIX;
case TEXTSTRING:
return (titanPredicate instanceof Text) || titanPredicate == Cmp.EQUAL || titanPredicate==Cmp.NOT_EQUAL;
}
}
return false;
}
@Override
public boolean supports(KeyInformation information) {
Class<?> dataType = information.getDataType();
Mapping mapping = Mapping.getMapping(information);
if (Number.class.isAssignableFrom(dataType) || dataType == Geoshape.class) {
if (mapping==Mapping.DEFAULT) return true;
} else if (AttributeUtil.isString(dataType)) {
if (mapping==Mapping.DEFAULT || mapping==Mapping.STRING
|| mapping==Mapping.TEXT || mapping==Mapping.TEXTSTRING) return true;
}
return false;
}
@Override
public String mapKey2Field(String key, KeyInformation information) {
Preconditions.checkArgument(!StringUtils.containsAny(key,new char[]{' '}),"Invalid key name provided: %s",key);
return key;
}
@Override
public IndexFeatures getFeatures() {
return ES_FEATURES;
}
@Override
public BaseTransactionConfigurable beginTransaction(BaseTransactionConfig config) throws BackendException {
return new DefaultTransaction(config);
}
@Override
public void close() throws BackendException {
client.close();
if (node != null && !node.isClosed()) {
node.close();
}
}
@Override
public void clearStorage() throws BackendException {
try {
try {
client.admin().indices()
.delete(new DeleteIndexRequest(indexName)).actionGet();
// We wait for one second to let ES delete the river
Thread.sleep(1000);
} catch (IndexMissingException e) {
// Index does not exist... Fine
}
} catch (Exception e) {
throw new PermanentBackendException("Could not delete index " + indexName, e);
} finally {
close();
}
}
/**
* Exposed for testing
*/
Node getNode() {
return node;
}
private void checkExpectedClientVersion() {
if (!Version.CURRENT.equals(ElasticSearchConstants.ES_VERSION_EXPECTED)) {
log.warn("ES client version {} does not match the version with which Titan was compiled {}. This might cause problems.",
Version.CURRENT, ElasticSearchConstants.ES_VERSION_EXPECTED);
} else {
log.debug("Found expected ES client version: {} (OK)", Version.CURRENT);
}
}
}
| 1no label
|
titan-es_src_main_java_com_thinkaurelius_titan_diskstorage_es_ElasticSearchIndex.java
|
4,744 |
public class URLRepository extends BlobStoreRepository {
public final static String TYPE = "url";
private final URLBlobStore blobStore;
private final BlobPath basePath;
private boolean listDirectories;
/**
* Constructs new read-only URL-based repository
*
* @param name repository name
* @param repositorySettings repository settings
* @param indexShardRepository shard repository
* @throws IOException
*/
@Inject
public URLRepository(RepositoryName name, RepositorySettings repositorySettings, IndexShardRepository indexShardRepository) throws IOException {
super(name.getName(), repositorySettings, indexShardRepository);
URL url;
String path = repositorySettings.settings().get("url", componentSettings.get("url"));
if (path == null) {
throw new RepositoryException(name.name(), "missing url");
} else {
url = new URL(path);
}
int concurrentStreams = repositorySettings.settings().getAsInt("concurrent_streams", componentSettings.getAsInt("concurrent_streams", 5));
ExecutorService concurrentStreamPool = EsExecutors.newScaling(1, concurrentStreams, 60, TimeUnit.SECONDS, EsExecutors.daemonThreadFactory(settings, "[fs_stream]"));
listDirectories = repositorySettings.settings().getAsBoolean("list_directories", componentSettings.getAsBoolean("list_directories", true));
blobStore = new URLBlobStore(componentSettings, concurrentStreamPool, url);
basePath = BlobPath.cleanPath();
}
/**
* {@inheritDoc}
*/
@Override
protected BlobStore blobStore() {
return blobStore;
}
@Override
protected BlobPath basePath() {
return basePath;
}
@Override
public ImmutableList<SnapshotId> snapshots() {
if (listDirectories) {
return super.snapshots();
} else {
try {
return readSnapshotList();
} catch (IOException ex) {
throw new RepositoryException(repositoryName, "failed to get snapshot list in repository", ex);
}
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_repositories_uri_URLRepository.java
|
1,081 |
public abstract class OSQLFilterItemAbstract implements OSQLFilterItem {
protected List<OPair<OSQLMethod, Object[]>> operationsChain = null;
public OSQLFilterItemAbstract(final OBaseParser iQueryToParse, final String iText) {
final List<String> parts = OStringSerializerHelper.smartSplit(iText, '.');
setRoot(iQueryToParse, parts.get(0));
if (parts.size() > 1) {
operationsChain = new ArrayList<OPair<OSQLMethod, Object[]>>();
// GET ALL SPECIAL OPERATIONS
for (int i = 1; i < parts.size(); ++i) {
final String part = parts.get(i);
final int pindex = part.indexOf('(');
if (pindex > -1) {
final String methodName = part.substring(0, pindex).trim().toLowerCase(Locale.ENGLISH);
OSQLMethod method = OSQLHelper.getMethodByName(methodName);
final Object[] arguments;
if (method != null) {
if (method.getMaxParams() == -1 || method.getMaxParams() > 0) {
arguments = OStringSerializerHelper.getParameters(part).toArray();
if (arguments.length < method.getMinParams()
|| (method.getMaxParams() > -1 && arguments.length > method.getMaxParams()))
throw new OQueryParsingException(iQueryToParse.parserText, "Syntax error: field operator '"
+ method.getName()
+ "' needs "
+ (method.getMinParams() == method.getMaxParams() ? method.getMinParams() : method.getMinParams() + "-"
+ method.getMaxParams()) + " argument(s) while has been received " + arguments.length, 0);
} else
arguments = null;
} else {
// LOOK FOR FUNCTION
final OSQLFunction f = OSQLEngine.getInstance().getFunction(methodName);
if (f == null)
// ERROR: METHOD/FUNCTION NOT FOUND OR MISPELLED
throw new OQueryParsingException(iQueryToParse.parserText,
"Syntax error: function or field operator not recognized between the supported ones: "
+ Arrays.toString(OSQLHelper.getAllMethodNames()), 0);
if (f.getMaxParams() == -1 || f.getMaxParams() > 0) {
arguments = OStringSerializerHelper.getParameters(part).toArray();
if (arguments.length < f.getMinParams() || (f.getMaxParams() > -1 && arguments.length > f.getMaxParams()))
throw new OQueryParsingException(iQueryToParse.parserText, "Syntax error: function '" + f.getName() + "' needs "
+ (f.getMinParams() == f.getMaxParams() ? f.getMinParams() : f.getMinParams() + "-" + f.getMaxParams())
+ " argument(s) while has been received " + arguments.length, 0);
} else
arguments = null;
method = new OSQLMethodFunctionDelegate(f);
}
// SPECIAL OPERATION FOUND: ADD IT IN TO THE CHAIN
operationsChain.add(new OPair<OSQLMethod, Object[]>(method, arguments));
} else {
operationsChain.add(new OPair<OSQLMethod, Object[]>(OSQLHelper.getMethodByName(OSQLMethodField.NAME),
new Object[] { part }));
}
}
}
}
public abstract String getRoot();
protected abstract void setRoot(OBaseParser iQueryToParse, final String iRoot);
public Object transformValue(final OIdentifiable iRecord, final OCommandContext iContext, Object ioResult) {
if (ioResult != null && operationsChain != null) {
// APPLY OPERATIONS FOLLOWING THE STACK ORDER
OSQLMethod operator = null;
try {
for (OPair<OSQLMethod, Object[]> op : operationsChain) {
operator = op.getKey();
// DON'T PASS THE CURRENT RECORD TO FORCE EVALUATING TEMPORARY RESULT
ioResult = operator.execute(iRecord, iContext, ioResult, op.getValue());
}
} catch (ParseException e) {
OLogManager.instance().exception("Error on conversion of value '%s' using field operator %s", e,
OCommandExecutionException.class, ioResult, operator.getName());
}
}
return ioResult;
}
public boolean hasChainOperators() {
return operationsChain != null;
}
@Override
public String toString() {
final StringBuilder buffer = new StringBuilder();
final String root = getRoot();
if (root != null)
buffer.append(root);
if (operationsChain != null) {
for (OPair<OSQLMethod, Object[]> op : operationsChain) {
buffer.append('.');
buffer.append(op.getKey());
if (op.getValue() != null) {
final Object[] values = op.getValue();
buffer.append('(');
int i = 0;
for (Object v : values) {
if (i++ > 0)
buffer.append(',');
buffer.append(v);
}
buffer.append(')');
}
}
}
return buffer.toString();
}
protected OCollate getCollateForField(final ODocument doc, final String iFieldName) {
if (doc.getSchemaClass() != null) {
final OProperty p = doc.getSchemaClass().getProperty(iFieldName);
if (p != null)
return p.getCollate();
}
return null;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_filter_OSQLFilterItemAbstract.java
|
205 |
public class BigMemoryHydratedCacheManagerImpl extends AbstractHydratedCacheManager {
private static final Log LOG = LogFactory.getLog(BigMemoryHydratedCacheManagerImpl.class);
private static final BigMemoryHydratedCacheManagerImpl MANAGER = new BigMemoryHydratedCacheManagerImpl();
public static BigMemoryHydratedCacheManagerImpl getInstance() {
return MANAGER;
}
private Map<String, List<String>> cacheMemberNamesByEntity = Collections.synchronizedMap(new HashMap<String, List<String>>(100));
private List<String> removeKeys = Collections.synchronizedList(new ArrayList<String>(100));
private Cache offHeap = null;
private BigMemoryHydratedCacheManagerImpl() {
//CacheManager.getInstance() and CacheManager.create() cannot be called in this constructor because it will create two cache manager instances
}
private Cache getHeap() {
if (offHeap == null) {
if (CacheManager.getInstance().cacheExists("hydrated-offheap-cache")) {
offHeap = CacheManager.getInstance().getCache("hydrated-offheap-cache");
} else {
CacheConfiguration config = new CacheConfiguration("hydrated-offheap-cache", 500).eternal(true).overflowToOffHeap(true).maxMemoryOffHeap("1400M");
Cache cache = new Cache(config);
CacheManager.create().addCache(cache);
offHeap = cache;
}
}
return offHeap;
}
@Override
public Object getHydratedCacheElementItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName) {
Element element;
String myKey = cacheRegion + '_' + cacheName + '_' + elementItemName + '_' + elementKey;
if (removeKeys.contains(myKey)) {
return null;
}
Object response = null;
element = getHeap().get(myKey);
if (element != null) {
response = element.getObjectValue();
}
return response;
}
@Override
public void addHydratedCacheElementItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName, Object elementValue) {
String heapKey = cacheRegion + '_' + cacheName + '_' + elementItemName + '_' + elementKey;
String nameKey = cacheRegion + '_' + cacheName + '_' + elementKey;
removeKeys.remove(nameKey);
Element element = new Element(heapKey, elementValue);
if (!cacheMemberNamesByEntity.containsKey(nameKey)) {
List<String> myMembers = new ArrayList<String>(50);
myMembers.add(elementItemName);
cacheMemberNamesByEntity.put(nameKey, myMembers);
} else {
List<String> myMembers = cacheMemberNamesByEntity.get(nameKey);
myMembers.add(elementItemName);
}
getHeap().put(element);
}
protected void removeCache(String cacheRegion, Serializable key) {
String cacheName = cacheRegion;
if (key instanceof CacheKey) {
cacheName = ((CacheKey) key).getEntityOrRoleName();
key = ((CacheKey) key).getKey();
}
String nameKey = cacheRegion + '_' + cacheName + '_' + key;
if (cacheMemberNamesByEntity.containsKey(nameKey)) {
String[] members = new String[cacheMemberNamesByEntity.get(nameKey).size()];
members = cacheMemberNamesByEntity.get(nameKey).toArray(members);
for (String myMember : members) {
String itemKey = cacheRegion + '_' + myMember + '_' + key;
removeKeys.add(itemKey);
}
cacheMemberNamesByEntity.remove(nameKey);
}
}
protected void removeAll(String cacheName) {
//do nothing
}
@Override
public void notifyElementEvicted(Ehcache arg0, Element arg1) {
removeCache(arg0.getName(), arg1.getKey());
}
@Override
public void notifyElementExpired(Ehcache arg0, Element arg1) {
removeCache(arg0.getName(), arg1.getKey());
}
@Override
public void notifyElementPut(Ehcache arg0, Element arg1) throws CacheException {
//do nothing
}
@Override
public void notifyElementRemoved(Ehcache arg0, Element arg1) throws CacheException {
removeCache(arg0.getName(), arg1.getKey());
}
@Override
public void notifyElementUpdated(Ehcache arg0, Element arg1) throws CacheException {
removeCache(arg0.getName(), arg1.getKey());
}
@Override
public void notifyRemoveAll(Ehcache arg0) {
removeAll(arg0.getName());
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_cache_engine_BigMemoryHydratedCacheManagerImpl.java
|
48 |
public class VersionCommandProcessor extends MemcacheCommandProcessor<VersionCommand> {
public VersionCommandProcessor(TextCommandServiceImpl textCommandService) {
super(textCommandService);
}
public void handle(VersionCommand request) {
textCommandService.sendResponse(request);
}
public void handleRejection(VersionCommand request) {
handle(request);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_ascii_memcache_VersionCommandProcessor.java
|
321 |
public class TransportNodesHotThreadsAction extends TransportNodesOperationAction<NodesHotThreadsRequest, NodesHotThreadsResponse, TransportNodesHotThreadsAction.NodeRequest, NodeHotThreads> {
@Inject
public TransportNodesHotThreadsAction(Settings settings, ClusterName clusterName, ThreadPool threadPool,
ClusterService clusterService, TransportService transportService) {
super(settings, clusterName, threadPool, clusterService, transportService);
}
@Override
protected String executor() {
return ThreadPool.Names.GENERIC;
}
@Override
protected String transportAction() {
return NodesHotThreadsAction.NAME;
}
@Override
protected NodesHotThreadsResponse newResponse(NodesHotThreadsRequest request, AtomicReferenceArray responses) {
final List<NodeHotThreads> nodes = Lists.newArrayList();
for (int i = 0; i < responses.length(); i++) {
Object resp = responses.get(i);
if (resp instanceof NodeHotThreads) {
nodes.add((NodeHotThreads) resp);
}
}
return new NodesHotThreadsResponse(clusterName, nodes.toArray(new NodeHotThreads[nodes.size()]));
}
@Override
protected NodesHotThreadsRequest newRequest() {
return new NodesHotThreadsRequest();
}
@Override
protected NodeRequest newNodeRequest() {
return new NodeRequest();
}
@Override
protected NodeRequest newNodeRequest(String nodeId, NodesHotThreadsRequest request) {
return new NodeRequest(nodeId, request);
}
@Override
protected NodeHotThreads newNodeResponse() {
return new NodeHotThreads();
}
@Override
protected NodeHotThreads nodeOperation(NodeRequest request) throws ElasticsearchException {
HotThreads hotThreads = new HotThreads()
.busiestThreads(request.request.threads)
.type(request.request.type)
.interval(request.request.interval)
.threadElementsSnapshotCount(request.request.snapshots);
try {
return new NodeHotThreads(clusterService.localNode(), hotThreads.detect());
} catch (Exception e) {
throw new ElasticsearchException("failed to detect hot threads", e);
}
}
@Override
protected boolean accumulateExceptions() {
return false;
}
static class NodeRequest extends NodeOperationRequest {
NodesHotThreadsRequest request;
NodeRequest() {
}
NodeRequest(String nodeId, NodesHotThreadsRequest request) {
super(request, nodeId);
this.request = request;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
request = new NodesHotThreadsRequest();
request.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
request.writeTo(out);
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_hotthreads_TransportNodesHotThreadsAction.java
|
912 |
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
ActionListener<T> lst = (ActionListener<T>) listener;
try {
lst.onResponse(actionGet());
} catch (ElasticsearchException e) {
lst.onFailure(e);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_support_AbstractListenableActionFuture.java
|
530 |
public class FormatUtil {
public static final String DATE_FORMAT = "yyyy.MM.dd HH:mm:ss";
public static final String DATE_FORMAT_WITH_TIMEZONE = "yyyy.MM.dd HH:mm:ss Z";
public static SimpleDateFormat getDateFormat() {
SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
formatter.setTimeZone(BroadleafRequestContext.getBroadleafRequestContext().getTimeZone());
return formatter;
}
/**
* Used with dates in rules since they are not stored as a Timestamp type (and thus not converted to a specific database
* timezone on a save). In order to provide accurate information, the timezone must also be preserved in the MVEL rule
* expression
*
* @return
*/
public static SimpleDateFormat getTimeZoneFormat() {
SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT_WITH_TIMEZONE);
formatter.setTimeZone(BroadleafRequestContext.getBroadleafRequestContext().getTimeZone());
return formatter;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_util_FormatUtil.java
|
1 |
private static final class AndroidCeylonBuildHook extends CeylonBuildHook {
public static final String CEYLON_GENERATED_ARCHIVES_PREFIX = "ceylonGenerated-";
public static final String CEYLON_GENERATED_CLASSES_ARCHIVE = CEYLON_GENERATED_ARCHIVES_PREFIX + "CeylonClasses.jar";
public static final String ANDROID_LIBS_DIRECTORY = "libs";
public static final String[] ANDROID_PROVIDED_PACKAGES = new String[] {"android.app"};
public static final String[] UNNECESSARY_CEYLON_RUNTIME_LIBRARIES = new String[] {"org.jboss.modules",
"com.redhat.ceylon.module-resolver",
"com.redhat.ceylon.common"};
boolean areModulesChanged = false;
boolean hasAndroidNature = false;
boolean isReentrantBuild = false;
boolean isFullBuild = false;
WeakReference<IProgressMonitor> monitorRef = null;
WeakReference<IProject> projectRef = null;
private IProgressMonitor getMonitor() {
if (monitorRef != null) {
return monitorRef.get();
}
return null;
}
private IProject getProject() {
if (projectRef != null) {
return projectRef.get();
}
return null;
}
@Override
protected void startBuild(int kind, @SuppressWarnings("rawtypes") Map args,
IProject project, IBuildConfiguration config, IBuildContext context, IProgressMonitor monitor) throws CoreException {
try {
hasAndroidNature = project.hasNature("com.android.ide.eclipse.adt.AndroidNature");
} catch (CoreException e) {
hasAndroidNature= false;
}
areModulesChanged = false;
monitorRef = new WeakReference<IProgressMonitor>(monitor);
projectRef = new WeakReference<IProject>(project);
isReentrantBuild = args.containsKey(CeylonBuilder.BUILDER_ID + ".reentrant");
if (hasAndroidNature) {
IJavaProject javaProject =JavaCore.create(project);
boolean CeylonCPCFound = false;
IMarker[] buildMarkers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_ZERO);
for (IMarker m: buildMarkers) {
if (CeylonAndroidPlugin.PLUGIN_ID.equals(m.getAttribute(IMarker.SOURCE_ID))) {
m.delete();
}
}
for (IClasspathEntry entry : javaProject.getRawClasspath()) {
if (CeylonClasspathUtil.isProjectModulesClasspathContainer(entry.getPath())) {
CeylonCPCFound = true;
} else {
IPath containerPath = entry.getPath();
int size = containerPath.segmentCount();
if (size > 0) {
if (containerPath.segment(0).equals("com.android.ide.eclipse.adt.LIBRARIES") ||
containerPath.segment(0).equals("com.android.ide.eclipse.adt.DEPENDENCIES")) {
if (! CeylonCPCFound) {
//if the ClassPathContainer is missing, add an error
IMarker marker = project.createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER);
marker.setAttribute(IMarker.SOURCE_ID, CeylonAndroidPlugin.PLUGIN_ID);
marker.setAttribute(IMarker.MESSAGE, "Invalid Java Build Path for project " + project.getName() + " : " +
"The Ceylon libraries should be set before the Android libraries in the Java Build Path. " +
"Move down the 'Android Private Libraries' and 'Android Dependencies' after the Ceylon Libraries " +
"in the 'Order and Export' tab of the 'Java Build Path' properties page.");
marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
marker.setAttribute(IMarker.LOCATION, "Java Build Path Order");
throw new CoreException(new Status(IStatus.CANCEL, CeylonAndroidPlugin.PLUGIN_ID, IResourceStatus.OK,
"Build cancelled because of invalid build path", null));
}
}
}
}
}
}
}
@Override
protected void deltasAnalyzed(List<IResourceDelta> currentDeltas,
BooleanHolder sourceModified,
BooleanHolder mustDoFullBuild,
BooleanHolder mustResolveClasspathContainer,
boolean mustContinueBuild) {
if (mustContinueBuild && hasAndroidNature) {
CeylonBuilder.waitForUpToDateJavaModel(10000, getProject(), getMonitor());
}
}
@Override
protected void setAndRefreshClasspathContainer() {
areModulesChanged = true;
}
@Override
protected void doFullBuild() {
isFullBuild = true;
}
@Override
protected void afterGeneratingBinaries() {
IProject project = getProject();
if (project == null) {
return;
}
if (! isReentrantBuild && hasAndroidNature) {
try {
File libsDirectory = project.findMember(ANDROID_LIBS_DIRECTORY).getLocation().toFile();
if (!libsDirectory.exists()) {
libsDirectory.mkdirs();
}
Files.walkFileTree(java.nio.file.FileSystems.getDefault().getPath(libsDirectory.getAbsolutePath()), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException
{
if (areModulesChanged || isFullBuild ?
path.getFileName().toString().startsWith(CEYLON_GENERATED_ARCHIVES_PREFIX) :
path.getFileName().toString().equals(CEYLON_GENERATED_CLASSES_ARCHIVE)) {
try {
Files.delete(path);
} catch(IOException ioe) {
CeylonAndroidPlugin.logError("Could not delete a ceylon jar from the android libs directory", ioe);
}
}
return FileVisitResult.CONTINUE;
}
});
final List<IFile> filesToAddInArchive = new LinkedList<>();
final IFolder ceylonOutputFolder = CeylonBuilder.getCeylonClassesOutputFolder(project);
ceylonOutputFolder.refreshLocal(DEPTH_INFINITE, getMonitor());
ceylonOutputFolder.accept(new IResourceVisitor() {
@Override
public boolean visit(IResource resource) throws CoreException {
if (resource instanceof IFile) {
filesToAddInArchive.add((IFile)resource);
}
return true;
}
});
if (! filesToAddInArchive.isEmpty()) {
JarPackageData jarPkgData = new JarPackageData();
jarPkgData.setBuildIfNeeded(false);
jarPkgData.setOverwrite(true);
jarPkgData.setGenerateManifest(true);
jarPkgData.setExportClassFiles(true);
jarPkgData.setCompress(true);
jarPkgData.setJarLocation(project.findMember("libs").getLocation().append(CEYLON_GENERATED_CLASSES_ARCHIVE).makeAbsolute());
jarPkgData.setElements(filesToAddInArchive.toArray());
JarWriter3 jarWriter = null;
try {
jarWriter = new JarWriter3(jarPkgData, null);
for (IFile fileToAdd : filesToAddInArchive) {
jarWriter.write(fileToAdd, fileToAdd.getFullPath().makeRelativeTo(ceylonOutputFolder.getFullPath()));
}
} finally {
if (jarWriter != null) {
jarWriter.close();
}
}
}
if (isFullBuild || areModulesChanged) {
List<Path> jarsToCopyToLib = new LinkedList<>();
IJavaProject javaProject = JavaCore.create(project);
List<IClasspathContainer> cpContainers = CeylonClasspathUtil.getCeylonClasspathContainers(javaProject);
if (cpContainers != null) {
for (IClasspathContainer cpc : cpContainers) {
for (IClasspathEntry cpe : cpc.getClasspathEntries()) {
if (cpe.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
Path path = FileSystems.getDefault().getPath(cpe.getPath().toOSString());
if (! Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS) &&
Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
boolean isAndroidProvidedJar = false;
providerPackageFound:
for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
if (javaProject.isOnClasspath(root) &&
cpe.equals(root.getResolvedClasspathEntry())) {
for (String providedPackage : ANDROID_PROVIDED_PACKAGES) {
if (root.getPackageFragment(providedPackage).exists()) {
isAndroidProvidedJar = true;
break providerPackageFound;
}
}
}
}
if (! isAndroidProvidedJar) {
jarsToCopyToLib.add(path);
}
}
}
}
}
}
for (String runtimeJar : CeylonPlugin.getRuntimeRequiredJars()) {
boolean isNecessary = true;
for (String unnecessaryRuntime : UNNECESSARY_CEYLON_RUNTIME_LIBRARIES) {
if (runtimeJar.contains(unnecessaryRuntime + "-")) {
isNecessary = false;
break;
}
}
if (isNecessary) {
jarsToCopyToLib.add(FileSystems.getDefault().getPath(runtimeJar));
}
}
for (Path archive : jarsToCopyToLib) {
String newName = CEYLON_GENERATED_ARCHIVES_PREFIX + archive.getFileName();
if (newName.endsWith(ArtifactContext.CAR)) {
newName = newName.replaceFirst("\\.car$", "\\.jar");
}
Path destinationPath = FileSystems.getDefault().getPath(project.findMember(ANDROID_LIBS_DIRECTORY).getLocation().toOSString(), newName);
try {
Files.copy(archive, destinationPath);
} catch (IOException e) {
CeylonAndroidPlugin.logError("Could not copy a ceylon jar to the android libs directory", e);
}
}
}
project.findMember(ANDROID_LIBS_DIRECTORY).refreshLocal(DEPTH_INFINITE, getMonitor());
} catch (Exception e) {
CeylonAndroidPlugin.logError("Error during the generation of ceylon-derived archives for Android", e);
}
}
}
@Override
protected void endBuild() {
areModulesChanged = false;
hasAndroidNature = false;
isReentrantBuild = false;
isFullBuild = false;
monitorRef = null;
projectRef = null;
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.android.plugin_src_com_redhat_ceylon_eclipse_android_plugin_AndroidBuildHookProvider.java
|
6,436 |
public class NettyTransport extends AbstractLifecycleComponent<Transport> implements Transport {
static {
NettyStaticSetup.setup();
}
private final NetworkService networkService;
final Version version;
final int workerCount;
final int bossCount;
final boolean blockingServer;
final boolean blockingClient;
final String port;
final String bindHost;
final String publishHost;
final int publishPort;
final boolean compress;
final TimeValue connectTimeout;
final Boolean tcpNoDelay;
final Boolean tcpKeepAlive;
final Boolean reuseAddress;
final ByteSizeValue tcpSendBufferSize;
final ByteSizeValue tcpReceiveBufferSize;
final ReceiveBufferSizePredictorFactory receiveBufferSizePredictorFactory;
final int connectionsPerNodeRecovery;
final int connectionsPerNodeBulk;
final int connectionsPerNodeReg;
final int connectionsPerNodeState;
final int connectionsPerNodePing;
final ByteSizeValue maxCumulationBufferCapacity;
final int maxCompositeBufferComponents;
private final ThreadPool threadPool;
private volatile OpenChannelsHandler serverOpenChannels;
private volatile ClientBootstrap clientBootstrap;
private volatile ServerBootstrap serverBootstrap;
// node id to actual channel
final ConcurrentMap<DiscoveryNode, NodeChannels> connectedNodes = newConcurrentMap();
private volatile Channel serverChannel;
private volatile TransportServiceAdapter transportServiceAdapter;
private volatile BoundTransportAddress boundAddress;
private final KeyedLock<String> connectionLock = new KeyedLock<String>();
// this lock is here to make sure we close this transport and disconnect all the client nodes
// connections while no connect operations is going on... (this might help with 100% CPU when stopping the transport?)
private final ReadWriteLock globalLock = new ReentrantReadWriteLock();
@Inject
public NettyTransport(Settings settings, ThreadPool threadPool, NetworkService networkService, Version version) {
super(settings);
this.threadPool = threadPool;
this.networkService = networkService;
this.version = version;
if (settings.getAsBoolean("netty.epollBugWorkaround", false)) {
System.setProperty("org.jboss.netty.epollBugWorkaround", "true");
}
this.workerCount = componentSettings.getAsInt("worker_count", EsExecutors.boundedNumberOfProcessors(settings) * 2);
this.bossCount = componentSettings.getAsInt("boss_count", 1);
this.blockingServer = settings.getAsBoolean("transport.tcp.blocking_server", settings.getAsBoolean(TCP_BLOCKING_SERVER, settings.getAsBoolean(TCP_BLOCKING, false)));
this.blockingClient = settings.getAsBoolean("transport.tcp.blocking_client", settings.getAsBoolean(TCP_BLOCKING_CLIENT, settings.getAsBoolean(TCP_BLOCKING, false)));
this.port = componentSettings.get("port", settings.get("transport.tcp.port", "9300-9400"));
this.bindHost = componentSettings.get("bind_host", settings.get("transport.bind_host", settings.get("transport.host")));
this.publishHost = componentSettings.get("publish_host", settings.get("transport.publish_host", settings.get("transport.host")));
this.publishPort = componentSettings.getAsInt("publish_port", settings.getAsInt("transport.publish_port", 0));
this.compress = settings.getAsBoolean(TransportSettings.TRANSPORT_TCP_COMPRESS, false);
this.connectTimeout = componentSettings.getAsTime("connect_timeout", settings.getAsTime("transport.tcp.connect_timeout", settings.getAsTime(TCP_CONNECT_TIMEOUT, TCP_DEFAULT_CONNECT_TIMEOUT)));
this.tcpNoDelay = componentSettings.getAsBoolean("tcp_no_delay", settings.getAsBoolean(TCP_NO_DELAY, true));
this.tcpKeepAlive = componentSettings.getAsBoolean("tcp_keep_alive", settings.getAsBoolean(TCP_KEEP_ALIVE, true));
this.reuseAddress = componentSettings.getAsBoolean("reuse_address", settings.getAsBoolean(TCP_REUSE_ADDRESS, NetworkUtils.defaultReuseAddress()));
this.tcpSendBufferSize = componentSettings.getAsBytesSize("tcp_send_buffer_size", settings.getAsBytesSize(TCP_SEND_BUFFER_SIZE, TCP_DEFAULT_SEND_BUFFER_SIZE));
this.tcpReceiveBufferSize = componentSettings.getAsBytesSize("tcp_receive_buffer_size", settings.getAsBytesSize(TCP_RECEIVE_BUFFER_SIZE, TCP_DEFAULT_RECEIVE_BUFFER_SIZE));
this.connectionsPerNodeRecovery = componentSettings.getAsInt("connections_per_node.recovery", settings.getAsInt("transport.connections_per_node.recovery", 2));
this.connectionsPerNodeBulk = componentSettings.getAsInt("connections_per_node.bulk", settings.getAsInt("transport.connections_per_node.bulk", 3));
this.connectionsPerNodeReg = componentSettings.getAsInt("connections_per_node.reg", settings.getAsInt("transport.connections_per_node.reg", 6));
this.connectionsPerNodeState = componentSettings.getAsInt("connections_per_node.high", settings.getAsInt("transport.connections_per_node.state", 1));
this.connectionsPerNodePing = componentSettings.getAsInt("connections_per_node.ping", settings.getAsInt("transport.connections_per_node.ping", 1));
// we want to have at least 1 for reg/state/ping
if (this.connectionsPerNodeReg == 0) {
throw new ElasticsearchIllegalArgumentException("can't set [connection_per_node.reg] to 0");
}
if (this.connectionsPerNodePing == 0) {
throw new ElasticsearchIllegalArgumentException("can't set [connection_per_node.ping] to 0");
}
if (this.connectionsPerNodeState == 0) {
throw new ElasticsearchIllegalArgumentException("can't set [connection_per_node.state] to 0");
}
this.maxCumulationBufferCapacity = componentSettings.getAsBytesSize("max_cumulation_buffer_capacity", null);
this.maxCompositeBufferComponents = componentSettings.getAsInt("max_composite_buffer_components", -1);
long defaultReceiverPredictor = 512 * 1024;
if (JvmInfo.jvmInfo().mem().directMemoryMax().bytes() > 0) {
// we can guess a better default...
long l = (long) ((0.3 * JvmInfo.jvmInfo().mem().directMemoryMax().bytes()) / workerCount);
defaultReceiverPredictor = Math.min(defaultReceiverPredictor, Math.max(l, 64 * 1024));
}
// See AdaptiveReceiveBufferSizePredictor#DEFAULT_XXX for default values in netty..., we can use higher ones for us, even fixed one
ByteSizeValue receivePredictorMin = componentSettings.getAsBytesSize("receive_predictor_min", componentSettings.getAsBytesSize("receive_predictor_size", new ByteSizeValue(defaultReceiverPredictor)));
ByteSizeValue receivePredictorMax = componentSettings.getAsBytesSize("receive_predictor_max", componentSettings.getAsBytesSize("receive_predictor_size", new ByteSizeValue(defaultReceiverPredictor)));
if (receivePredictorMax.bytes() == receivePredictorMin.bytes()) {
receiveBufferSizePredictorFactory = new FixedReceiveBufferSizePredictorFactory((int) receivePredictorMax.bytes());
} else {
receiveBufferSizePredictorFactory = new AdaptiveReceiveBufferSizePredictorFactory((int) receivePredictorMin.bytes(), (int) receivePredictorMin.bytes(), (int) receivePredictorMax.bytes());
}
logger.debug("using worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], connect_timeout[{}], connections_per_node[{}/{}/{}/{}/{}], receive_predictor[{}->{}]",
workerCount, port, bindHost, publishHost, compress, connectTimeout, connectionsPerNodeRecovery, connectionsPerNodeBulk, connectionsPerNodeReg, connectionsPerNodeState, connectionsPerNodePing, receivePredictorMin, receivePredictorMax);
}
public Settings settings() {
return this.settings;
}
@Override
public void transportServiceAdapter(TransportServiceAdapter service) {
this.transportServiceAdapter = service;
}
TransportServiceAdapter transportServiceAdapter() {
return transportServiceAdapter;
}
ThreadPool threadPool() {
return threadPool;
}
@Override
protected void doStart() throws ElasticsearchException {
if (blockingClient) {
clientBootstrap = new ClientBootstrap(new OioClientSocketChannelFactory(Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_client_worker"))));
} else {
clientBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_client_boss")),
bossCount,
new NioWorkerPool(Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_client_worker")), workerCount),
new HashedWheelTimer(daemonThreadFactory(settings, "transport_client_timer"))));
}
ChannelPipelineFactory clientPipelineFactory = new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
SizeHeaderFrameDecoder sizeHeader = new SizeHeaderFrameDecoder();
if (maxCumulationBufferCapacity != null) {
if (maxCumulationBufferCapacity.bytes() > Integer.MAX_VALUE) {
sizeHeader.setMaxCumulationBufferCapacity(Integer.MAX_VALUE);
} else {
sizeHeader.setMaxCumulationBufferCapacity((int) maxCumulationBufferCapacity.bytes());
}
}
if (maxCompositeBufferComponents != -1) {
sizeHeader.setMaxCumulationBufferComponents(maxCompositeBufferComponents);
}
pipeline.addLast("size", sizeHeader);
pipeline.addLast("dispatcher", new MessageChannelHandler(NettyTransport.this, logger));
return pipeline;
}
};
clientBootstrap.setPipelineFactory(clientPipelineFactory);
clientBootstrap.setOption("connectTimeoutMillis", connectTimeout.millis());
if (tcpNoDelay != null) {
clientBootstrap.setOption("tcpNoDelay", tcpNoDelay);
}
if (tcpKeepAlive != null) {
clientBootstrap.setOption("keepAlive", tcpKeepAlive);
}
if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) {
clientBootstrap.setOption("sendBufferSize", tcpSendBufferSize.bytes());
}
if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) {
clientBootstrap.setOption("receiveBufferSize", tcpReceiveBufferSize.bytes());
}
clientBootstrap.setOption("receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory);
if (reuseAddress != null) {
clientBootstrap.setOption("reuseAddress", reuseAddress);
}
if (!settings.getAsBoolean("network.server", true)) {
return;
}
serverOpenChannels = new OpenChannelsHandler(logger);
if (blockingServer) {
serverBootstrap = new ServerBootstrap(new OioServerSocketChannelFactory(
Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_boss")),
Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_worker"))
));
} else {
serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_boss")),
Executors.newCachedThreadPool(daemonThreadFactory(settings, "transport_server_worker")),
workerCount));
}
ChannelPipelineFactory serverPipelineFactory = new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("openChannels", serverOpenChannels);
SizeHeaderFrameDecoder sizeHeader = new SizeHeaderFrameDecoder();
if (maxCumulationBufferCapacity != null) {
if (maxCumulationBufferCapacity.bytes() > Integer.MAX_VALUE) {
sizeHeader.setMaxCumulationBufferCapacity(Integer.MAX_VALUE);
} else {
sizeHeader.setMaxCumulationBufferCapacity((int) maxCumulationBufferCapacity.bytes());
}
}
if (maxCompositeBufferComponents != -1) {
sizeHeader.setMaxCumulationBufferComponents(maxCompositeBufferComponents);
}
pipeline.addLast("size", sizeHeader);
pipeline.addLast("dispatcher", new MessageChannelHandler(NettyTransport.this, logger));
return pipeline;
}
};
serverBootstrap.setPipelineFactory(serverPipelineFactory);
if (tcpNoDelay != null) {
serverBootstrap.setOption("child.tcpNoDelay", tcpNoDelay);
}
if (tcpKeepAlive != null) {
serverBootstrap.setOption("child.keepAlive", tcpKeepAlive);
}
if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) {
serverBootstrap.setOption("child.sendBufferSize", tcpSendBufferSize.bytes());
}
if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) {
serverBootstrap.setOption("child.receiveBufferSize", tcpReceiveBufferSize.bytes());
}
serverBootstrap.setOption("receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory);
serverBootstrap.setOption("child.receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory);
if (reuseAddress != null) {
serverBootstrap.setOption("reuseAddress", reuseAddress);
serverBootstrap.setOption("child.reuseAddress", reuseAddress);
}
// Bind and start to accept incoming connections.
InetAddress hostAddressX;
try {
hostAddressX = networkService.resolveBindHostAddress(bindHost);
} catch (IOException e) {
throw new BindTransportException("Failed to resolve host [" + bindHost + "]", e);
}
final InetAddress hostAddress = hostAddressX;
PortsRange portsRange = new PortsRange(port);
final AtomicReference<Exception> lastException = new AtomicReference<Exception>();
boolean success = portsRange.iterate(new PortsRange.PortCallback() {
@Override
public boolean onPortNumber(int portNumber) {
try {
serverChannel = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber));
} catch (Exception e) {
lastException.set(e);
return false;
}
return true;
}
});
if (!success) {
throw new BindTransportException("Failed to bind to [" + port + "]", lastException.get());
}
logger.debug("Bound to address [{}]", serverChannel.getLocalAddress());
InetSocketAddress boundAddress = (InetSocketAddress) serverChannel.getLocalAddress();
InetSocketAddress publishAddress;
int publishPort = this.publishPort;
if (0 == publishPort) {
publishPort = boundAddress.getPort();
}
try {
publishAddress = new InetSocketAddress(networkService.resolvePublishHostAddress(publishHost), publishPort);
} catch (Exception e) {
throw new BindTransportException("Failed to resolve publish address", e);
}
this.boundAddress = new BoundTransportAddress(new InetSocketTransportAddress(boundAddress), new InetSocketTransportAddress(publishAddress));
}
@Override
protected void doStop() throws ElasticsearchException {
final CountDownLatch latch = new CountDownLatch(1);
// make sure we run it on another thread than a possible IO handler thread
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
globalLock.writeLock().lock();
try {
for (Iterator<NodeChannels> it = connectedNodes.values().iterator(); it.hasNext(); ) {
NodeChannels nodeChannels = it.next();
it.remove();
nodeChannels.close();
}
if (serverChannel != null) {
try {
serverChannel.close().awaitUninterruptibly();
} finally {
serverChannel = null;
}
}
if (serverOpenChannels != null) {
serverOpenChannels.close();
serverOpenChannels = null;
}
if (serverBootstrap != null) {
serverBootstrap.releaseExternalResources();
serverBootstrap = null;
}
for (Iterator<NodeChannels> it = connectedNodes.values().iterator(); it.hasNext(); ) {
NodeChannels nodeChannels = it.next();
it.remove();
nodeChannels.close();
}
if (clientBootstrap != null) {
clientBootstrap.releaseExternalResources();
clientBootstrap = null;
}
} finally {
globalLock.writeLock().unlock();
latch.countDown();
}
}
});
try {
latch.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// ignore
}
}
@Override
protected void doClose() throws ElasticsearchException {
}
@Override
public TransportAddress[] addressesFromString(String address) throws Exception {
int index = address.indexOf('[');
if (index != -1) {
String host = address.substring(0, index);
Set<String> ports = Strings.commaDelimitedListToSet(address.substring(index + 1, address.indexOf(']')));
List<TransportAddress> addresses = Lists.newArrayList();
for (String port : ports) {
int[] iPorts = new PortsRange(port).ports();
for (int iPort : iPorts) {
addresses.add(new InetSocketTransportAddress(host, iPort));
}
}
return addresses.toArray(new TransportAddress[addresses.size()]);
} else {
index = address.lastIndexOf(':');
if (index == -1) {
List<TransportAddress> addresses = Lists.newArrayList();
int[] iPorts = new PortsRange(this.port).ports();
for (int iPort : iPorts) {
addresses.add(new InetSocketTransportAddress(address, iPort));
}
return addresses.toArray(new TransportAddress[addresses.size()]);
} else {
String host = address.substring(0, index);
int port = Integer.parseInt(address.substring(index + 1));
return new TransportAddress[]{new InetSocketTransportAddress(host, port)};
}
}
}
@Override
public boolean addressSupported(Class<? extends TransportAddress> address) {
return InetSocketTransportAddress.class.equals(address);
}
@Override
public BoundTransportAddress boundAddress() {
return this.boundAddress;
}
void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
if (!lifecycle.started()) {
// ignore
}
if (isCloseConnectionException(e.getCause())) {
logger.trace("close connection exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel());
// close the channel, which will cause a node to be disconnected if relevant
ctx.getChannel().close();
disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
} else if (isConnectException(e.getCause())) {
logger.trace("connect exception caught on transport layer [{}]", e.getCause(), ctx.getChannel());
// close the channel as safe measure, which will cause a node to be disconnected if relevant
ctx.getChannel().close();
disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
} else if (e.getCause() instanceof CancelledKeyException) {
logger.trace("cancelled key exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel());
// close the channel as safe measure, which will cause a node to be disconnected if relevant
ctx.getChannel().close();
disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
} else {
logger.warn("exception caught on transport layer [{}], closing connection", e.getCause(), ctx.getChannel());
// close the channel, which will cause a node to be disconnected if relevant
ctx.getChannel().close();
disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
}
}
TransportAddress wrapAddress(SocketAddress socketAddress) {
return new InetSocketTransportAddress((InetSocketAddress) socketAddress);
}
@Override
public long serverOpen() {
OpenChannelsHandler channels = serverOpenChannels;
return channels == null ? 0 : channels.numberOfOpenChannels();
}
@Override
public void sendRequest(final DiscoveryNode node, final long requestId, final String action, final TransportRequest request, TransportRequestOptions options) throws IOException, TransportException {
Channel targetChannel = nodeChannel(node, options);
if (compress) {
options.withCompress(true);
}
byte status = 0;
status = TransportStatus.setRequest(status);
BytesStreamOutput bStream = new BytesStreamOutput();
bStream.skip(NettyHeader.HEADER_SIZE);
StreamOutput stream = bStream;
// only compress if asked, and, the request is not bytes, since then only
// the header part is compressed, and the "body" can't be extracted as compressed
if (options.compress() && (!(request instanceof BytesTransportRequest))) {
status = TransportStatus.setCompress(status);
stream = CompressorFactory.defaultCompressor().streamOutput(stream);
}
stream = new HandlesStreamOutput(stream);
// we pick the smallest of the 2, to support both backward and forward compatibility
// note, this is the only place we need to do this, since from here on, we use the serialized version
// as the version to use also when the node receiving this request will send the response with
Version version = Version.smallest(this.version, node.version());
stream.setVersion(version);
stream.writeString(action);
ChannelBuffer buffer;
// it might be nice to somehow generalize this optimization, maybe a smart "paged" bytes output
// that create paged channel buffers, but its tricky to know when to do it (where this option is
// more explicit).
if (request instanceof BytesTransportRequest) {
BytesTransportRequest bRequest = (BytesTransportRequest) request;
assert node.version().equals(bRequest.version());
bRequest.writeThin(stream);
stream.close();
ChannelBuffer headerBuffer = bStream.bytes().toChannelBuffer();
ChannelBuffer contentBuffer = bRequest.bytes().toChannelBuffer();
// false on gathering, cause gathering causes the NIO layer to combine the buffers into a single direct buffer....
buffer = new CompositeChannelBuffer(headerBuffer.order(), ImmutableList.<ChannelBuffer>of(headerBuffer, contentBuffer), false);
} else {
request.writeTo(stream);
stream.close();
buffer = bStream.bytes().toChannelBuffer();
}
NettyHeader.writeHeader(buffer, requestId, status, version);
targetChannel.write(buffer);
// We handle close connection exception in the #exceptionCaught method, which is the main reason we want to add this future
// channelFuture.addListener(new ChannelFutureListener() {
// @Override public void operationComplete(ChannelFuture future) throws Exception {
// if (!future.isSuccess()) {
// // maybe add back the retry?
// TransportResponseHandler handler = transportServiceAdapter.remove(requestId);
// if (handler != null) {
// handler.handleException(new RemoteTransportException("Failed write request", new SendRequestTransportException(node, action, future.getCause())));
// }
// }
// }
// });
}
@Override
public boolean nodeConnected(DiscoveryNode node) {
return connectedNodes.containsKey(node);
}
@Override
public void connectToNodeLight(DiscoveryNode node) throws ConnectTransportException {
connectToNode(node, true);
}
@Override
public void connectToNode(DiscoveryNode node) {
connectToNode(node, false);
}
public void connectToNode(DiscoveryNode node, boolean light) {
if (!lifecycle.started()) {
throw new ElasticsearchIllegalStateException("can't add nodes to a stopped transport");
}
if (node == null) {
throw new ConnectTransportException(null, "can't connect to a null node");
}
globalLock.readLock().lock();
try {
if (!lifecycle.started()) {
throw new ElasticsearchIllegalStateException("can't add nodes to a stopped transport");
}
NodeChannels nodeChannels = connectedNodes.get(node);
if (nodeChannels != null) {
return;
}
connectionLock.acquire(node.id());
try {
if (!lifecycle.started()) {
throw new ElasticsearchIllegalStateException("can't add nodes to a stopped transport");
}
try {
if (light) {
nodeChannels = connectToChannelsLight(node);
} else {
nodeChannels = new NodeChannels(new Channel[connectionsPerNodeRecovery], new Channel[connectionsPerNodeBulk], new Channel[connectionsPerNodeReg], new Channel[connectionsPerNodeState], new Channel[connectionsPerNodePing]);
try {
connectToChannels(nodeChannels, node);
} catch (Exception e) {
nodeChannels.close();
throw e;
}
}
NodeChannels existing = connectedNodes.putIfAbsent(node, nodeChannels);
if (existing != null) {
// we are already connected to a node, close this ones
nodeChannels.close();
} else {
if (logger.isDebugEnabled()) {
logger.debug("connected to node [{}]", node);
}
transportServiceAdapter.raiseNodeConnected(node);
}
} catch (ConnectTransportException e) {
throw e;
} catch (Exception e) {
throw new ConnectTransportException(node, "General node connection failure", e);
}
} finally {
connectionLock.release(node.id());
}
} finally {
globalLock.readLock().unlock();
}
}
private NodeChannels connectToChannelsLight(DiscoveryNode node) {
InetSocketAddress address = ((InetSocketTransportAddress) node.address()).address();
ChannelFuture connect = clientBootstrap.connect(address);
connect.awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
if (!connect.isSuccess()) {
throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connect.getCause());
}
Channel[] channels = new Channel[1];
channels[0] = connect.getChannel();
channels[0].getCloseFuture().addListener(new ChannelCloseListener(node));
return new NodeChannels(channels, channels, channels, channels, channels);
}
private void connectToChannels(NodeChannels nodeChannels, DiscoveryNode node) {
ChannelFuture[] connectRecovery = new ChannelFuture[nodeChannels.recovery.length];
ChannelFuture[] connectBulk = new ChannelFuture[nodeChannels.bulk.length];
ChannelFuture[] connectReg = new ChannelFuture[nodeChannels.reg.length];
ChannelFuture[] connectState = new ChannelFuture[nodeChannels.state.length];
ChannelFuture[] connectPing = new ChannelFuture[nodeChannels.ping.length];
InetSocketAddress address = ((InetSocketTransportAddress) node.address()).address();
for (int i = 0; i < connectRecovery.length; i++) {
connectRecovery[i] = clientBootstrap.connect(address);
}
for (int i = 0; i < connectBulk.length; i++) {
connectBulk[i] = clientBootstrap.connect(address);
}
for (int i = 0; i < connectReg.length; i++) {
connectReg[i] = clientBootstrap.connect(address);
}
for (int i = 0; i < connectState.length; i++) {
connectState[i] = clientBootstrap.connect(address);
}
for (int i = 0; i < connectPing.length; i++) {
connectPing[i] = clientBootstrap.connect(address);
}
try {
for (int i = 0; i < connectRecovery.length; i++) {
connectRecovery[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
if (!connectRecovery[i].isSuccess()) {
throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectRecovery[i].getCause());
}
nodeChannels.recovery[i] = connectRecovery[i].getChannel();
nodeChannels.recovery[i].getCloseFuture().addListener(new ChannelCloseListener(node));
}
for (int i = 0; i < connectBulk.length; i++) {
connectBulk[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
if (!connectBulk[i].isSuccess()) {
throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectBulk[i].getCause());
}
nodeChannels.bulk[i] = connectBulk[i].getChannel();
nodeChannels.bulk[i].getCloseFuture().addListener(new ChannelCloseListener(node));
}
for (int i = 0; i < connectReg.length; i++) {
connectReg[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
if (!connectReg[i].isSuccess()) {
throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectReg[i].getCause());
}
nodeChannels.reg[i] = connectReg[i].getChannel();
nodeChannels.reg[i].getCloseFuture().addListener(new ChannelCloseListener(node));
}
for (int i = 0; i < connectState.length; i++) {
connectState[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
if (!connectState[i].isSuccess()) {
throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectState[i].getCause());
}
nodeChannels.state[i] = connectState[i].getChannel();
nodeChannels.state[i].getCloseFuture().addListener(new ChannelCloseListener(node));
}
for (int i = 0; i < connectPing.length; i++) {
connectPing[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
if (!connectPing[i].isSuccess()) {
throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectPing[i].getCause());
}
nodeChannels.ping[i] = connectPing[i].getChannel();
nodeChannels.ping[i].getCloseFuture().addListener(new ChannelCloseListener(node));
}
if (nodeChannels.recovery.length == 0) {
if (nodeChannels.bulk.length > 0) {
nodeChannels.recovery = nodeChannels.bulk;
} else {
nodeChannels.recovery = nodeChannels.reg;
}
}
if (nodeChannels.bulk.length == 0) {
nodeChannels.bulk = nodeChannels.reg;
}
} catch (RuntimeException e) {
// clean the futures
for (ChannelFuture future : ImmutableList.<ChannelFuture>builder().add(connectRecovery).add(connectBulk).add(connectReg).add(connectState).add(connectPing).build()) {
future.cancel();
if (future.getChannel() != null && future.getChannel().isOpen()) {
try {
future.getChannel().close();
} catch (Exception e1) {
// ignore
}
}
}
throw e;
}
}
@Override
public void disconnectFromNode(DiscoveryNode node) {
NodeChannels nodeChannels = connectedNodes.remove(node);
if (nodeChannels != null) {
connectionLock.acquire(node.id());
try {
try {
nodeChannels.close();
} finally {
logger.debug("disconnected from [{}]", node);
transportServiceAdapter.raiseNodeDisconnected(node);
}
} finally {
connectionLock.release(node.id());
}
}
}
/**
* Disconnects from a node, only if the relevant channel is found to be part of the node channels.
*/
private void disconnectFromNode(DiscoveryNode node, Channel channel, String reason) {
NodeChannels nodeChannels = connectedNodes.get(node);
if (nodeChannels != null && nodeChannels.hasChannel(channel)) {
connectionLock.acquire(node.id());
if (!nodeChannels.hasChannel(channel)) { //might have been removed in the meanwhile, safety check
assert !connectedNodes.containsKey(node);
} else {
try {
connectedNodes.remove(node);
try {
nodeChannels.close();
} finally {
logger.debug("disconnected from [{}], {}", node, reason);
transportServiceAdapter.raiseNodeDisconnected(node);
}
} finally {
connectionLock.release(node.id());
}
}
}
}
/**
* Disconnects from a node if a channel is found as part of that nodes channels.
*/
private void disconnectFromNodeChannel(Channel channel, Throwable failure) {
for (DiscoveryNode node : connectedNodes.keySet()) {
NodeChannels nodeChannels = connectedNodes.get(node);
if (nodeChannels != null && nodeChannels.hasChannel(channel)) {
connectionLock.acquire(node.id());
if (!nodeChannels.hasChannel(channel)) { //might have been removed in the meanwhile, safety check
assert !connectedNodes.containsKey(node);
} else {
try {
connectedNodes.remove(node);
try {
nodeChannels.close();
} finally {
logger.debug("disconnected from [{}] on channel failure", failure, node);
transportServiceAdapter.raiseNodeDisconnected(node);
}
} finally {
connectionLock.release(node.id());
}
}
}
}
}
private Channel nodeChannel(DiscoveryNode node, TransportRequestOptions options) throws ConnectTransportException {
NodeChannels nodeChannels = connectedNodes.get(node);
if (nodeChannels == null) {
throw new NodeNotConnectedException(node, "Node not connected");
}
return nodeChannels.channel(options.type());
}
private class ChannelCloseListener implements ChannelFutureListener {
private final DiscoveryNode node;
private ChannelCloseListener(DiscoveryNode node) {
this.node = node;
}
@Override
public void operationComplete(ChannelFuture future) throws Exception {
disconnectFromNode(node, future.getChannel(), "channel closed event");
}
}
public static class NodeChannels {
private Channel[] recovery;
private final AtomicInteger recoveryCounter = new AtomicInteger();
private Channel[] bulk;
private final AtomicInteger bulkCounter = new AtomicInteger();
private Channel[] reg;
private final AtomicInteger regCounter = new AtomicInteger();
private Channel[] state;
private final AtomicInteger stateCounter = new AtomicInteger();
private Channel[] ping;
private final AtomicInteger pingCounter = new AtomicInteger();
public NodeChannels(Channel[] recovery, Channel[] bulk, Channel[] reg, Channel[] state, Channel[] ping) {
this.recovery = recovery;
this.bulk = bulk;
this.reg = reg;
this.state = state;
this.ping = ping;
}
public boolean hasChannel(Channel channel) {
return hasChannel(channel, recovery) || hasChannel(channel, bulk) || hasChannel(channel, reg) || hasChannel(channel, state) || hasChannel(channel, ping);
}
private boolean hasChannel(Channel channel, Channel[] channels) {
for (Channel channel1 : channels) {
if (channel.equals(channel1)) {
return true;
}
}
return false;
}
public Channel channel(TransportRequestOptions.Type type) {
if (type == TransportRequestOptions.Type.REG) {
return reg[Math.abs(regCounter.incrementAndGet()) % reg.length];
} else if (type == TransportRequestOptions.Type.STATE) {
return state[Math.abs(stateCounter.incrementAndGet()) % state.length];
} else if (type == TransportRequestOptions.Type.PING) {
return ping[Math.abs(pingCounter.incrementAndGet()) % ping.length];
} else if (type == TransportRequestOptions.Type.BULK) {
return bulk[Math.abs(bulkCounter.incrementAndGet()) % bulk.length];
} else if (type == TransportRequestOptions.Type.RECOVERY) {
return recovery[Math.abs(recoveryCounter.incrementAndGet()) % recovery.length];
} else {
throw new ElasticsearchIllegalArgumentException("no type channel for [" + type + "]");
}
}
public synchronized void close() {
List<ChannelFuture> futures = new ArrayList<ChannelFuture>();
closeChannelsAndWait(recovery, futures);
closeChannelsAndWait(bulk, futures);
closeChannelsAndWait(reg, futures);
closeChannelsAndWait(state, futures);
closeChannelsAndWait(ping, futures);
for (ChannelFuture future : futures) {
future.awaitUninterruptibly();
}
}
private void closeChannelsAndWait(Channel[] channels, List<ChannelFuture> futures) {
for (Channel channel : channels) {
try {
if (channel != null && channel.isOpen()) {
futures.add(channel.close());
}
} catch (Exception e) {
//ignore
}
}
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_transport_netty_NettyTransport.java
|
5,325 |
public class UnmappedTerms extends InternalTerms {
public static final Type TYPE = new Type("terms", "umterms");
private static final Collection<Bucket> BUCKETS = Collections.emptyList();
private static final Map<String, Bucket> BUCKETS_MAP = Collections.emptyMap();
public static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public UnmappedTerms readResult(StreamInput in) throws IOException {
UnmappedTerms buckets = new UnmappedTerms();
buckets.readFrom(in);
return buckets;
}
};
public static void registerStreams() {
AggregationStreams.registerStream(STREAM, TYPE.stream());
}
UnmappedTerms() {} // for serialization
public UnmappedTerms(String name, InternalOrder order, int requiredSize, long minDocCount) {
super(name, order, requiredSize, minDocCount, BUCKETS);
}
@Override
public Type type() {
return TYPE;
}
@Override
public void readFrom(StreamInput in) throws IOException {
this.name = in.readString();
this.order = InternalOrder.Streams.readOrder(in);
this.requiredSize = readSize(in);
this.minDocCount = in.readVLong();
this.buckets = BUCKETS;
this.bucketMap = BUCKETS_MAP;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
InternalOrder.Streams.writeOrder(order, out);
writeSize(requiredSize, out);
out.writeVLong(minDocCount);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
builder.startArray(CommonFields.BUCKETS).endArray();
builder.endObject();
return builder;
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_bucket_terms_UnmappedTerms.java
|
93 |
@SuppressWarnings("serial")
static final class ReduceKeysTask<K,V>
extends BulkTask<K,V,K> {
final BiFun<? super K, ? super K, ? extends K> reducer;
K result;
ReduceKeysTask<K,V> rights, nextRight;
ReduceKeysTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
ReduceKeysTask<K,V> nextRight,
BiFun<? super K, ? super K, ? extends K> reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.reducer = reducer;
}
public final K getRawResult() { return result; }
public final void compute() {
final BiFun<? super K, ? super K, ? extends K> reducer;
if ((reducer = this.reducer) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new ReduceKeysTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, reducer)).fork();
}
K r = null;
for (Node<K,V> p; (p = advance()) != null; ) {
K u = p.key;
r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
}
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked") ReduceKeysTask<K,V>
t = (ReduceKeysTask<K,V>)c,
s = t.rights;
while (s != null) {
K tr, sr;
if ((sr = s.result) != null)
t.result = (((tr = t.result) == null) ? sr :
reducer.apply(tr, sr));
s = t.rights = s.nextRight;
}
}
}
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
265 |
public class AppendCallable implements Callable<String>, DataSerializable{
public static final String APPENDAGE = ":CallableResult";
private String msg;
public AppendCallable() {
}
public AppendCallable(String msg) {
this.msg = msg;
}
public String call() throws Exception {
return msg + APPENDAGE;
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(msg);
}
public void readData(ObjectDataInput in) throws IOException {
msg = in.readUTF();
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_tasks_AppendCallable.java
|
374 |
public static class TestCombiner
extends Combiner<String, Integer, Integer> {
private transient int sum;
@Override
public void combine(String key, Integer value) {
sum += value;
}
@Override
public Integer finalizeChunk() {
int v = sum;
sum = 0;
return v;
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_DistributedMapperClientMapReduceTest.java
|
1,540 |
public class XAResourceWrapper implements XAResource {
private final ManagedConnectionImpl managedConnection;
private int transactionTimeoutSeconds;
private XAResource inner;
public XAResourceWrapper(ManagedConnectionImpl managedConnectionImpl) {
this.managedConnection = managedConnectionImpl;
}
//XAResource --START
@Override
public void start(Xid xid, int flags) throws XAException {
managedConnection.log(Level.FINEST, "XA start: " + xid);
switch (flags) {
case TMNOFLAGS:
setInner();
break;
case TMRESUME:
case TMJOIN:
break;
default:
throw new XAException(XAException.XAER_INVAL);
}
if (inner != null) {
inner.start(xid, flags);
}
}
@Override
public void end(Xid xid, int flags) throws XAException {
managedConnection.log(Level.FINEST, "XA end: " + xid + ", " + flags);
validateInner();
inner.end(xid, flags);
}
@Override
public int prepare(Xid xid) throws XAException {
managedConnection.log(Level.FINEST, "XA prepare: " + xid);
validateInner();
return inner.prepare(xid);
}
@Override
public void commit(Xid xid, boolean onePhase) throws XAException {
managedConnection.log(Level.FINEST, "XA commit: " + xid);
validateInner();
inner.commit(xid, onePhase);
}
@Override
public void rollback(Xid xid) throws XAException {
managedConnection.log(Level.FINEST, "XA rollback: " + xid);
validateInner();
inner.rollback(xid);
}
@Override
public void forget(Xid xid) throws XAException {
throw new XAException(XAException.XAER_PROTO);
}
@Override
public boolean isSameRM(XAResource xaResource) throws XAException {
if (xaResource instanceof XAResourceWrapper) {
final ManagedConnectionImpl otherManagedConnection = ((XAResourceWrapper) xaResource).managedConnection;
final HazelcastInstance hazelcastInstance = managedConnection.getHazelcastInstance();
final HazelcastInstance otherHazelcastInstance = otherManagedConnection.getHazelcastInstance();
return hazelcastInstance != null && hazelcastInstance.equals(otherHazelcastInstance);
}
return false;
}
@Override
public Xid[] recover(int flag) throws XAException {
if (inner == null) {
setInner();
}
return inner.recover(flag);
}
@Override
public int getTransactionTimeout() throws XAException {
return transactionTimeoutSeconds;
}
@Override
public boolean setTransactionTimeout(int seconds) throws XAException {
this.transactionTimeoutSeconds = seconds;
return false;
}
private void validateInner() throws XAException {
if (inner == null) {
throw new XAException(XAException.XAER_NOTA);
}
}
private void setInner() throws XAException {
final TransactionContext transactionContext = HazelcastTransactionImpl
.createTransaction(this.getTransactionTimeout(), managedConnection.getHazelcastInstance());
this.managedConnection.getTx().setTxContext(transactionContext);
inner = transactionContext.getXaResource();
}
}
| 1no label
|
hazelcast-ra_hazelcast-jca_src_main_java_com_hazelcast_jca_XAResourceWrapper.java
|
348 |
underlying.backup(out, options, new Callable<Object>() {
@Override
public Object call() throws Exception {
// FLUSHES ALL THE INDEX BEFORE
for (OIndex<?> index : getMetadata().getIndexManager().getIndexes()) {
index.flush();
}
if (callable != null)
return callable.call();
return null;
}
});
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_ODatabaseRecordWrapperAbstract.java
|
1,332 |
public class SolrContext {
public static final String PRIMARY = "primary";
public static final String REINDEX = "reindex";
protected static SolrServer primaryServer = null;
protected static SolrServer reindexServer = null;
public static void setPrimaryServer(SolrServer server) {
primaryServer = server;
}
public static void setReindexServer(SolrServer server) {
reindexServer = server;
}
public static SolrServer getServer() {
return primaryServer;
}
public static SolrServer getReindexServer() {
return isSingleCoreMode() ? primaryServer : reindexServer;
}
public static boolean isSingleCoreMode() {
return reindexServer == null;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_service_solr_SolrContext.java
|
144 |
public static class Order {
public static final int Rules = 1000;
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentImpl.java
|
111 |
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ClientNearCacheConfigTest {
@Test
public void testSpecificNearCacheConfig_whenAsteriskAtTheEnd(){
final ClientConfig clientConfig = new ClientConfig();
final NearCacheConfig genericNearCacheConfig = new NearCacheConfig();
genericNearCacheConfig.setName("map*");
clientConfig.addNearCacheConfig(genericNearCacheConfig);
final NearCacheConfig specificNearCacheConfig = new NearCacheConfig();
specificNearCacheConfig.setName("mapStudent*");
clientConfig.addNearCacheConfig(specificNearCacheConfig);
final NearCacheConfig mapFoo = clientConfig.getNearCacheConfig("mapFoo");
final NearCacheConfig mapStudentFoo = clientConfig.getNearCacheConfig("mapStudentFoo");
assertEquals(genericNearCacheConfig, mapFoo);
assertEquals(specificNearCacheConfig, mapStudentFoo);
}
@Test
public void testSpecificNearCacheConfig_whenAsteriskAtTheBeginning(){
final ClientConfig clientConfig = new ClientConfig();
final NearCacheConfig genericNearCacheConfig = new NearCacheConfig();
genericNearCacheConfig.setName("*Map");
clientConfig.addNearCacheConfig(genericNearCacheConfig);
final NearCacheConfig specificNearCacheConfig = new NearCacheConfig();
specificNearCacheConfig.setName("*MapStudent");
clientConfig.addNearCacheConfig(specificNearCacheConfig);
final NearCacheConfig mapFoo = clientConfig.getNearCacheConfig("fooMap");
final NearCacheConfig mapStudentFoo = clientConfig.getNearCacheConfig("fooMapStudent");
assertEquals(genericNearCacheConfig, mapFoo);
assertEquals(specificNearCacheConfig, mapStudentFoo);
}
@Test
public void testSpecificNearCacheConfig_whenAsteriskInTheMiddle(){
final ClientConfig clientConfig = new ClientConfig();
final NearCacheConfig genericNearCacheConfig = new NearCacheConfig();
genericNearCacheConfig.setName("map*Bar");
clientConfig.addNearCacheConfig(genericNearCacheConfig);
final NearCacheConfig specificNearCacheConfig = new NearCacheConfig();
specificNearCacheConfig.setName("mapStudent*Bar");
clientConfig.addNearCacheConfig(specificNearCacheConfig);
final NearCacheConfig mapFoo = clientConfig.getNearCacheConfig("mapFooBar");
final NearCacheConfig mapStudentFoo = clientConfig.getNearCacheConfig("mapStudentFooBar");
assertEquals(genericNearCacheConfig, mapFoo);
assertEquals(specificNearCacheConfig, mapStudentFoo);
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_ClientNearCacheConfigTest.java
|
212 |
public class ManagerAuthenticator implements Authenticator {
@Override
public void auth(ClientConnection connection) throws AuthenticationException, IOException {
final Object response = authenticate(connection, credentials, principal, true, true);
principal = (ClientPrincipal) response;
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientConnectionManagerImpl.java
|
48 |
public interface PropertyKey extends RelationType {
/**
* Returns the data type for this property key.
* The values of all properties of this type must be an instance of this data type.
*
* @return Data type for this property key.
*/
public Class<?> getDataType();
/**
* The {@link Cardinality} of this property key.
* @return
*/
public Cardinality getCardinality();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_PropertyKey.java
|
158 |
public class ONullSerializer implements OBinarySerializer<Object> {
public static ONullSerializer INSTANCE = new ONullSerializer();
public static final byte ID = 11;
public int getObjectSize(final Object object, Object... hints) {
return 0;
}
public void serialize(final Object object, final byte[] stream, final int startPosition, Object... hints) {
// nothing to serialize
}
public Object deserialize(final byte[] stream, final int startPosition) {
// nothing to deserialize
return null;
}
public int getObjectSize(byte[] stream, int startPosition) {
return 0;
}
public byte getId() {
return ID;
}
public int getObjectSizeNative(byte[] stream, int startPosition) {
return 0;
}
public void serializeNative(Object object, byte[] stream, int startPosition, Object... hints) {
}
public Object deserializeNative(byte[] stream, int startPosition) {
return null;
}
@Override
public void serializeInDirectMemory(Object object, ODirectMemoryPointer pointer, long offset, Object... hints) {
}
@Override
public Object deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) {
return null;
}
@Override
public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) {
return 0;
}
public boolean isFixedLength() {
return true;
}
public int getFixedLength() {
return 0;
}
@Override
public Object preprocess(Object value, Object... hints) {
return null;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_serialization_types_ONullSerializer.java
|
120 |
public interface OLAPResult<S> {
/**
* Returns an {@link Iterable} over all final vertex states.
*
* @return
*/
public Iterable<S> values();
/**
* Returns an {@link Iterable} over all final (vertex-id,vertex-state) pairs resulting from a job's execution.
* @return
*/
public Iterable<Map.Entry<Long,S>> entries();
/**
* Returns the number of vertices in the result
* @return
*/
public long size();
/**
* Returns the final vertex state for a given vertex identified by its id.
*
* @param vertexid
* @return
*/
public S get(long vertexid);
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_olap_OLAPResult.java
|
723 |
ItemListener listener = new ItemListener() {
public void itemAdded(ItemEvent item) {
latchAdd.countDown();
}
public void itemRemoved(ItemEvent item) {
latchRemove.countDown();
}
};
| 0true
|
hazelcast_src_test_java_com_hazelcast_collection_ListTest.java
|
329 |
static final class Fields {
static final XContentBuilderString NAME = new XContentBuilderString("name");
static final XContentBuilderString DESCRIPTION = new XContentBuilderString("description");
static final XContentBuilderString URL = new XContentBuilderString("url");
static final XContentBuilderString JVM = new XContentBuilderString("jvm");
static final XContentBuilderString SITE = new XContentBuilderString("site");
static final XContentBuilderString VERSION = new XContentBuilderString("version");
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_info_PluginInfo.java
|
623 |
static final class Fields {
static final XContentBuilderString ROUTING = new XContentBuilderString("routing");
static final XContentBuilderString STATE = new XContentBuilderString("state");
static final XContentBuilderString PRIMARY = new XContentBuilderString("primary");
static final XContentBuilderString NODE = new XContentBuilderString("node");
static final XContentBuilderString RELOCATING_NODE = new XContentBuilderString("relocating_node");
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_stats_ShardStats.java
|
166 |
public interface RetryableRequest {
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_RetryableRequest.java
|
1,454 |
public class OServerCommandGetGephi extends OServerCommandAuthenticatedDbAbstract {
private static final String[] NAMES = { "GET|gephi/*" };
public OServerCommandGetGephi() {
}
public OServerCommandGetGephi(final OServerCommandConfiguration iConfig) {
}
@Override
public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception {
String[] urlParts = checkSyntax(
iRequest.url,
4,
"Syntax error: gephi/<database>/<language>/<query-text>[/<limit>][/<fetchPlan>].<br/>Limit is optional and is setted to 20 by default. Set expressely to 0 to have no limits.");
final String language = urlParts[2];
final String text = urlParts[3];
final int limit = urlParts.length > 4 ? Integer.parseInt(urlParts[4]) : 20;
final String fetchPlan = urlParts.length > 5 ? urlParts[5] : null;
iRequest.data.commandInfo = "Gephi";
iRequest.data.commandDetail = text;
final ODatabaseDocumentTx db = getProfiledDatabaseInstance(iRequest);
final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph();
try {
final Iterable<OrientVertex> vertices;
if (language.equals("sql"))
vertices = graph.command(new OSQLSynchQuery<OrientVertex>(text, limit).setFetchPlan(fetchPlan)).execute();
else if (language.equals("gremlin")) {
List<Object> result = new ArrayList<Object>();
OGremlinHelper.execute(graph, text, null, null, result, null, null);
vertices = new ArrayList<OrientVertex>(result.size());
for (Object o : result) {
((ArrayList<OrientVertex>) vertices).add(graph.getVertex((OIdentifiable) o));
}
} else
throw new IllegalArgumentException("Language '" + language + "' is not supported. Use 'sql' or 'gremlin'");
sendRecordsContent(iRequest, iResponse, vertices, fetchPlan);
} finally {
if (graph != null)
graph.shutdown();
if (db != null)
db.close();
}
return false;
}
protected void sendRecordsContent(final OHttpRequest iRequest, final OHttpResponse iResponse, Iterable<OrientVertex> iRecords,
String iFetchPlan) throws IOException {
final StringWriter buffer = new StringWriter();
final OJSONWriter json = new OJSONWriter(buffer, OHttpResponse.JSON_FORMAT);
json.setPrettyPrint(true);
generateGraphDbOutput(iRecords, json);
iResponse.send(OHttpUtils.STATUS_OK_CODE, OHttpUtils.STATUS_OK_DESCRIPTION, OHttpUtils.CONTENT_JSON, buffer.toString(), null);
}
protected void generateGraphDbOutput(final Iterable<OrientVertex> iVertices, final OJSONWriter json) throws IOException {
if (iVertices == null)
return;
// CREATE A SET TO SPEED UP SEARCHES ON VERTICES
final Set<OrientVertex> vertexes = new HashSet<OrientVertex>();
for (OrientVertex id : iVertices)
vertexes.add(id);
final Set<OrientEdge> edges = new HashSet<OrientEdge>();
for (OrientVertex vertex : vertexes) {
json.resetAttributes();
json.beginObject(0, false, null);
json.beginObject(1, false, "an");
json.beginObject(2, false, vertex.getIdentity());
// ADD ALL THE EDGES
for (Edge e : vertex.getEdges(Direction.BOTH))
edges.add((OrientEdge) e);
// ADD ALL THE PROPERTIES
for (String field : vertex.getPropertyKeys()) {
final Object v = vertex.getProperty(field);
if (v != null)
json.writeAttribute(3, false, field, v);
}
json.endObject(2, false);
json.endObject(1, false);
json.endObject(0, false);
json.newline();
}
for (OrientEdge edge : edges) {
json.resetAttributes();
json.beginObject();
json.beginObject(1, false, "ae");
json.beginObject(2, false, edge.getId());
json.writeAttribute(3, false, "directed", false);
json.writeAttribute(3, false, "source", edge.getVertex(Direction.IN).getId());
json.writeAttribute(3, false, "target", edge.getVertex(Direction.OUT).getId());
for (String field : edge.getPropertyKeys()) {
final Object v = edge.getProperty(field);
if (v != null)
json.writeAttribute(3, false, field, v);
}
json.endObject(2, false);
json.endObject(1, false);
json.endObject(0, false);
json.newline();
}
}
@Override
public String[] getNames() {
return NAMES;
}
}
| 1no label
|
graphdb_src_main_java_com_orientechnologies_orient_graph_server_command_OServerCommandGetGephi.java
|
26 |
final class ImportVisitor extends Visitor {
private final String prefix;
private final CommonToken token;
private final int offset;
private final Node node;
private final CeylonParseController cpc;
private final List<ICompletionProposal> result;
ImportVisitor(String prefix, CommonToken token, int offset,
Node node, CeylonParseController cpc,
List<ICompletionProposal> result) {
this.prefix = prefix;
this.token = token;
this.offset = offset;
this.node = node;
this.cpc = cpc;
this.result = result;
}
@Override
public void visit(Tree.ModuleDescriptor that) {
super.visit(that);
if (that.getImportPath()==node) {
addCurrentPackageNameCompletion(cpc, offset,
fullPath(offset, prefix, that.getImportPath()) + prefix,
result);
}
}
public void visit(Tree.PackageDescriptor that) {
super.visit(that);
if (that.getImportPath()==node) {
addCurrentPackageNameCompletion(cpc, offset,
fullPath(offset, prefix, that.getImportPath()) + prefix,
result);
}
}
@Override
public void visit(Tree.Import that) {
super.visit(that);
if (that.getImportPath()==node) {
addPackageCompletions(cpc, offset, prefix,
(Tree.ImportPath) node, node, result,
nextTokenType(cpc, token)!=CeylonLexer.LBRACE);
}
}
@Override
public void visit(Tree.PackageLiteral that) {
super.visit(that);
if (that.getImportPath()==node) {
addPackageCompletions(cpc, offset, prefix,
(Tree.ImportPath) node, node, result, false);
}
}
@Override
public void visit(Tree.ImportModule that) {
super.visit(that);
if (that.getImportPath()==node) {
addModuleCompletions(cpc, offset, prefix,
(Tree.ImportPath) node, node, result,
nextTokenType(cpc, token)!=CeylonLexer.STRING_LITERAL);
}
}
@Override
public void visit(Tree.ModuleLiteral that) {
super.visit(that);
if (that.getImportPath()==node) {
addModuleCompletions(cpc, offset, prefix,
(Tree.ImportPath) node, node, result, false);
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ImportVisitor.java
|
547 |
final class TransactionProxy {
private static final ThreadLocal<Boolean> THREAD_FLAG = new ThreadLocal<Boolean>();
private final TransactionOptions options;
private final HazelcastClient client;
private final long threadId = Thread.currentThread().getId();
private final ClientConnection connection;
private SerializableXID sXid;
private String txnId;
private State state = NO_TXN;
private long startTime;
TransactionProxy(HazelcastClient client, TransactionOptions options, ClientConnection connection) {
this.options = options;
this.client = client;
this.connection = connection;
}
public String getTxnId() {
return txnId;
}
public State getState() {
return state;
}
public long getTimeoutMillis() {
return options.getTimeoutMillis();
}
void begin() {
try {
if (state == ACTIVE) {
throw new IllegalStateException("Transaction is already active");
}
checkThread();
if (THREAD_FLAG.get() != null) {
throw new IllegalStateException("Nested transactions are not allowed!");
}
THREAD_FLAG.set(Boolean.TRUE);
startTime = Clock.currentTimeMillis();
txnId = invoke(new CreateTransactionRequest(options, sXid));
state = ACTIVE;
} catch (Exception e) {
closeConnection();
throw ExceptionUtil.rethrow(e);
}
}
public void prepare() {
try {
if (state != ACTIVE) {
throw new TransactionNotActiveException("Transaction is not active");
}
checkThread();
checkTimeout();
invoke(new PrepareTransactionRequest());
state = PREPARED;
} catch (Exception e) {
state = ROLLING_BACK;
closeConnection();
throw ExceptionUtil.rethrow(e);
}
}
void commit(boolean prepareAndCommit) {
try {
if (prepareAndCommit && state != ACTIVE) {
throw new TransactionNotActiveException("Transaction is not active");
}
if (!prepareAndCommit && state != PREPARED) {
throw new TransactionNotActiveException("Transaction is not prepared");
}
checkThread();
checkTimeout();
invoke(new CommitTransactionRequest(prepareAndCommit));
state = COMMITTED;
} catch (Exception e) {
state = ROLLING_BACK;
throw ExceptionUtil.rethrow(e);
} finally {
closeConnection();
}
}
void rollback() {
try {
if (state == NO_TXN || state == ROLLED_BACK) {
throw new IllegalStateException("Transaction is not active");
}
if (state == ROLLING_BACK) {
state = ROLLED_BACK;
return;
}
checkThread();
try {
invoke(new RollbackTransactionRequest());
} catch (Exception ignored) {
}
state = ROLLED_BACK;
} finally {
closeConnection();
}
}
SerializableXID getXid() {
return sXid;
}
void setXid(SerializableXID xid) {
this.sXid = xid;
}
private void closeConnection() {
THREAD_FLAG.set(null);
// try {
// connection.release();
// } catch (IOException e) {
// IOUtil.closeResource(connection);
// }
}
private void checkThread() {
if (threadId != Thread.currentThread().getId()) {
throw new IllegalStateException("Transaction cannot span multiple threads!");
}
}
private void checkTimeout() {
if (startTime + options.getTimeoutMillis() < Clock.currentTimeMillis()) {
throw new TransactionException("Transaction is timed-out!");
}
}
private <T> T invoke(ClientRequest request) {
if (request instanceof BaseTransactionRequest) {
((BaseTransactionRequest) request).setTxnId(txnId);
((BaseTransactionRequest) request).setClientThreadId(threadId);
}
final SerializationService ss = client.getSerializationService();
final ClientInvocationServiceImpl invocationService = (ClientInvocationServiceImpl) client.getInvocationService();
try {
final Future f = invocationService.send(request, connection);
return ss.toObject(f.get());
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_txn_TransactionProxy.java
|
165 |
public class TestPartialTransactionCopier
{
@Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule();
@SuppressWarnings( "unchecked" )
@Test
public void shouldCopyRunningTransactionsToNewLog() throws Exception
{
// Given
int masterId = -1;
int meId = -1;
String storeDir = "dir";
// I have a log with a transaction in the middle missing a "DONE" record
Pair<File, Integer> broken = createBrokenLogFile( storeDir );
File brokenLogFile = broken.first();
Integer brokenTxIdentifier = broken.other();
// And I've read the log header on that broken file
StoreChannel brokenLog = fs.get().open( brokenLogFile, "rw" );
ByteBuffer buffer = allocate( 9 + Xid.MAXGTRIDSIZE + Xid.MAXBQUALSIZE * 10 );
readLogHeader( buffer, brokenLog, true );
// And I have an awesome partial transaction copier
PartialTransactionCopier copier = new PartialTransactionCopier(
buffer, new CommandFactory(),
StringLogger.DEV_NULL, new LogExtractor.LogPositionCache(),
null, createXidMapWithOneStartEntry( masterId, /*txId=*/brokenTxIdentifier ),
new Monitors().newMonitor( ByteCounterMonitor.class ) );
// When
File newLogFile = new File( "new.log" );
copier.copy( brokenLog, createNewLogWithHeader( newLogFile ), 1 );
// Then
assertThat(
logEntries( fs.get(), newLogFile ),
containsExactly(
startEntry( brokenTxIdentifier, masterId, meId ),
nodeCommandEntry( brokenTxIdentifier, /*nodeId=*/1 ),
onePhaseCommitEntry( brokenTxIdentifier, /*txid=*/3 ),
// Missing done entry
startEntry( 5, masterId, meId ),
nodeCommandEntry( 5, /*nodeId=*/2),
onePhaseCommitEntry( 5, /*txid=*/4 ),
doneEntry( 5 ),
startEntry( 6, masterId, meId ),
nodeCommandEntry( 6, /*nodeId=*/3 ),
onePhaseCommitEntry( 6, /*txid=*/5 ),
doneEntry( 6 )
));
}
private ArrayMap<Integer, LogEntry.Start> createXidMapWithOneStartEntry( int masterId, Integer brokenTxId )
{
ArrayMap<Integer, LogEntry.Start> xidentMap = new ArrayMap<Integer, LogEntry.Start>();
xidentMap.put( brokenTxId, new LogEntry.Start( null, brokenTxId, masterId, 3, 4, 5, 6 ) );
return xidentMap;
}
private LogBuffer createNewLogWithHeader( File newLogFile ) throws IOException
{
StoreChannel newLog = fs.get().open( newLogFile, "rw" );
LogBuffer newLogBuffer = new DirectLogBuffer( newLog, allocate( 10000 ) );
ByteBuffer buf = allocate( 100 );
writeLogHeader( buf, 1, /* we don't care about this */ 4 );
newLogBuffer.getFileChannel().write( buf );
return newLogBuffer;
}
private Pair<File, Integer> createBrokenLogFile( String storeDir ) throws Exception
{
GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory()
.setFileSystem( fs.get() ).newImpermanentDatabase( storeDir );
for ( int i = 0; i < 4; i++ )
{
Transaction tx = db.beginTx();
db.createNode();
tx.success();
tx.finish();
}
db.shutdown();
// Remove the DONE record from the second transaction
final AtomicInteger brokenTxIdentifier = new AtomicInteger();
LogHookAdapter<LogEntry> filter = new LogTestUtils.LogHookAdapter<LogEntry>()
{
int doneRecordCount = 0;
@Override
public boolean accept( LogEntry item )
{
//System.out.println(item);
if( item instanceof LogEntry.Done)
{
doneRecordCount++;
// Accept everything except the second done record we find
if( doneRecordCount == 2)
{
brokenTxIdentifier.set( item.getIdentifier() );
return false;
}
}
// Not a done record, not our concern
return true;
}
};
File brokenLogFile = filterNeostoreLogicalLog( fs.get(),
new File( storeDir, "nioneo_logical.log.v0"), filter );
return Pair.of( brokenLogFile, brokenTxIdentifier.get() );
}
}
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestPartialTransactionCopier.java
|
606 |
@Component("blRequestFilter")
public class BroadleafRequestFilter extends OncePerRequestFilter {
private final Log LOG = LogFactory.getLog(getClass());
/**
* Parameter/Attribute name for the current language
*/
public static String REQUEST_DTO_PARAM_NAME = "blRequestDTO";
// Properties to manage URLs that will not be processed by this filter.
private static final String BLC_ADMIN_GWT = "org.broadleafcommerce.admin";
private static final String BLC_ADMIN_PREFIX = "blcadmin";
private static final String BLC_ADMIN_SERVICE = ".service";
private Set<String> ignoreSuffixes;
@Resource(name = "blRequestProcessor")
protected BroadleafRequestProcessor requestProcessor;
@Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
if (!shouldProcessURL(request, request.getRequestURI())) {
if (LOG.isTraceEnabled()) {
LOG.trace("Process URL not processing URL " + request.getRequestURI());
}
filterChain.doFilter(request, response);
return;
}
if (LOG.isTraceEnabled()) {
String requestURIWithoutContext;
if (request.getContextPath() != null) {
requestURIWithoutContext = request.getRequestURI().substring(request.getContextPath().length());
} else {
requestURIWithoutContext = request.getRequestURI();
}
// Remove JSESSION-ID or other modifiers
int pos = requestURIWithoutContext.indexOf(";");
if (pos >= 0) {
requestURIWithoutContext = requestURIWithoutContext.substring(0, pos);
}
LOG.trace("Process URL Filter Begin " + requestURIWithoutContext);
}
if (request.getAttribute(REQUEST_DTO_PARAM_NAME) == null) {
request.setAttribute(REQUEST_DTO_PARAM_NAME, new RequestDTOImpl(request));
}
try {
requestProcessor.process(new ServletWebRequest(request, response));
filterChain.doFilter(request, response);
} catch (SiteNotFoundException e) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
} finally {
requestProcessor.postProcess(new ServletWebRequest(request, response));
}
}
/**
* Determines if the passed in URL should be processed by the content management system.
* <p/>
* By default, this method returns false for any BLC-Admin URLs and service calls and for all common image/digital mime-types (as determined by an internal call to {@code getIgnoreSuffixes}.
* <p/>
* This check is called with the {@code doFilterInternal} method to short-circuit the content processing which can be expensive for requests that do not require it.
*
* @param requestURI
* - the HttpServletRequest.getRequestURI
* @return true if the {@code HttpServletRequest} should be processed
*/
protected boolean shouldProcessURL(HttpServletRequest request, String requestURI) {
if (requestURI.contains(BLC_ADMIN_GWT) || requestURI.endsWith(BLC_ADMIN_SERVICE) || requestURI.contains(BLC_ADMIN_PREFIX)) {
if (LOG.isTraceEnabled()) {
LOG.trace("BroadleafProcessURLFilter ignoring admin request URI " + requestURI);
}
return false;
} else {
int pos = requestURI.lastIndexOf(".");
if (pos > 0) {
// String suffix = requestURI.substring(pos);
// if (getIgnoreSuffixes().contains(suffix.toLowerCase())) {
// if (LOG.isTraceEnabled()) {
// LOG.trace("BroadleafProcessURLFilter ignoring request due to suffix " + requestURI);
// }
// return false;
// }
}
}
return true;
}
/**
* Returns a set of suffixes that can be ignored by content processing. The following are returned:
* <p/>
* <B>List of suffixes ignored:</B>
*
* ".aif", ".aiff", ".asf", ".avi", ".bin", ".bmp", ".doc", ".eps", ".gif", ".hqx", ".jpg", ".jpeg", ".mid", ".midi", ".mov", ".mp3", ".mpg", ".mpeg", ".p65", ".pdf", ".pic", ".pict", ".png", ".ppt", ".psd", ".qxd", ".ram", ".ra", ".rm", ".sea", ".sit", ".stk", ".swf", ".tif", ".tiff", ".txt", ".rtf", ".vob", ".wav", ".wmf", ".xls", ".zip";
*
* @return set of suffixes to ignore.
*/
protected Set getIgnoreSuffixes() {
if (ignoreSuffixes == null || ignoreSuffixes.isEmpty()) {
String[] ignoreSuffixList = { ".aif", ".aiff", ".asf", ".avi", ".bin", ".bmp", ".css", ".doc", ".eps", ".gif", ".hqx", ".js", ".jpg", ".jpeg", ".mid", ".midi", ".mov", ".mp3", ".mpg", ".mpeg", ".p65", ".pdf", ".pic", ".pict", ".png", ".ppt", ".psd", ".qxd", ".ram", ".ra", ".rm", ".sea", ".sit", ".stk", ".swf", ".tif", ".tiff", ".txt", ".rtf", ".vob", ".wav", ".wmf", ".xls", ".zip" };
ignoreSuffixes = new HashSet<String>(Arrays.asList(ignoreSuffixList));
}
return ignoreSuffixes;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_web_BroadleafRequestFilter.java
|
141 |
@Test
public class DecimalSerializerTest {
private final static int FIELD_SIZE = 9;
private static final BigDecimal OBJECT = new BigDecimal(new BigInteger("20"), 2);
private ODecimalSerializer decimalSerializer;
private static final byte[] stream = new byte[FIELD_SIZE];
@BeforeClass
public void beforeClass() {
decimalSerializer = new ODecimalSerializer();
}
public void testFieldSize() {
Assert.assertEquals(decimalSerializer.getObjectSize(OBJECT), FIELD_SIZE);
}
public void testSerialize() {
decimalSerializer.serialize(OBJECT, stream, 0);
Assert.assertEquals(decimalSerializer.deserialize(stream, 0), OBJECT);
}
public void testSerializeNative() {
decimalSerializer.serializeNative(OBJECT, stream, 0);
Assert.assertEquals(decimalSerializer.deserializeNative(stream, 0), OBJECT);
}
public void testNativeDirectMemoryCompatibility() {
decimalSerializer.serializeNative(OBJECT, stream, 0);
ODirectMemoryPointer pointer = new ODirectMemoryPointer(stream);
try {
Assert.assertEquals(decimalSerializer.deserializeFromDirectMemory(pointer, 0), OBJECT);
} finally {
pointer.free();
}
}
}
| 0true
|
commons_src_test_java_com_orientechnologies_common_serialization_types_DecimalSerializerTest.java
|
40 |
public class DummyCreditCardModule extends AbstractModule {
@Override
public PaymentResponseItem processAuthorize(PaymentContext paymentContext, Money amountToAuthorize, PaymentResponseItem responseItem) throws PaymentException {
return createResponse(paymentContext, responseItem);
}
@Override
public PaymentResponseItem processAuthorizeAndDebit(PaymentContext paymentContext, Money amountToDebit, PaymentResponseItem responseItem) throws PaymentException {
return createResponse(paymentContext, responseItem);
}
@Override
public PaymentResponseItem processDebit(PaymentContext paymentContext, Money amountToDebit, PaymentResponseItem responseItem) throws PaymentException {
return createResponse(paymentContext, responseItem);
}
@Override
public PaymentResponseItem processCredit(PaymentContext paymentContext, Money amountToCredit, PaymentResponseItem responseItem) throws PaymentException {
return createResponse(paymentContext, responseItem);
}
@Override
public PaymentResponseItem processVoidPayment(PaymentContext paymentContext, Money amountToVoid, PaymentResponseItem responseItem) throws PaymentException {
return createResponse(paymentContext, responseItem);
}
@Override
public PaymentResponseItem processBalance(PaymentContext paymentContext, PaymentResponseItem responseItem) throws PaymentException {
return createResponse(paymentContext, responseItem);
}
@Override
public PaymentResponseItem processReverseAuthorize(PaymentContext paymentContext, Money amountToReverseAuthorize, PaymentResponseItem responseItem) throws PaymentException {
return createResponse(paymentContext, responseItem);
}
@Override
public PaymentResponseItem processPartialPayment(PaymentContext paymentContext, Money amountToDebit, PaymentResponseItem responseItem) throws PaymentException {
throw new PaymentException("partial payment not implemented.");
}
private PaymentResponseItem createResponse(PaymentContext paymentContext, PaymentResponseItem responseItem) {
paymentContext.getPaymentInfo().setReferenceNumber("abc123");
responseItem.setReferenceNumber(paymentContext.getPaymentInfo().getReferenceNumber());
responseItem.setTransactionId(paymentContext.getPaymentInfo().getReferenceNumber());
responseItem.setTransactionSuccess(true);
responseItem.setTransactionAmount(paymentContext.getPaymentInfo().getAmount());
responseItem.setCurrency(paymentContext.getPaymentInfo().getCurrency());
return responseItem;
}
@Override
public Boolean isValidCandidate(PaymentInfoType paymentType) {
return PaymentInfoType.CREDIT_CARD.equals(paymentType);
}
}
| 0true
|
integration_src_test_java_org_broadleafcommerce_checkout_service_DummyCreditCardModule.java
|
142 |
public enum ReflectiveConfigOptionLoader {
INSTANCE;
private static final String SYS_PROP_NAME = "titan.load.cfg.opts";
private static final String ENV_VAR_NAME = "TITAN_LOAD_CFG_OPTS";
private static final Logger log =
LoggerFactory.getLogger(ReflectiveConfigOptionLoader.class);
private volatile LoaderConfiguration cfg = new LoaderConfiguration();
public ReflectiveConfigOptionLoader setUseThreadContextLoader(boolean b) {
cfg = cfg.setUseThreadContextLoader(b);
return this;
}
public ReflectiveConfigOptionLoader setUseCallerLoader(boolean b) {
cfg = cfg.setUseCallerLoader(b);
return this;
}
public ReflectiveConfigOptionLoader setPreferredClassLoaders(List<ClassLoader> loaders) {
cfg = cfg.setPreferredClassLoaders(ImmutableList.copyOf(loaders));
return this;
}
public ReflectiveConfigOptionLoader setEnabled(boolean enabled) {
cfg = cfg.setEnabled(enabled);
return this;
}
public ReflectiveConfigOptionLoader reset() {
cfg = new LoaderConfiguration();
return this;
}
/**
* Reflectively load types at most once over the life of this class. This
* method is synchronized and uses a static class field to ensure that it
* calls {@link #load()} only on the first invocation and does nothing
* thereafter. This is the right behavior as long as the classpath doesn't
* change in the middle of the enclosing JVM's lifetime.
*/
public void loadAll(Class<?> caller) {
LoaderConfiguration cfg = this.cfg;
if (!cfg.enabled || cfg.allInit)
return;
load(cfg, caller);
cfg.allInit = true;
}
public void loadStandard(Class<?> caller) {
LoaderConfiguration cfg = this.cfg;
if (!cfg.enabled || cfg.standardInit || cfg.allInit)
return;
/*
* Aside from the classes in titan-core, we can't guarantee the presence
* of these classes at runtime. That's why they're loaded reflectively.
* We could probably hard-code the initialization of the titan-core classes,
* but the benefit isn't substantial.
*/
List<String> classnames = ImmutableList.of(
"com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager",
"com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager",
"com.thinkaurelius.titan.diskstorage.cassandra.AbstractCassandraStoreManager",
"com.thinkaurelius.titan.diskstorage.cassandra.thrift.CassandraThriftStoreManager",
"com.thinkaurelius.titan.diskstorage.es.ElasticSearchIndex",
"com.thinkaurelius.titan.diskstorage.log.kcvs.KCVSLog",
"com.thinkaurelius.titan.diskstorage.log.kcvs.KCVSLogManager",
"com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration",
"com.thinkaurelius.titan.graphdb.database.idassigner.placement.SimpleBulkPlacementStrategy",
"com.thinkaurelius.titan.graphdb.database.idassigner.VertexIDAssigner",
//"com.thinkaurelius.titan.graphdb.TestMockIndexProvider",
//"com.thinkaurelius.titan.graphdb.TestMockLog",
"com.thinkaurelius.titan.diskstorage.berkeleyje.BerkeleyJEStoreManager");
Timer t = new Timer(Timestamps.MILLI);
t.start();
List<ClassLoader> loaders = getClassLoaders(cfg, caller);
// Iterate over classloaders until the first successful load, then keep that
// loader even if it fails to load classes further down the classnames list.
boolean foundLoader = false;
ClassLoader cl = null;
int loadedClasses = 0;
for (String c : classnames) {
if (foundLoader) {
try {
Class.forName(c, true, cl);
loadedClasses++;
log.debug("Loaded class {} with selected loader {}", c, cl);
} catch (ClassNotFoundException e) {
log.debug("Unable to load class {} with selected loader {}", c, cl, e);
}
} else {
for (ClassLoader candidate : loaders) {
cl = candidate;
try {
Class.forName(c, true, cl);
loadedClasses++;
log.debug("Loaded class {} with loader {}", c, cl);
log.debug("Located functioning classloader {}; using it for remaining classload attempts", cl);
foundLoader = true;
break;
} catch (ClassNotFoundException e) {
log.debug("Unable to load class {} with loader {}", c, cl, e);
}
}
}
}
log.info("Loaded and initialized config classes: {} OK out of {} attempts in {}", loadedClasses, classnames.size(), t.elapsed());
cfg.standardInit = true;
}
private List<ClassLoader> getClassLoaders(LoaderConfiguration cfg, Class<?> caller) {
ImmutableList.Builder<ClassLoader> builder = ImmutableList.<ClassLoader>builder();
builder.addAll(cfg.preferredLoaders);
for (ClassLoader c : cfg.preferredLoaders)
log.debug("Added preferred classloader to config option loader chain: {}", c);
if (cfg.useThreadContextLoader) {
ClassLoader c = Thread.currentThread().getContextClassLoader();
builder.add(c);
log.debug("Added thread context classloader to config option loader chain: {}", c);
}
if (cfg.useCallerLoader) {
ClassLoader c = caller.getClassLoader();
builder.add(c);
log.debug("Added caller classloader to config option loader chain: {}", c);
}
return builder.build();
}
/**
* Use reflection to iterate over the classpath looking for
* {@link PreInitializeConfigOptions} annotations, then load any such
* annotated types found. This method's runtime is roughly proportional to
* the number of elements in the classpath (and can be substantial).
*/
private synchronized void load(LoaderConfiguration cfg, Class<?> caller) {
try {
loadAllClassesUnsafe(cfg, caller);
} catch (Throwable t) {
// We could probably narrow the caught exception type to Error or maybe even just LinkageError,
// but in this case catching anything via Throwable seems appropriate. RuntimeException is
// not sufficient -- it wouldn't even catch NoClassDefFoundError.
log.error("Failed to iterate over classpath using Reflections; this usually indicates a broken classpath/classloader", PreInitializeConfigOptions.class, t);
}
}
private void loadAllClassesUnsafe(LoaderConfiguration cfg, Class<?> caller) {
int loadCount = 0;
int errorCount = 0;
List<ClassLoader> loaderList = getClassLoaders(cfg, caller);
Collection<URL> scanUrls = forClassLoaders(loaderList);
Iterator<URL> i = scanUrls.iterator();
while (i.hasNext()) {
File f = new File(i.next().getPath());
if (!f.exists() || !f.canRead()) {
log.trace("Skipping nonexistent or unreadable classpath element {}", f);
i.remove();
}
log.trace("Retaining classpath element {}", f);
}
org.reflections.Configuration rc = new org.reflections.util.ConfigurationBuilder()
.setUrls(scanUrls)
.setScanners(new TypeAnnotationsScanner(), new SubTypesScanner());
Reflections reflections = new Reflections(rc);
//for (Class<?> c : reflections.getSubTypesOf(Object.class)) { // Returns nothing
for (Class<?> c : reflections.getTypesAnnotatedWith(PreInitializeConfigOptions.class)) {
try {
loadCount += loadSingleClassUnsafe(c);
} catch (Throwable t) {
log.warn("Failed to load class {} or its referenced types; this usually indicates a broken classpath/classloader", c, t);
errorCount++;
}
}
log.debug("Preloaded {} config option(s) via Reflections ({} class(es) with errors)", loadCount, errorCount);
}
/**
* This method is based on ClasspathHelper.forClassLoader from Reflections.
*
* We made our own copy to avoid dealing with bytecode-level incompatibilities
* introduced by changing method signatures between 0.9.9-RC1 and 0.9.9.
*
* @return A set of all URLs associated with URLClassLoaders in the argument
*/
private Set<URL> forClassLoaders(List<ClassLoader> loaders) {
final Set<URL> result = Sets.newHashSet();
for (ClassLoader classLoader : loaders) {
while (classLoader != null) {
if (classLoader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader) classLoader).getURLs();
if (urls != null) {
result.addAll(Sets.newHashSet(urls));
}
}
classLoader = classLoader.getParent();
}
}
return result;
}
private int loadSingleClassUnsafe(Class<?> c) {
int loadCount = 0;
log.trace("Looking for ConfigOption public static fields on class {}", c);
for (Field f : c.getDeclaredFields()) {
final boolean pub = Modifier.isPublic(f.getModifiers());
final boolean stat = Modifier.isStatic(f.getModifiers());
final boolean typeMatch = ConfigOption.class.isAssignableFrom(f.getType());
log.trace("Properties for field \"{}\": public={} static={} assignable={}", f, pub, stat, typeMatch);
if (pub && stat && typeMatch) {
try {
Object o = f.get(null);
Preconditions.checkNotNull(o);
log.debug("Initialized {}={}", f, o);
loadCount++;
} catch (IllegalArgumentException e) {
log.warn("ConfigOption initialization error", e);
} catch (IllegalAccessException e) {
log.warn("ConfigOption initialization error", e);
}
}
}
return loadCount;
}
private static class LoaderConfiguration {
private static final Logger log =
LoggerFactory.getLogger(LoaderConfiguration.class);
private final boolean enabled;
private final List<ClassLoader> preferredLoaders;
private final boolean useCallerLoader;
private final boolean useThreadContextLoader;
private volatile boolean allInit = false;
private volatile boolean standardInit = false;
private LoaderConfiguration(boolean enabled, List<ClassLoader> preferredLoaders,
boolean useCallerLoader, boolean useThreadContextLoader) {
this.enabled = enabled;
this.preferredLoaders = preferredLoaders;
this.useCallerLoader = useCallerLoader;
this.useThreadContextLoader = useThreadContextLoader;
}
private LoaderConfiguration() {
enabled = getEnabledByDefault();
preferredLoaders = ImmutableList.of(ReflectiveConfigOptionLoader.class.getClassLoader());
useCallerLoader = true;
useThreadContextLoader = true;
}
private boolean getEnabledByDefault() {
List<String> sources =
Arrays.asList(System.getProperty(SYS_PROP_NAME), System.getenv(ENV_VAR_NAME));
for (String setting : sources) {
if (null != setting) {
boolean enabled = setting.equalsIgnoreCase("true");
log.debug("Option loading enabled={}", enabled);
return enabled;
}
}
log.debug("Option loading enabled by default");
return true;
}
LoaderConfiguration setEnabled(boolean b) {
return new LoaderConfiguration(b, preferredLoaders, useCallerLoader, useThreadContextLoader);
}
LoaderConfiguration setPreferredClassLoaders(List<ClassLoader> cl) {
return new LoaderConfiguration(enabled, cl, useCallerLoader, useThreadContextLoader);
}
LoaderConfiguration setUseCallerLoader(boolean b) {
return new LoaderConfiguration(enabled, preferredLoaders, b, useThreadContextLoader);
}
LoaderConfiguration setUseThreadContextLoader(boolean b) {
return new LoaderConfiguration(enabled, preferredLoaders, useCallerLoader, b);
}
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_util_ReflectiveConfigOptionLoader.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
|
902 |
@SuppressWarnings({ "unchecked", "serial" })
public abstract class ORecordSchemaAwareAbstract<T> extends ORecordAbstract<T> implements ORecordSchemaAware<T> {
protected OClass _clazz;
public ORecordSchemaAwareAbstract() {
}
/**
* Validates the record following the declared constraints defined in schema such as mandatory, notNull, min, max, regexp, etc. If
* the schema is not defined for the current class or there are not constraints then the validation is ignored.
*
* @see OProperty
* @throws OValidationException
* if the document breaks some validation constraints defined in the schema
*/
public void validate() throws OValidationException {
if (ODatabaseRecordThreadLocal.INSTANCE.isDefined() && !getDatabase().isValidationEnabled())
return;
checkForLoading();
checkForFields();
if (_clazz != null) {
if (_clazz.isStrictMode()) {
// CHECK IF ALL FIELDS ARE DEFINED
for (String f : fieldNames()) {
if (_clazz.getProperty(f) == null)
throw new OValidationException("Found additional field '" + f + "'. It cannot be added because the schema class '"
+ _clazz.getName() + "' is defined as STRICT");
}
}
for (OProperty p : _clazz.properties()) {
validateField(this, p);
}
}
}
public OClass getSchemaClass() {
if (_clazz == null) {
// DESERIALIZE ONLY IF THE CLASS IS NOT SETTED: THIS PREVENT TO
// UNMARSHALL THE RECORD EVEN IF SETTED BY fromString()
checkForLoading();
checkForFields("@class");
}
return _clazz;
}
public String getClassName() {
if (_clazz != null)
return _clazz.getName();
// CLASS NOT FOUND: CHECK IF NEED LOADING AND UNMARSHALLING
checkForLoading();
checkForFields("@class");
return _clazz != null ? _clazz.getName() : null;
}
public void setClassName(final String iClassName) {
if (iClassName == null) {
_clazz = null;
return;
}
setClass(getDatabase().getMetadata().getSchema().getOrCreateClass(iClassName));
}
public void setClassNameIfExists(final String iClassName) {
if (iClassName == null) {
_clazz = null;
return;
}
setClass(getDatabase().getMetadata().getSchema().getClass(iClassName));
}
@Override
public ORecordSchemaAwareAbstract<T> reset() {
super.reset();
_clazz = null;
return this;
}
public byte[] toStream() {
return toStream(false);
}
public byte[] toStream(final boolean iOnlyDelta) {
if (_source == null)
_source = _recordFormat.toStream(this, iOnlyDelta);
invokeListenerEvent(ORecordListener.EVENT.MARSHALL);
return _source;
}
public void remove() {
throw new UnsupportedOperationException();
}
protected boolean checkForFields(final String... iFields) {
if (_status == ORecordElement.STATUS.LOADED && fields() == 0)
// POPULATE FIELDS LAZY
return deserializeFields(iFields);
return true;
}
public boolean deserializeFields(final String... iFields) {
if (_source == null)
return false;
_status = ORecordElement.STATUS.UNMARSHALLING;
_recordFormat.fromStream(_source, this, iFields);
_status = ORecordElement.STATUS.LOADED;
return true;
}
protected void setClass(final OClass iClass) {
if (iClass != null && iClass.isAbstract())
throw new OSchemaException("Cannot create a document of an abstract class");
_clazz = iClass;
}
protected void checkFieldAccess(final int iIndex) {
if (iIndex < 0 || iIndex >= fields())
throw new IndexOutOfBoundsException("Index " + iIndex + " is outside the range allowed: 0-" + fields());
}
public static void validateField(ORecordSchemaAwareAbstract<?> iRecord, OProperty p) throws OValidationException {
final Object fieldValue;
if (iRecord.containsField(p.getName())) {
if (iRecord instanceof ODocument)
// AVOID CONVERSIONS: FASTER!
fieldValue = ((ODocument) iRecord).rawField(p.getName());
else
fieldValue = iRecord.field(p.getName());
if (p.isNotNull() && fieldValue == null)
// NULLITY
throw new OValidationException("The field '" + p.getFullName() + "' cannot be null");
if (fieldValue != null && p.getRegexp() != null) {
// REGEXP
if (!fieldValue.toString().matches(p.getRegexp()))
throw new OValidationException("The field '" + p.getFullName() + "' does not match the regular expression '"
+ p.getRegexp() + "'. Field value is: " + fieldValue);
}
} else {
if (p.isMandatory())
throw new OValidationException("The field '" + p.getFullName() + "' is mandatory");
fieldValue = null;
}
final OType type = p.getType();
if (fieldValue != null && type != null) {
// CHECK TYPE
switch (type) {
case LINK:
validateLink(p, fieldValue);
break;
case LINKLIST:
if (!(fieldValue instanceof List))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as LINKLIST but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null)
for (Object item : ((List<?>) fieldValue))
validateLink(p, item);
break;
case LINKSET:
if (!(fieldValue instanceof Set))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as LINKSET but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null)
for (Object item : ((Set<?>) fieldValue))
validateLink(p, item);
break;
case LINKMAP:
if (!(fieldValue instanceof Map))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as LINKMAP but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null)
for (Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet())
validateLink(p, entry.getValue());
break;
case EMBEDDED:
validateEmbedded(p, fieldValue);
break;
case EMBEDDEDLIST:
if (!(fieldValue instanceof List))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as EMBEDDEDLIST but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null) {
for (Object item : ((List<?>) fieldValue))
validateEmbedded(p, item);
} else if (p.getLinkedType() != null) {
for (Object item : ((List<?>) fieldValue))
validateType(p, item);
}
break;
case EMBEDDEDSET:
if (!(fieldValue instanceof Set))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as EMBEDDEDSET but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null) {
for (Object item : ((Set<?>) fieldValue))
validateEmbedded(p, item);
} else if (p.getLinkedType() != null) {
for (Object item : ((Set<?>) fieldValue))
validateType(p, item);
}
break;
case EMBEDDEDMAP:
if (!(fieldValue instanceof Map))
throw new OValidationException("The field '" + p.getFullName()
+ "' has been declared as EMBEDDEDMAP but an incompatible type is used. Value: " + fieldValue);
if (p.getLinkedClass() != null) {
for (Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet())
validateEmbedded(p, entry.getValue());
} else if (p.getLinkedType() != null) {
for (Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet())
validateType(p, entry.getValue());
}
break;
}
}
if (p.getMin() != null) {
// MIN
final String min = p.getMin();
if (p.getType().equals(OType.STRING) && (fieldValue != null && ((String) fieldValue).length() < Integer.parseInt(min)))
throw new OValidationException("The field '" + p.getFullName() + "' contains fewer characters than " + min + " requested");
else if (p.getType().equals(OType.BINARY) && (fieldValue != null && ((byte[]) fieldValue).length < Integer.parseInt(min)))
throw new OValidationException("The field '" + p.getFullName() + "' contains fewer bytes than " + min + " requested");
else if (p.getType().equals(OType.INTEGER) && (fieldValue != null && type.asInt(fieldValue) < Integer.parseInt(min)))
throw new OValidationException("The field '" + p.getFullName() + "' is less than " + min);
else if (p.getType().equals(OType.LONG) && (fieldValue != null && type.asLong(fieldValue) < Long.parseLong(min)))
throw new OValidationException("The field '" + p.getFullName() + "' is less than " + min);
else if (p.getType().equals(OType.FLOAT) && (fieldValue != null && type.asFloat(fieldValue) < Float.parseFloat(min)))
throw new OValidationException("The field '" + p.getFullName() + "' is less than " + min);
else if (p.getType().equals(OType.DOUBLE) && (fieldValue != null && type.asDouble(fieldValue) < Double.parseDouble(min)))
throw new OValidationException("The field '" + p.getFullName() + "' is less than " + min);
else if (p.getType().equals(OType.DATE)) {
try {
if (fieldValue != null
&& ((Date) fieldValue).before(iRecord.getDatabase().getStorage().getConfiguration().getDateFormatInstance()
.parse(min)))
throw new OValidationException("The field '" + p.getFullName() + "' contains the date " + fieldValue
+ " which precedes the first acceptable date (" + min + ")");
} catch (ParseException e) {
}
} else if (p.getType().equals(OType.DATETIME)) {
try {
if (fieldValue != null
&& ((Date) fieldValue).before(iRecord.getDatabase().getStorage().getConfiguration().getDateTimeFormatInstance()
.parse(min)))
throw new OValidationException("The field '" + p.getFullName() + "' contains the datetime " + fieldValue
+ " which precedes the first acceptable datetime (" + min + ")");
} catch (ParseException e) {
}
} else if ((p.getType().equals(OType.EMBEDDEDLIST) || p.getType().equals(OType.EMBEDDEDSET)
|| p.getType().equals(OType.LINKLIST) || p.getType().equals(OType.LINKSET))
&& (fieldValue != null && ((Collection<?>) fieldValue).size() < Integer.parseInt(min)))
throw new OValidationException("The field '" + p.getFullName() + "' contains fewer items than " + min + " requested");
}
if (p.getMax() != null) {
// MAX
final String max = p.getMax();
if (p.getType().equals(OType.STRING) && (fieldValue != null && ((String) fieldValue).length() > Integer.parseInt(max)))
throw new OValidationException("The field '" + p.getFullName() + "' contains more characters than " + max + " requested");
else if (p.getType().equals(OType.BINARY) && (fieldValue != null && ((byte[]) fieldValue).length > Integer.parseInt(max)))
throw new OValidationException("The field '" + p.getFullName() + "' contains more bytes than " + max + " requested");
else if (p.getType().equals(OType.INTEGER) && (fieldValue != null && type.asInt(fieldValue) > Integer.parseInt(max)))
throw new OValidationException("The field '" + p.getFullName() + "' is greater than " + max);
else if (p.getType().equals(OType.LONG) && (fieldValue != null && type.asLong(fieldValue) > Long.parseLong(max)))
throw new OValidationException("The field '" + p.getFullName() + "' is greater than " + max);
else if (p.getType().equals(OType.FLOAT) && (fieldValue != null && type.asFloat(fieldValue) > Float.parseFloat(max)))
throw new OValidationException("The field '" + p.getFullName() + "' is greater than " + max);
else if (p.getType().equals(OType.DOUBLE) && (fieldValue != null && type.asDouble(fieldValue) > Double.parseDouble(max)))
throw new OValidationException("The field '" + p.getFullName() + "' is greater than " + max);
else if (p.getType().equals(OType.DATE)) {
try {
if (fieldValue != null
&& ((Date) fieldValue).before(iRecord.getDatabase().getStorage().getConfiguration().getDateFormatInstance()
.parse(max)))
throw new OValidationException("The field '" + p.getFullName() + "' contains the date " + fieldValue
+ " which is after the last acceptable date (" + max + ")");
} catch (ParseException e) {
}
} else if (p.getType().equals(OType.DATETIME)) {
try {
if (fieldValue != null
&& ((Date) fieldValue).before(iRecord.getDatabase().getStorage().getConfiguration().getDateTimeFormatInstance()
.parse(max)))
throw new OValidationException("The field '" + p.getFullName() + "' contains the datetime " + fieldValue
+ " which is after the last acceptable datetime (" + max + ")");
} catch (ParseException e) {
}
} else if ((p.getType().equals(OType.EMBEDDEDLIST) || p.getType().equals(OType.EMBEDDEDSET)
|| p.getType().equals(OType.LINKLIST) || p.getType().equals(OType.LINKSET))
&& (fieldValue != null && ((Collection<?>) fieldValue).size() > Integer.parseInt(max)))
throw new OValidationException("The field '" + p.getFullName() + "' contains more items than " + max + " requested");
}
if (p.isReadonly() && iRecord instanceof ODocument && !iRecord.getRecordVersion().isTombstone()) {
for (String f : ((ODocument) iRecord).getDirtyFields())
if (f.equals(p.getName())) {
// check if the field is actually changed by equal.
// this is due to a limitation in the merge algorithm used server side marking all non simple fields as dirty
Object orgVal = ((ODocument) iRecord).getOriginalValue(f);
boolean simple = fieldValue != null ? OType.isSimpleType(fieldValue) : OType.isSimpleType(orgVal);
if ((simple) || (fieldValue != null && orgVal == null) || (fieldValue == null && orgVal != null)
|| (!fieldValue.equals(orgVal)))
throw new OValidationException("The field '" + p.getFullName()
+ "' is immutable and cannot be altered. Field value is: " + ((ODocument) iRecord).field(f));
}
}
}
protected static void validateType(final OProperty p, final Object value) {
if (value != null)
if (OType.convert(value, p.getLinkedType().getDefaultJavaType()) == null)
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType() + " of type '"
+ p.getLinkedType() + "' but the value is " + value);
}
protected static void validateLink(final OProperty p, final Object fieldValue) {
if (fieldValue == null)
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but contains a null record (probably a deleted record?)");
final ORecord<?> linkedRecord;
if (fieldValue instanceof OIdentifiable)
linkedRecord = ((OIdentifiable) fieldValue).getRecord();
else if (fieldValue instanceof String)
linkedRecord = new ORecordId((String) fieldValue).getRecord();
else
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but the value is not a record or a record-id");
if (linkedRecord != null && p.getLinkedClass() != null) {
if (!(linkedRecord instanceof ODocument))
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType() + " of type '"
+ p.getLinkedClass() + "' but the value is the record " + linkedRecord.getIdentity() + " that is not a document");
final ODocument doc = (ODocument) linkedRecord;
// AT THIS POINT CHECK THE CLASS ONLY IF != NULL BECAUSE IN CASE OF GRAPHS THE RECORD COULD BE PARTIAL
if (doc.getSchemaClass() != null && !p.getLinkedClass().isSuperClassOf(doc.getSchemaClass()))
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType() + " of type '"
+ p.getLinkedClass().getName() + "' but the value is the document " + linkedRecord.getIdentity() + " of class '"
+ doc.getSchemaClass() + "'");
}
}
protected static void validateEmbedded(final OProperty p, final Object fieldValue) {
if (fieldValue instanceof ORecordId)
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but the value is the RecordID " + fieldValue);
else if (fieldValue instanceof OIdentifiable) {
if (((OIdentifiable) fieldValue).getIdentity().isValid())
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but the value is a document with the valid RecordID " + fieldValue);
final OClass embeddedClass = p.getLinkedClass();
if (embeddedClass != null) {
final ORecord<?> rec = ((OIdentifiable) fieldValue).getRecord();
if (!(rec instanceof ODocument))
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " with linked class '" + embeddedClass + "' but the record was not a document");
final ODocument doc = (ODocument) rec;
if (doc.getSchemaClass() == null)
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " with linked class '" + embeddedClass + "' but the record has no class");
if (!(doc.getSchemaClass().isSubClassOf(embeddedClass)))
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " with linked class '" + embeddedClass + "' but the record is of class '" + doc.getSchemaClass().getName()
+ "' that is not a subclass of that");
}
} else
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but an incompatible type is used. Value: " + fieldValue);
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_record_ORecordSchemaAwareAbstract.java
|
2,555 |
public class DiscoveryService extends AbstractLifecycleComponent<DiscoveryService> {
private final TimeValue initialStateTimeout;
private final Discovery discovery;
private volatile boolean initialStateReceived;
@Inject
public DiscoveryService(Settings settings, Discovery discovery) {
super(settings);
this.discovery = discovery;
this.initialStateTimeout = componentSettings.getAsTime("initial_state_timeout", TimeValue.timeValueSeconds(30));
}
@Override
protected void doStart() throws ElasticsearchException {
final CountDownLatch latch = new CountDownLatch(1);
InitialStateDiscoveryListener listener = new InitialStateDiscoveryListener() {
@Override
public void initialStateProcessed() {
latch.countDown();
}
};
discovery.addListener(listener);
try {
discovery.start();
if (initialStateTimeout.millis() > 0) {
try {
logger.trace("waiting for {} for the initial state to be set by the discovery", initialStateTimeout);
if (latch.await(initialStateTimeout.millis(), TimeUnit.MILLISECONDS)) {
logger.trace("initial state set from discovery");
initialStateReceived = true;
} else {
initialStateReceived = false;
logger.warn("waited for {} and no initial state was set by the discovery", initialStateTimeout);
}
} catch (InterruptedException e) {
// ignore
}
}
} finally {
discovery.removeListener(listener);
}
logger.info(discovery.nodeDescription());
}
@Override
protected void doStop() throws ElasticsearchException {
discovery.stop();
}
@Override
protected void doClose() throws ElasticsearchException {
discovery.close();
}
public DiscoveryNode localNode() {
return discovery.localNode();
}
/**
* Returns <tt>true</tt> if the initial state was received within the timeout waiting for it
* on {@link #doStart()}.
*/
public boolean initialStateReceived() {
return initialStateReceived;
}
public String nodeDescription() {
return discovery.nodeDescription();
}
/**
* Publish all the changes to the cluster from the master (can be called just by the master). The publish
* process should not publish this state to the master as well! (the master is sending it...).
* <p/>
* The {@link org.elasticsearch.discovery.Discovery.AckListener} allows to acknowledge the publish
* event based on the response gotten from all nodes
*/
public void publish(ClusterState clusterState, Discovery.AckListener ackListener) {
if (lifecycle.started()) {
discovery.publish(clusterState, ackListener);
}
}
public static String generateNodeId(Settings settings) {
String seed = settings.get("discovery.id.seed");
if (seed != null) {
Strings.randomBase64UUID(new Random(Long.parseLong(seed)));
}
return Strings.randomBase64UUID();
}
}
| 1no label
|
src_main_java_org_elasticsearch_discovery_DiscoveryService.java
|
635 |
public final class ClientMembershipEvent implements IdentifiedDataSerializable {
public static final int MEMBER_ADDED = MembershipEvent.MEMBER_ADDED;
public static final int MEMBER_REMOVED = MembershipEvent.MEMBER_REMOVED;
public static final int MEMBER_ATTRIBUTE_CHANGED = MembershipEvent.MEMBER_ATTRIBUTE_CHANGED;
private Member member;
private MemberAttributeChange memberAttributeChange;
private int eventType;
public ClientMembershipEvent() {
}
public ClientMembershipEvent(Member member, int eventType) {
this(member, null, eventType);
}
public ClientMembershipEvent(Member member, MemberAttributeChange memberAttributeChange) {
this(member, memberAttributeChange, MEMBER_ATTRIBUTE_CHANGED);
}
private ClientMembershipEvent(Member member, MemberAttributeChange memberAttributeChange, int eventType) {
this.member = member;
this.eventType = eventType;
this.memberAttributeChange = memberAttributeChange;
}
/**
* Returns the membership event type; #MEMBER_ADDED or #MEMBER_REMOVED
*
* @return the membership event type
*/
public int getEventType() {
return eventType;
}
/**
* Returns the removed or added member.
*
* @return member which is removed/added
*/
public Member getMember() {
return member;
}
/**
* Returns the member attribute chance operation to execute
* if event type is {@link #MEMBER_ATTRIBUTE_CHANGED}.
*
* @return MemberAttributeChange to execute
*/
public MemberAttributeChange getMemberAttributeChange() {
return memberAttributeChange;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
member.writeData(out);
out.writeInt(eventType);
out.writeBoolean(memberAttributeChange != null);
if (memberAttributeChange != null) {
memberAttributeChange.writeData(out);
}
}
@Override
public void readData(ObjectDataInput in) throws IOException {
member = new MemberImpl();
member.readData(in);
eventType = in.readInt();
if (in.readBoolean()) {
memberAttributeChange = new MemberAttributeChange();
memberAttributeChange.readData(in);
}
}
@Override
public int getFactoryId() {
return ClusterDataSerializerHook.F_ID;
}
@Override
public int getId() {
return ClusterDataSerializerHook.MEMBERSHIP_EVENT;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_cluster_client_ClientMembershipEvent.java
|
469 |
public interface ClientClusterService {
MemberImpl getMember(Address address);
MemberImpl getMember(String uuid);
Collection<MemberImpl> getMemberList();
Address getMasterAddress();
int getSize();
long getClusterTime();
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_spi_ClientClusterService.java
|
306 |
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ClientMapLockTest {
static HazelcastInstance client;
static HazelcastInstance server;
@BeforeClass
public static void init() {
server = Hazelcast.newHazelcastInstance();
client = HazelcastClient.newHazelcastClient();
}
@AfterClass
public static void destroy() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test(expected = NullPointerException.class)
public void testisLocked_whenKeyNull_fromSameThread() {
final IMap map = client.getMap(randomString());
map.isLocked(null);
}
@Test
public void testisLocked_whenKeyAbsent_fromSameThread() {
final IMap map = client.getMap(randomString());
boolean isLocked = map.isLocked("NOT_THERE");
assertFalse(isLocked);
}
@Test
public void testisLocked_whenKeyPresent_fromSameThread() {
final IMap map = client.getMap(randomString());
final Object key ="key";
map.put(key, "value");
final boolean isLocked = map.isLocked(key);
assertFalse(isLocked);
}
@Test(expected = NullPointerException.class)
public void testLock_whenKeyNull_fromSameThread() {
final IMap map = client.getMap(randomString());
map.lock(null);
}
@Test
public void testLock_whenKeyAbsent_fromSameThread() {
final IMap map = client.getMap(randomString());
final Object key = "key";
map.lock(key);
assertTrue(map.isLocked(key));
}
@Test
public void testLock_whenKeyPresent_fromSameThread() {
final IMap map = client.getMap(randomString());
final Object key ="key";
map.put(key, "value");
map.lock(key);
assertTrue(map.isLocked(key));
}
@Test
public void testLock_whenLockedRepeatedly_fromSameThread() {
final IMap map = client.getMap(randomString());
final Object key ="key";
map.lock(key);
map.lock(key);
assertTrue(map.isLocked(key));
}
@Test(expected = NullPointerException.class)
public void testUnLock_whenKeyNull_fromSameThread() {
final IMap map = client.getMap(randomString());
map.unlock(null);
}
@Test(expected = IllegalMonitorStateException.class)
public void testUnLock_whenKeyNotPresentAndNotLocked_fromSameThread() {
final IMap map = client.getMap(randomString());
map.unlock("NOT_THERE_OR_LOCKED");
}
@Test(expected = IllegalMonitorStateException.class)
public void testUnLock_whenKeyPresentAndNotLocked_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
map.put(key, "value");
map.unlock(key);
}
@Test
public void testUnLock_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
map.lock(key);
map.unlock(key);
assertFalse(map.isLocked(key));
}
@Test
public void testUnLock_whenKeyLockedRepeatedly_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
map.lock(key);
map.lock(key);
map.unlock(key);
assertTrue(map.isLocked(key));
}
@Test(expected = NullPointerException.class)
public void testForceUnlock_whenKeyNull_fromSameThread() {
final IMap map = client.getMap(randomString());
map.forceUnlock(null);
}
@Test
public void testForceUnlock_whenKeyNotPresentAndNotLocked_fromSameThread() {
final IMap map = client.getMap(randomString());
map.forceUnlock("NOT_THERE_OR_LOCKED");
}
@Test
public void testForceUnlock_whenKeyPresentAndNotLocked_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
map.put(key, "value");
map.forceUnlock(key);
}
@Test
public void testForceUnlock_fromSameThread(){
final IMap map = client.getMap(randomString());
final String key = "key";
map.lock(key);
map.forceUnlock(key);
assertFalse(map.isLocked(key));
}
@Test
public void testForceUnLock_whenKeyLockedRepeatedly_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
map.lock(key);
map.lock(key);
map.unlock(key);
assertTrue(map.isLocked(key));
}
@Test
public void testLockAbsentKey_thenPutKey_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
final String value = "value";
map.lock(key);
map.put(key, value);
map.unlock(key);
assertEquals(value, map.get(key));
}
@Test
public void testLockAbsentKey_thenPutKeyIfAbsent_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
final String value = "value";
map.lock(key);
map.putIfAbsent(key, value);
map.unlock(key);
assertEquals(value, map.get(key));
}
@Test
public void testLockPresentKey_thenPutKey_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
final String oldValue = "oldValue";
final String newValue = "newValue";
map.put(key, oldValue);
map.lock(key);
map.put(key, newValue);
map.unlock(key);
assertEquals(newValue, map.get(key));
}
@Test
public void testLockPresentKey_thenSetKey_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
final String oldValue = "oldValue";
final String newValue = "newValue";
map.put(key, oldValue);
map.lock(key);
map.set(key, newValue);
map.unlock(key);
assertEquals(newValue, map.get(key));
}
@Test
public void testLockPresentKey_thenReplace_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
final String oldValue = "oldValue";
final String newValue = "newValue";
map.put(key, oldValue);
map.lock(key);
map.replace(key, newValue);
map.unlock(key);
assertEquals(newValue, map.get(key));
}
@Test
public void testLockPresentKey_thenRemoveKey_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
final String oldValue = "oldValue";
map.put(key, oldValue);
map.lock(key);
map.remove(key);
map.unlock(key);
assertFalse(map.isLocked(key));
assertEquals(null, map.get(key));
}
@Test
public void testLockPresentKey_thenDeleteKey_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
final String oldValue = "oldValue";
map.put(key, oldValue);
map.lock(key);
map.delete(key);
map.unlock(key);
assertFalse(map.isLocked(key));
assertEquals(null, map.get(key));
}
@Test
public void testLockPresentKey_thenEvictKey_fromSameThread() {
final IMap map = client.getMap(randomString());
final String key = "key";
final String oldValue = "oldValue";
map.put(key, oldValue);
map.lock(key);
map.evict(key);
map.unlock(key);
assertFalse(map.isLocked(key));
assertEquals(null, map.get(key));
}
@Test
public void testLockKey_thenPutAndCheckKeySet_fromOtherThread() throws InterruptedException {
final IMap map = client.getMap(randomString());
final String key = "key";
final String value = "oldValue";
final CountDownLatch putWhileLocked = new CountDownLatch(1);
final CountDownLatch checkingKeySet = new CountDownLatch(1);
new Thread() {
public void run() {
try {
map.lock(key);
map.put(key, value);
putWhileLocked.countDown();
checkingKeySet.await();
map.unlock(key);
}catch(Exception e){}
}
}.start();
putWhileLocked.await();
Set keySet = map.keySet();
assertFalse(keySet.isEmpty());
checkingKeySet.countDown();
}
@Test
public void testLockKey_thenPutAndGet_fromOtherThread() throws InterruptedException {
final IMap map = client.getMap(randomString());
final String key = "key";
final String value = "oldValue";
final CountDownLatch putWhileLocked = new CountDownLatch(1);
final CountDownLatch checkingKeySet = new CountDownLatch(1);
new Thread() {
public void run() {
try {
map.lock(key);
map.put(key, value);
putWhileLocked.countDown();
checkingKeySet.await();
map.unlock(key);
}catch(Exception e){}
}
}.start();
putWhileLocked.await();
assertEquals(value, map.get(key));
checkingKeySet.countDown();
}
@Test
public void testLockKey_thenRemoveAndGet_fromOtherThread() throws InterruptedException {
final IMap map = client.getMap(randomString());
final String key = "key";
final String value = "oldValue";
final CountDownLatch removeWhileLocked = new CountDownLatch(1);
final CountDownLatch checkingKey = new CountDownLatch(1);
map.put(key, value);
new Thread() {
public void run() {
try {
map.lock(key);
map.remove(key);
removeWhileLocked.countDown();
checkingKey.await();
map.unlock(key);
}catch(Exception e){}
}
}.start();
removeWhileLocked.await();
assertEquals(null, map.get(key));
checkingKey.countDown();
}
@Test
public void testLockKey_thenTryPutOnKey() throws Exception {
final IMap map = client.getMap(randomString());
final String key = "key";
final String value = "value";
map.put(key, value);
map.lock(key);
final CountDownLatch tryPutReturned = new CountDownLatch(1);
new Thread() {
public void run() {
map.tryPut(key, "NEW_VALUE", 1, TimeUnit.SECONDS);
tryPutReturned.countDown();
}
}.start();
assertOpenEventually(tryPutReturned);
assertEquals(value, map.get(key));
}
@Test
public void testLockTTLExpires_usingIsLocked() throws Exception {
final IMap map = client.getMap(randomString());
final String key = "key";
map.lock(key, 3, TimeUnit.SECONDS);
final boolean isLockedBeforeSleep = map.isLocked(key);
sleepSeconds(4);
final boolean isLockedAfterSleep = map.isLocked(key);
assertTrue(isLockedBeforeSleep);
assertFalse(isLockedAfterSleep);
}
@Test
public void testLockTTLExpires() throws Exception {
final IMap map = client.getMap(randomString());
final String key = "key";
final String oldValue = "value";
final String newValue = "NEW_VALUE";
map.put(key, oldValue);
map.lock(key, 4, TimeUnit.SECONDS);
final CountDownLatch tryPutReturned = new CountDownLatch(1);
new Thread() {
public void run() {
map.tryPut(key, newValue, 8, TimeUnit.SECONDS);
tryPutReturned.countDown();
}
}.start();
assertOpenEventually(tryPutReturned);
assertEquals(newValue, map.get(key));
}
@Test
public void testLockTTLExpires_onAbsentKey() throws Exception {
final IMap map = client.getMap(randomString());
final String key = "key";
final String value = "value";
map.lock(key, 4, TimeUnit.SECONDS);
final CountDownLatch tryPutReturned = new CountDownLatch(1);
new Thread() {
public void run() {
map.tryPut(key, value, 8, TimeUnit.SECONDS);
tryPutReturned.countDown();
}
}.start();
assertOpenEventually(tryPutReturned);
assertEquals(value, map.get(key));
}
@Test
public void testisLocked_whenLockedFromOtherThread() throws Exception {
final IMap map = client.getMap(randomString());
final String key = "key";
final CountDownLatch lockedLatch = new CountDownLatch(1);
new Thread() {
public void run() {
map.lock(key);
lockedLatch.countDown();
}
}.start();
assertOpenEventually(lockedLatch);
assertTrue(map.isLocked(key));
}
@Test(expected = IllegalMonitorStateException.class)
public void testUnLocked_whenLockedFromOtherThread() throws Exception {
final IMap map = client.getMap(randomString());
final String key = "key";
final CountDownLatch lockedLatch = new CountDownLatch(1);
new Thread() {
public void run() {
map.lock(key);
lockedLatch.countDown();
}
}.start();
assertOpenEventually(lockedLatch);
map.unlock(key);
}
@Test
public void testForceUnLocked_whenLockedFromOtherThread() throws Exception {
final IMap map = client.getMap(randomString());
final String key = "key";
final CountDownLatch lockedLatch = new CountDownLatch(1);
new Thread() {
public void run() {
map.lock(key);
map.lock(key);
lockedLatch.countDown();
}
}.start();
lockedLatch.await(10, TimeUnit.SECONDS);
map.forceUnlock(key);
assertFalse(map.isLocked(key));
}
@Test
public void testTryPut_whenLockedFromOtherThread() throws Exception {
final IMap map = client.getMap(randomString());
final String key = "key";
final CountDownLatch lockedLatch = new CountDownLatch(1);
new Thread() {
public void run() {
map.lock(key);
lockedLatch.countDown();
}
}.start();
assertOpenEventually(lockedLatch);
assertFalse(map.tryPut(key, "value", 1, TimeUnit.SECONDS));
}
@Test
public void testTryRemove_whenLockedFromOtherThread() throws Exception {
final IMap map = client.getMap(randomString());
final String key = "key";
final CountDownLatch lockedLatch = new CountDownLatch(1);
new Thread() {
public void run() {
map.lock(key);
lockedLatch.countDown();
}
}.start();
assertOpenEventually(lockedLatch);
assertFalse(map.tryRemove(key, 1, TimeUnit.SECONDS));
}
@Test
public void testTryLock_whenLockedFromOtherThread() throws Exception {
final IMap map = client.getMap(randomString());
final String key = "key";
final CountDownLatch lockedLatch = new CountDownLatch(1);
new Thread() {
public void run() {
map.lock(key);
lockedLatch.countDown();
}
}.start();
assertOpenEventually(lockedLatch);
assertFalse(map.tryLock(key));
}
@Test
public void testLock_whenUnLockedFromOtherThread() throws Exception {
final IMap map = client.getMap(randomString());
final String key = "key";
map.lock(key);
final CountDownLatch beforeLock = new CountDownLatch(1);
final CountDownLatch afterLock = new CountDownLatch(1);
new Thread() {
public void run() {
beforeLock.countDown();
map.lock(key);
afterLock.countDown();
}
}.start();
beforeLock.await();
map.unlock(key);
assertOpenEventually(afterLock);
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapLockTest.java
|
600 |
public class GetSettingsAction extends IndicesAction<GetSettingsRequest, GetSettingsResponse, GetSettingsRequestBuilder> {
public static final GetSettingsAction INSTANCE = new GetSettingsAction();
public static final String NAME = "indices/settings/get";
public GetSettingsAction() {
super(NAME);
}
@Override
public GetSettingsRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new GetSettingsRequestBuilder((InternalGenericClient) client);
}
@Override
public GetSettingsResponse newResponse() {
return new GetSettingsResponse();
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_settings_get_GetSettingsAction.java
|
72 |
class AssignToLocalProposal extends LocalProposal {
protected DocumentChange createChange(IDocument document, Node expanse,
Integer stopIndex) {
DocumentChange change =
new DocumentChange("Assign to Local", document);
change.setEdit(new MultiTextEdit());
change.addEdit(new InsertEdit(offset, "value " + initialName + " = "));
String terminal = expanse.getEndToken().getText();
if (!terminal.equals(";")) {
change.addEdit(new InsertEdit(stopIndex+1, ";"));
exitPos = stopIndex+2;
}
else {
exitPos = stopIndex+1;
}
return change;
}
public AssignToLocalProposal(Tree.CompilationUnit cu,
Node node, int currentOffset) {
super(cu, node, currentOffset);
}
protected void addLinkedPositions(IDocument document, Unit unit)
throws BadLocationException {
ProposalPosition typePosition =
new ProposalPosition(document, offset, 5, 1,
getSupertypeProposals(offset, unit,
type, true, "value"));
ProposalPosition namePosition =
new ProposalPosition(document, offset+6, initialName.length(), 0,
getNameProposals(offset, 1, nameProposals));
LinkedMode.addLinkedPosition(linkedModeModel, typePosition);
LinkedMode.addLinkedPosition(linkedModeModel, namePosition);
}
@Override
public String getDisplayString() {
return "Assign expression to new local";
}
static void addAssignToLocalProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals,
Node node, int currentOffset) {
AssignToLocalProposal prop =
new AssignToLocalProposal(cu, node, currentOffset);
if (prop.isEnabled()) {
proposals.add(prop);
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AssignToLocalProposal.java
|
236 |
@Service("blModuleConfigurationService")
public class ModuleConfigurationServiceImpl implements ModuleConfigurationService {
@Resource(name = "blModuleConfigurationDao")
protected ModuleConfigurationDao moduleConfigDao;
@Override
public ModuleConfiguration findById(Long id) {
return moduleConfigDao.readById(id);
}
@Override
@Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER)
public ModuleConfiguration save(ModuleConfiguration config) {
return moduleConfigDao.save(config);
}
@Override
@Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER)
public void delete(ModuleConfiguration config) {
moduleConfigDao.delete(config);
}
@Override
public List<ModuleConfiguration> findActiveConfigurationsByType(ModuleConfigurationType type) {
return moduleConfigDao.readActiveByType(type);
}
@Override
public List<ModuleConfiguration> findAllConfigurationByType(ModuleConfigurationType type) {
return moduleConfigDao.readAllByType(type);
}
@Override
public List<ModuleConfiguration> findByType(Class<? extends ModuleConfiguration> type) {
return moduleConfigDao.readByType(type);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_config_service_ModuleConfigurationServiceImpl.java
|
80 |
public static class FieldOrder {
// General Fields
public static final int NAME = 1000;
public static final int URL = 2000;
public static final int TITLE = 3000;
public static final int ALT_TEXT = 4000;
public static final int MIME_TYPE = 5000;
public static final int FILE_EXTENSION = 6000;
public static final int FILE_SIZE = 7000;
// Used by subclasses to know where the last field is.
public static final int LAST = 7000;
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetImpl.java
|
719 |
public abstract class CollectionService implements ManagedService, RemoteService,
EventPublishingService<CollectionEvent, ItemListener>, TransactionalService, MigrationAwareService {
protected NodeEngine nodeEngine;
protected CollectionService(NodeEngine nodeEngine) {
this.nodeEngine = nodeEngine;
}
@Override
public void init(NodeEngine nodeEngine, Properties properties) {
}
@Override
public void reset() {
getContainerMap().clear();
}
@Override
public void shutdown(boolean terminate) {
reset();
}
@Override
public void destroyDistributedObject(String name) {
getContainerMap().remove(name);
nodeEngine.getEventService().deregisterAllListeners(getServiceName(), name);
}
public abstract CollectionContainer getOrCreateContainer(String name, boolean backup);
public abstract Map<String, ? extends CollectionContainer> getContainerMap();
public abstract String getServiceName();
@Override
public void dispatchEvent(CollectionEvent event, ItemListener listener) {
ItemEvent itemEvent = new ItemEvent(event.name, event.eventType, nodeEngine.toObject(event.data),
nodeEngine.getClusterService().getMember(event.caller));
if (event.eventType.equals(ItemEventType.ADDED)) {
listener.itemAdded(itemEvent);
} else {
listener.itemRemoved(itemEvent);
}
}
@Override
public void rollbackTransaction(String transactionId) {
final Set<String> collectionNames = getContainerMap().keySet();
InternalPartitionService partitionService = nodeEngine.getPartitionService();
OperationService operationService = nodeEngine.getOperationService();
for (String name : collectionNames) {
int partitionId = partitionService.getPartitionId(StringPartitioningStrategy.getPartitionKey(name));
Operation operation = new CollectionTransactionRollbackOperation(name, transactionId)
.setPartitionId(partitionId)
.setService(this)
.setNodeEngine(nodeEngine);
operationService.executeOperation(operation);
}
}
@Override
public void beforeMigration(PartitionMigrationEvent event) {
}
public Map<String, CollectionContainer> getMigrationData(PartitionReplicationEvent event) {
Map<String, CollectionContainer> migrationData = new HashMap<String, CollectionContainer>();
InternalPartitionService partitionService = nodeEngine.getPartitionService();
for (Map.Entry<String, ? extends CollectionContainer> entry : getContainerMap().entrySet()) {
String name = entry.getKey();
int partitionId = partitionService.getPartitionId(StringPartitioningStrategy.getPartitionKey(name));
CollectionContainer container = entry.getValue();
if (partitionId == event.getPartitionId() && container.getConfig().getTotalBackupCount() >= event.getReplicaIndex()) {
migrationData.put(name, container);
}
}
return migrationData;
}
@Override
public void commitMigration(PartitionMigrationEvent event) {
if (event.getMigrationEndpoint() == MigrationEndpoint.SOURCE) {
clearMigrationData(event.getPartitionId());
}
}
@Override
public void rollbackMigration(PartitionMigrationEvent event) {
if (event.getMigrationEndpoint() == MigrationEndpoint.DESTINATION) {
clearMigrationData(event.getPartitionId());
}
}
@Override
public void clearPartitionReplica(int partitionId) {
clearMigrationData(partitionId);
}
private void clearMigrationData(int partitionId) {
final Set<? extends Map.Entry<String, ? extends CollectionContainer>> entrySet = getContainerMap().entrySet();
final Iterator<? extends Map.Entry<String, ? extends CollectionContainer>> iterator = entrySet.iterator();
InternalPartitionService partitionService = nodeEngine.getPartitionService();
while (iterator.hasNext()) {
final Map.Entry<String, ? extends CollectionContainer> entry = iterator.next();
final String name = entry.getKey();
final CollectionContainer container = entry.getValue();
int containerPartitionId = partitionService.getPartitionId(StringPartitioningStrategy.getPartitionKey(name));
if (containerPartitionId == partitionId) {
container.destroy();
iterator.remove();
}
}
}
public void addContainer(String name, CollectionContainer container) {
final Map map = getContainerMap();
map.put(name, container);
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionService.java
|
517 |
public class IndicesExistsResponse extends ActionResponse {
private boolean exists;
IndicesExistsResponse() {
}
public IndicesExistsResponse(boolean exists) {
this.exists = exists;
}
public boolean isExists() {
return this.exists;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
exists = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(exists);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_exists_indices_IndicesExistsResponse.java
|
248 |
@Test
public class ODefaultCacheTest {
public void enabledAfterStartup() {
// Given cache created
// And not started
// And not enabled
OCache sut = newCache();
// When started
sut.startup();
// Then it should be enabled
assertTrue(sut.isEnabled());
}
public void disabledAfterShutdown() {
// Given running cache
OCache sut = runningCache();
// When started
sut.shutdown();
// Then it should be disabled
assertFalse(sut.isEnabled());
}
public void disablesOnlyIfWasEnabled() {
// Given enabled cache
OCache sut = enabledCache();
// When disabled more than once
boolean disableConfirmed = sut.disable();
boolean disableNotConfirmed = sut.disable();
// Then should return confirmation of switching from enabled to disabled state for first time
// And no confirmation on subsequent disables
assertTrue(disableConfirmed);
assertFalse(disableNotConfirmed);
}
public void enablesOnlyIfWasDisabled() {
// Given disabled cache
OCache sut = newCache();
// When enabled more than once
boolean enableConfirmed = sut.enable();
boolean enableNotConfirmed = sut.enable();
// Then should return confirmation of switching from disabled to enabled state for first time
// And no confirmation on subsequent enables
assertTrue(enableConfirmed);
assertFalse(enableNotConfirmed);
}
public void doesNothingWhileDisabled() {
// Given cache created
// And not started
// And not enabled
OCache sut = new ODefaultCache(null, 1);
// When any operation called on it
ODocument record = new ODocument();
ORID recordId = record.getIdentity();
sut.put(record);
ORecordInternal<?> recordGot = sut.get(recordId);
int cacheSizeAfterPut = sut.size();
ORecordInternal<?> recordRemoved = sut.remove(recordId);
int cacheSizeAfterRemove = sut.size();
// Then it has no effect on cache's state
assertEquals(sut.isEnabled(), false, "Cache should be disabled at creation");
assertEquals(recordGot, null, "Cache should return empty records while disabled");
assertEquals(recordRemoved, null, "Cache should return empty records while disabled");
assertEquals(cacheSizeAfterPut, 0, "Cache should ignore insert while disabled");
assertEquals(cacheSizeAfterRemove, cacheSizeAfterPut, "Cache should ignore remove while disabled");
}
public void hasZeroSizeAfterClear() {
// Given enabled non-empty cache
OCache sut = enabledNonEmptyCache();
// When cleared
sut.clear();
// Then size of cache should be zero
assertEquals(sut.size(), 0, "Cache was not cleaned up");
}
public void providesAccessToAllKeysInCache() {
// Given enabled non-empty cache
OCache sut = enabledNonEmptyCache();
// When asked for keys
Collection<ORID> keys = sut.keys();
// Then keys count should be same as size of cache
// And records available for keys
assertEquals(keys.size(), sut.size(), "Cache provided not all keys?");
for (ORID key : keys) {
assertNotNull(sut.get(key));
}
}
public void storesRecordsUsingTheirIdentity() {
// Given an enabled cache
OCache sut = enabledCache();
// When new record put into
ORecordId id = new ORecordId(1, OClusterPositionFactory.INSTANCE.valueOf(1));
ODocument record = new ODocument(id);
sut.put(record);
// Then it can be retrieved later by it's id
assertEquals(sut.get(id), record);
}
public void storesRecordsOnlyOnceForEveryIdentity() {
// Given an enabled cache
OCache sut = enabledCache();
final int initialSize = sut.size();
// When some records with same identity put in several times
ODocument first = new ODocument(new ORecordId(1, OClusterPositionFactory.INSTANCE.valueOf(1)));
ODocument last = new ODocument(new ORecordId(1, OClusterPositionFactory.INSTANCE.valueOf(1)));
sut.put(first);
sut.put(last);
// Then cache ends up storing only one item
assertEquals(sut.size(), initialSize + 1);
}
public void removesOnlyOnce() {
// Given an enabled cache with records in it
OCache sut = enabledCache();
ORecordId id = new ORecordId(1, OClusterPositionFactory.INSTANCE.valueOf(1));
ODocument record = new ODocument(id);
sut.put(record);
sut.remove(id);
// When removing already removed record
ORecordInternal<?> removedSecond = sut.remove(id);
// Then empty result returned
assertNull(removedSecond);
}
public void storesNoMoreElementsThanSpecifiedLimit() {
// Given an enabled cache
OCache sut = enabledCache();
// When stored more distinct elements than cache limit allows
for (int i = sut.limit() + 2; i > 0; i--)
sut.put(new ODocument(new ORecordId(i, OClusterPositionFactory.INSTANCE.valueOf(i))));
// Then size of cache should be exactly as it's limit
assertEquals(sut.size(), sut.limit(), "Cache doesn't meet limit requirements");
}
private ODefaultCache newCache() {
return new ODefaultCache(null, 5);
}
private OCache enabledCache() {
ODefaultCache cache = newCache();
cache.enable();
return cache;
}
private OCache enabledNonEmptyCache() {
OCache cache = enabledCache();
cache.put(new ODocument(new ORecordId(1, OClusterPositionFactory.INSTANCE.valueOf(1))));
cache.put(new ODocument(new ORecordId(2, OClusterPositionFactory.INSTANCE.valueOf(2))));
return cache;
}
private OCache runningCache() {
ODefaultCache cache = newCache();
cache.startup();
return cache;
}
}
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_cache_ODefaultCacheTest.java
|
560 |
public class OClassIndexManager extends ODocumentHookAbstract {
private final Set<String> lockedIndexes = new HashSet<String>();
public OClassIndexManager() {
}
public DISTRIBUTED_EXECUTION_MODE getDistributedExecutionMode() {
return DISTRIBUTED_EXECUTION_MODE.TARGET_NODE;
}
@Override
public RESULT onRecordBeforeCreate(ODocument iDocument) {
checkIndexesAndAquireLock(iDocument, BEFORE_CREATE);
return RESULT.RECORD_NOT_CHANGED;
}
@Override
public RESULT onRecordBeforeReplicaAdd(ODocument iDocument) {
checkIndexesAndAquireLock(iDocument, BEFORE_CREATE);
return RESULT.RECORD_NOT_CHANGED;
}
@Override
public void onRecordAfterCreate(ODocument iDocument) {
addIndexesEntriesAndReleaseLock(iDocument);
}
@Override
public void onRecordAfterReplicaAdd(ODocument iDocument) {
addIndexesEntriesAndReleaseLock(iDocument);
}
private void addIndexesEntriesAndReleaseLock(ODocument document) {
document = checkForLoading(document);
// STORE THE RECORD IF NEW, OTHERWISE ITS RID
final OIdentifiable rid = document.getIdentity().isPersistent() ? document.placeholder() : document;
final OClass cls = document.getSchemaClass();
if (cls != null) {
final Collection<OIndex<?>> indexes = cls.getIndexes();
for (final OIndex<?> index : indexes) {
final Object key = index.getDefinition().getDocumentValueToIndex(document);
// SAVE A COPY TO AVOID PROBLEM ON RECYCLING OF THE RECORD
if (key instanceof Collection) {
for (final Object keyItem : (Collection<?>) key)
if (keyItem != null)
index.put(keyItem, rid);
} else if (key != null)
index.put(key, rid);
}
releaseModificationLock(document, indexes);
}
}
@Override
public void onRecordCreateFailed(ODocument iDocument) {
releaseModificationLock(iDocument);
}
@Override
public void onRecordReplicaAddFailed(ODocument iDocument) {
releaseModificationLock(iDocument);
}
@Override
public void onRecordCreateReplicated(ODocument iDocument) {
releaseModificationLock(iDocument);
}
@Override
public RESULT onRecordBeforeUpdate(ODocument iDocument) {
checkIndexesAndAquireLock(iDocument, BEFORE_UPDATE);
return RESULT.RECORD_NOT_CHANGED;
}
@Override
public RESULT onRecordBeforeReplicaUpdate(ODocument iDocument) {
checkIndexesAndAquireLock(iDocument, BEFORE_UPDATE);
return RESULT.RECORD_NOT_CHANGED;
}
@Override
public void onRecordAfterUpdate(ODocument iDocument) {
updateIndexEntries(iDocument);
}
@Override
public void onRecordAfterReplicaUpdate(ODocument iDocument) {
updateIndexEntries(iDocument);
}
private void updateIndexEntries(ODocument iDocument) {
iDocument = checkForLoading(iDocument);
final OClass cls = iDocument.getSchemaClass();
if (cls == null)
return;
final Collection<OIndex<?>> indexes = cls.getIndexes();
if (!indexes.isEmpty()) {
final Set<String> dirtyFields = new HashSet<String>(Arrays.asList(iDocument.getDirtyFields()));
if (!dirtyFields.isEmpty()) {
for (final OIndex<?> index : indexes) {
if (index.getDefinition() instanceof OCompositeIndexDefinition)
processCompositeIndexUpdate(index, dirtyFields, iDocument);
else
processSingleIndexUpdate(index, dirtyFields, iDocument);
}
}
}
releaseModificationLock(iDocument, indexes);
if (iDocument.isTrackingChanges()) {
iDocument.setTrackingChanges(false);
iDocument.setTrackingChanges(true);
}
}
@Override
public void onRecordUpdateFailed(ODocument iDocument) {
releaseModificationLock(iDocument);
}
@Override
public void onRecordUpdateReplicated(ODocument iDocument) {
releaseModificationLock(iDocument);
}
@Override
public void onRecordReplicaUpdateFailed(ODocument iDocument) {
releaseModificationLock(iDocument);
}
@Override
public RESULT onRecordBeforeDelete(final ODocument iDocument) {
final ORecordVersion version = iDocument.getRecordVersion(); // Cache the transaction-provided value
if (iDocument.fields() == 0) {
// FORCE LOADING OF CLASS+FIELDS TO USE IT AFTER ON onRecordAfterDelete METHOD
iDocument.reload();
if (version.getCounter() > -1 && iDocument.getRecordVersion().compareTo(version) != 0) // check for record version errors
if (OFastConcurrentModificationException.enabled())
throw OFastConcurrentModificationException.instance();
else
throw new OConcurrentModificationException(iDocument.getIdentity(), iDocument.getRecordVersion(), version,
ORecordOperation.DELETED);
}
acquireModificationLock(iDocument.getSchemaClass() != null ? iDocument.getSchemaClass().getIndexes() : null);
return RESULT.RECORD_NOT_CHANGED;
}
@Override
public RESULT onRecordBeforeReplicaDelete(ODocument iDocument) {
checkForLoading(iDocument);
acquireModificationLock(iDocument.getSchemaClass() != null ? iDocument.getSchemaClass().getIndexes() : null);
return RESULT.RECORD_NOT_CHANGED;
}
@Override
public void onRecordAfterDelete(final ODocument iDocument) {
deleteIndexEntries(iDocument);
}
@Override
public void onRecordAfterReplicaDelete(ODocument iDocument) {
deleteIndexEntries(iDocument);
}
private void deleteIndexEntries(ODocument iDocument) {
final OClass cls = iDocument.getSchemaClass();
if (cls == null)
return;
final Collection<OIndex<?>> indexes = new ArrayList<OIndex<?>>(cls.getIndexes());
if (!indexes.isEmpty()) {
final Set<String> dirtyFields = new HashSet<String>(Arrays.asList(iDocument.getDirtyFields()));
if (!dirtyFields.isEmpty()) {
// REMOVE INDEX OF ENTRIES FOR THE OLD VALUES
final Iterator<OIndex<?>> indexIterator = indexes.iterator();
while (indexIterator.hasNext()) {
final OIndex<?> index = indexIterator.next();
final boolean result;
if (index.getDefinition() instanceof OCompositeIndexDefinition)
result = processCompositeIndexDelete(index, dirtyFields, iDocument);
else
result = processSingleIndexDelete(index, dirtyFields, iDocument);
if (result)
indexIterator.remove();
}
}
// REMOVE INDEX OF ENTRIES FOR THE NON CHANGED ONLY VALUES
for (final OIndex<?> index : indexes) {
final Object key = index.getDefinition().getDocumentValueToIndex(iDocument);
deleteIndexKey(index, iDocument, key);
}
}
releaseModificationLock(iDocument, indexes);
if (iDocument.isTrackingChanges()) {
iDocument.setTrackingChanges(false);
iDocument.setTrackingChanges(true);
}
}
@Override
public void onRecordDeleteFailed(ODocument iDocument) {
releaseModificationLock(iDocument);
}
@Override
public void onRecordDeleteReplicated(ODocument iDocument) {
releaseModificationLock(iDocument);
}
@Override
public void onRecordReplicaDeleteFailed(ODocument iDocument) {
releaseModificationLock(iDocument);
}
private static void processCompositeIndexUpdate(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
final OCompositeIndexDefinition indexDefinition = (OCompositeIndexDefinition) index.getDefinition();
final List<String> indexFields = indexDefinition.getFields();
final String multiValueField = indexDefinition.getMultiValueField();
for (final String indexField : indexFields) {
if (dirtyFields.contains(indexField)) {
final List<Object> origValues = new ArrayList<Object>(indexFields.size());
for (final String field : indexFields) {
if (!field.equals(multiValueField))
if (dirtyFields.contains(field)) {
origValues.add(iRecord.getOriginalValue(field));
} else {
origValues.add(iRecord.<Object> field(field));
}
}
if (multiValueField == null) {
final Object origValue = indexDefinition.createValue(origValues);
final Object newValue = indexDefinition.getDocumentValueToIndex(iRecord);
if (origValue != null)
index.remove(origValue, iRecord);
if (newValue != null)
index.put(newValue, iRecord.placeholder());
} else {
final OMultiValueChangeTimeLine<?, ?> multiValueChangeTimeLine = iRecord.getCollectionTimeLine(multiValueField);
if (multiValueChangeTimeLine == null) {
if (dirtyFields.contains(multiValueField))
origValues.add(indexDefinition.getMultiValueDefinitionIndex(), iRecord.getOriginalValue(multiValueField));
else
origValues.add(indexDefinition.getMultiValueDefinitionIndex(), iRecord.field(multiValueField));
final Object origValue = indexDefinition.createValue(origValues);
final Object newValue = indexDefinition.getDocumentValueToIndex(iRecord);
processIndexUpdateFieldAssignment(index, iRecord, origValue, newValue);
} else {
if (dirtyFields.size() == 1) {
final Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
final Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();
for (OMultiValueChangeEvent<?, ?> changeEvent : multiValueChangeTimeLine.getMultiValueChangeEvents()) {
indexDefinition.processChangeEvent(changeEvent, keysToAdd, keysToRemove, origValues.toArray());
}
for (final Object keyToRemove : keysToRemove.keySet())
index.remove(keyToRemove, iRecord);
for (final Object keyToAdd : keysToAdd.keySet())
index.put(keyToAdd, iRecord.placeholder());
} else {
final OTrackedMultiValue fieldValue = iRecord.field(multiValueField);
final Object restoredMultiValue = fieldValue
.returnOriginalState(multiValueChangeTimeLine.getMultiValueChangeEvents());
origValues.add(indexDefinition.getMultiValueDefinitionIndex(), restoredMultiValue);
final Object origValue = indexDefinition.createValue(origValues);
final Object newValue = indexDefinition.getDocumentValueToIndex(iRecord);
processIndexUpdateFieldAssignment(index, iRecord, origValue, newValue);
}
}
}
return;
}
}
}
private static void processSingleIndexUpdate(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
final OIndexDefinition indexDefinition = index.getDefinition();
final List<String> indexFields = indexDefinition.getFields();
if (indexFields.isEmpty())
return;
final String indexField = indexFields.get(0);
if (!dirtyFields.contains(indexField))
return;
final OMultiValueChangeTimeLine<?, ?> multiValueChangeTimeLine = iRecord.getCollectionTimeLine(indexField);
if (multiValueChangeTimeLine != null) {
final OIndexDefinitionMultiValue indexDefinitionMultiValue = (OIndexDefinitionMultiValue) indexDefinition;
final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>();
final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>();
for (OMultiValueChangeEvent<?, ?> changeEvent : multiValueChangeTimeLine.getMultiValueChangeEvents()) {
indexDefinitionMultiValue.processChangeEvent(changeEvent, keysToAdd, keysToRemove);
}
for (final Object keyToRemove : keysToRemove.keySet())
index.remove(keyToRemove, iRecord);
for (final Object keyToAdd : keysToAdd.keySet())
index.put(keyToAdd, iRecord.placeholder());
} else {
final Object origValue = indexDefinition.createValue(iRecord.getOriginalValue(indexField));
final Object newValue = indexDefinition.getDocumentValueToIndex(iRecord);
processIndexUpdateFieldAssignment(index, iRecord, origValue, newValue);
}
}
private static void processIndexUpdateFieldAssignment(OIndex<?> index, ODocument iRecord, final Object origValue,
final Object newValue) {
if ((origValue instanceof Collection) && (newValue instanceof Collection)) {
final Set<Object> valuesToRemove = new HashSet<Object>((Collection<?>) origValue);
final Set<Object> valuesToAdd = new HashSet<Object>((Collection<?>) newValue);
valuesToRemove.removeAll((Collection<?>) newValue);
valuesToAdd.removeAll((Collection<?>) origValue);
for (final Object valueToRemove : valuesToRemove) {
if (valueToRemove != null) {
index.remove(valueToRemove, iRecord);
}
}
for (final Object valueToAdd : valuesToAdd) {
if (valueToAdd != null) {
index.put(valueToAdd, iRecord);
}
}
} else {
deleteIndexKey(index, iRecord, origValue);
if (newValue instanceof Collection) {
for (final Object newValueItem : (Collection<?>) newValue) {
index.put(newValueItem, iRecord.placeholder());
}
} else if (newValue != null) {
index.put(newValue, iRecord.placeholder());
}
}
}
private static boolean processCompositeIndexDelete(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
final OCompositeIndexDefinition indexDefinition = (OCompositeIndexDefinition) index.getDefinition();
final String multiValueField = indexDefinition.getMultiValueField();
final List<String> indexFields = indexDefinition.getFields();
for (final String indexField : indexFields) {
// REMOVE IT
if (dirtyFields.contains(indexField)) {
final List<Object> origValues = new ArrayList<Object>(indexFields.size());
for (final String field : indexFields) {
if (!field.equals(multiValueField))
if (dirtyFields.contains(field))
origValues.add(iRecord.getOriginalValue(field));
else
origValues.add(iRecord.<Object> field(field));
}
if (multiValueField != null) {
final OMultiValueChangeTimeLine<?, ?> multiValueChangeTimeLine = iRecord.getCollectionTimeLine(multiValueField);
if (multiValueChangeTimeLine != null) {
final OTrackedMultiValue fieldValue = iRecord.field(multiValueField);
final Object restoredMultiValue = fieldValue.returnOriginalState(multiValueChangeTimeLine.getMultiValueChangeEvents());
origValues.add(indexDefinition.getMultiValueDefinitionIndex(), restoredMultiValue);
} else if (dirtyFields.contains(multiValueField))
origValues.add(indexDefinition.getMultiValueDefinitionIndex(), iRecord.getOriginalValue(multiValueField));
else
origValues.add(indexDefinition.getMultiValueDefinitionIndex(), iRecord.field(multiValueField));
}
final Object origValue = indexDefinition.createValue(origValues);
deleteIndexKey(index, iRecord, origValue);
return true;
}
}
return false;
}
private static void deleteIndexKey(final OIndex<?> index, final ODocument iRecord, final Object origValue) {
if (origValue instanceof Collection) {
for (final Object valueItem : (Collection<?>) origValue) {
if (valueItem != null)
index.remove(valueItem, iRecord);
}
} else if (origValue != null) {
index.remove(origValue, iRecord);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static boolean processSingleIndexDelete(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
final OIndexDefinition indexDefinition = index.getDefinition();
final List<String> indexFields = indexDefinition.getFields();
if (indexFields.isEmpty()) {
return false;
}
final String indexField = indexFields.iterator().next();
if (dirtyFields.contains(indexField)) {
final OMultiValueChangeTimeLine<?, ?> multiValueChangeTimeLine = iRecord.getCollectionTimeLine(indexField);
final Object origValue;
if (multiValueChangeTimeLine != null) {
final OTrackedMultiValue fieldValue = iRecord.field(indexField);
final Object restoredMultiValue = fieldValue.returnOriginalState(multiValueChangeTimeLine.getMultiValueChangeEvents());
origValue = indexDefinition.createValue(restoredMultiValue);
} else
origValue = indexDefinition.createValue(iRecord.getOriginalValue(indexField));
deleteIndexKey(index, iRecord, origValue);
return true;
}
return false;
}
private void checkIndexesAndAquireLock(ODocument document, TYPE hookType) {
document = checkForLoading(document);
final OClass cls = document.getSchemaClass();
if (cls != null) {
final Collection<OIndex<?>> indexes = cls.getIndexes();
switch (hookType) {
case BEFORE_CREATE:
checkIndexedPropertiesOnCreation(document, indexes);
break;
case BEFORE_UPDATE:
checkIndexedPropertiesOnUpdate(document, indexes);
break;
default:
throw new IllegalArgumentException("Invalid hook type: " + hookType);
}
acquireModificationLock(indexes);
}
}
private static void checkIndexedPropertiesOnCreation(final ODocument iRecord, final Collection<OIndex<?>> iIndexes) {
for (final OIndex<?> index : iIndexes) {
final Object key = index.getDefinition().getDocumentValueToIndex(iRecord);
if (key instanceof Collection) {
for (final Object keyItem : (Collection<?>) key) {
if (keyItem != null)
index.checkEntry(iRecord, keyItem);
}
} else {
if (key != null)
index.checkEntry(iRecord, key);
}
}
}
private void acquireModificationLock(final Collection<OIndex<?>> indexes) {
if (indexes == null)
return;
final SortedSet<OIndex<?>> indexesToLock = new TreeSet<OIndex<?>>(new Comparator<OIndex<?>>() {
public int compare(OIndex<?> indexOne, OIndex<?> indexTwo) {
return indexOne.getName().compareTo(indexTwo.getName());
}
});
indexesToLock.addAll(indexes);
lockedIndexes.clear();
for (final OIndex<?> index : indexesToLock) {
index.getInternal().acquireModificationLock();
lockedIndexes.add(index.getName());
}
}
/**
* Releases the index modification lock. Incurs overhead of index retrieval: if you already have a list of indexes for the schema
* class of this record, use the overloaded method that takes a collection.
*/
private void releaseModificationLock(final ODocument iRecord) {
final OClass cls = iRecord.getSchemaClass();
if (cls != null) {
releaseModificationLock(iRecord, cls.getIndexes());
}
}
/**
* Releases the index modification lock. Avoids overhead of retrieving the schema class' indexes.
*/
private void releaseModificationLock(final ODocument iRecord, final Collection<OIndex<?>> iIndexes) {
for (final OIndex<?> index : iIndexes) {
if (lockedIndexes.contains(index.getName()))
index.getInternal().releaseModificationLock();
}
lockedIndexes.clear();
}
private static void checkIndexedPropertiesOnUpdate(final ODocument iRecord, final Collection<OIndex<?>> iIndexes) {
final Set<String> dirtyFields = new HashSet<String>(Arrays.asList(iRecord.getDirtyFields()));
if (dirtyFields.isEmpty())
return;
for (final OIndex<?> index : iIndexes) {
final OIndexDefinition indexDefinition = index.getDefinition();
final List<String> indexFields = indexDefinition.getFields();
for (final String indexField : indexFields) {
if (dirtyFields.contains(indexField)) {
final Object key = index.getDefinition().getDocumentValueToIndex(iRecord);
if (key instanceof Collection) {
for (final Object keyItem : (Collection<?>) key) {
if (keyItem != null)
index.checkEntry(iRecord, keyItem);
}
} else {
if (key != null)
index.checkEntry(iRecord, key);
}
break;
}
}
}
}
private static ODocument checkForLoading(final ODocument iRecord) {
if (iRecord.getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) {
try {
return (ODocument) iRecord.load();
} catch (final ORecordNotFoundException e) {
throw new OIndexException("Error during loading of record with id : " + iRecord.getIdentity());
}
}
return iRecord;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_index_OClassIndexManager.java
|
822 |
public class GetAndAddOperation extends AtomicLongBackupAwareOperation {
private long delta;
private long returnValue;
public GetAndAddOperation() {
}
public GetAndAddOperation(String name, long delta) {
super(name);
this.delta = delta;
}
@Override
public void run() throws Exception {
LongWrapper number = getNumber();
returnValue = number.getAndAdd(delta);
}
@Override
public Object getResponse() {
return returnValue;
}
@Override
public int getId() {
return AtomicLongDataSerializerHook.GET_AND_ADD;
}
@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();
}
public Operation getBackupOperation() {
return new AddBackupOperation(name, delta);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_operations_GetAndAddOperation.java
|
705 |
constructors[TXN_SET_ADD] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new TxnSetAddRequest();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
|
4,489 |
class CleanFilesRequestHandler extends BaseTransportRequestHandler<RecoveryCleanFilesRequest> {
@Override
public RecoveryCleanFilesRequest newInstance() {
return new RecoveryCleanFilesRequest();
}
@Override
public String executor() {
return ThreadPool.Names.GENERIC;
}
@Override
public void messageReceived(RecoveryCleanFilesRequest request, TransportChannel channel) throws Exception {
RecoveryStatus onGoingRecovery = onGoingRecoveries.get(request.recoveryId());
if (onGoingRecovery == null) {
// shard is getting closed on us
throw new IndexShardClosedException(request.shardId());
}
if (onGoingRecovery.isCanceled()) {
onGoingRecovery.sentCanceledToSource = true;
throw new IndexShardClosedException(request.shardId());
}
Store store = onGoingRecovery.indexShard.store();
// first, we go and move files that were created with the recovery id suffix to
// the actual names, its ok if we have a corrupted index here, since we have replicas
// to recover from in case of a full cluster shutdown just when this code executes...
String prefix = "recovery." + onGoingRecovery.startTime + ".";
Set<String> filesToRename = Sets.newHashSet();
for (String existingFile : store.directory().listAll()) {
if (existingFile.startsWith(prefix)) {
filesToRename.add(existingFile.substring(prefix.length(), existingFile.length()));
}
}
Exception failureToRename = null;
if (!filesToRename.isEmpty()) {
// first, go and delete the existing ones
final Directory directory = store.directory();
for (String file : filesToRename) {
try {
directory.deleteFile(file);
} catch (Throwable ex) {
logger.debug("failed to delete file [{}]", ex, file);
}
}
for (String fileToRename : filesToRename) {
// now, rename the files... and fail it it won't work
store.renameFile(prefix + fileToRename, fileToRename);
}
}
// now write checksums
store.writeChecksums(onGoingRecovery.checksums);
for (String existingFile : store.directory().listAll()) {
// don't delete snapshot file, or the checksums file (note, this is extra protection since the Store won't delete checksum)
if (!request.snapshotFiles().contains(existingFile) && !Store.isChecksum(existingFile)) {
try {
store.directory().deleteFile(existingFile);
} catch (Exception e) {
// ignore, we don't really care, will get deleted later on
}
}
}
channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
}
| 1no label
|
src_main_java_org_elasticsearch_indices_recovery_RecoveryTarget.java
|
4,199 |
static final class Fields {
static final XContentBuilderString NAME = new XContentBuilderString("name");
static final XContentBuilderString PHYSICAL_NAME = new XContentBuilderString("physical_name");
static final XContentBuilderString LENGTH = new XContentBuilderString("length");
static final XContentBuilderString CHECKSUM = new XContentBuilderString("checksum");
static final XContentBuilderString PART_SIZE = new XContentBuilderString("part_size");
}
| 1no label
|
src_main_java_org_elasticsearch_index_snapshots_blobstore_BlobStoreIndexShardSnapshot.java
|
154 |
public static final Map<String, ConfigOption> REGISTERED_STORAGE_MANAGERS_SHORTHAND = new HashMap<String, ConfigOption>() {{
put("berkeleyje", STORAGE_DIRECTORY);
put("hazelcast", STORAGE_DIRECTORY);
put("hazelcastcache", STORAGE_DIRECTORY);
put("infinispan", STORAGE_DIRECTORY);
put("cassandra", STORAGE_HOSTS);
put("cassandrathrift", STORAGE_HOSTS);
put("astyanax", STORAGE_HOSTS);
put("hbase", STORAGE_HOSTS);
put("embeddedcassandra", STORAGE_CONF_FILE);
put("inmemory", null);
}};
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java
|
4,183 |
public class IndexShardSnapshotAndRestoreService extends AbstractIndexShardComponent {
private final InternalIndexShard indexShard;
private final RepositoriesService repositoriesService;
private final RestoreService restoreService;
@Inject
public IndexShardSnapshotAndRestoreService(ShardId shardId, @IndexSettings Settings indexSettings, IndexShard indexShard, RepositoriesService repositoriesService, RestoreService restoreService) {
super(shardId, indexSettings);
this.indexShard = (InternalIndexShard) indexShard;
this.repositoriesService = repositoriesService;
this.restoreService = restoreService;
}
/**
* Creates shard snapshot
*
* @param snapshotId snapshot id
* @param snapshotStatus snapshot status
*/
public void snapshot(final SnapshotId snapshotId, final IndexShardSnapshotStatus snapshotStatus) {
IndexShardRepository indexShardRepository = repositoriesService.indexShardRepository(snapshotId.getRepository());
if (!indexShard.routingEntry().primary()) {
throw new IndexShardSnapshotFailedException(shardId, "snapshot should be performed only on primary");
}
if (indexShard.routingEntry().relocating()) {
// do not snapshot when in the process of relocation of primaries so we won't get conflicts
throw new IndexShardSnapshotFailedException(shardId, "cannot snapshot while relocating");
}
if (indexShard.state() == IndexShardState.CREATED || indexShard.state() == IndexShardState.RECOVERING) {
// shard has just been created, or still recovering
throw new IndexShardSnapshotFailedException(shardId, "shard didn't fully recover yet");
}
try {
SnapshotIndexCommit snapshotIndexCommit = indexShard.snapshotIndex();
try {
indexShardRepository.snapshot(snapshotId, shardId, snapshotIndexCommit, snapshotStatus);
if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
sb.append("snapshot (").append(snapshotId.getSnapshot()).append(") completed to ").append(indexShardRepository).append(", took [").append(TimeValue.timeValueMillis(snapshotStatus.time())).append("]\n");
sb.append(" index : version [").append(snapshotStatus.indexVersion()).append("], number_of_files [").append(snapshotStatus.numberOfFiles()).append("] with total_size [").append(new ByteSizeValue(snapshotStatus.totalSize())).append("]\n");
logger.debug(sb.toString());
}
} finally {
snapshotIndexCommit.release();
}
} catch (SnapshotFailedEngineException e) {
throw e;
} catch (IndexShardSnapshotFailedException e) {
throw e;
} catch (Throwable e) {
throw new IndexShardSnapshotFailedException(shardId, "Failed to snapshot", e);
}
}
/**
* Restores shard from {@link RestoreSource} associated with this shard in routing table
*
* @param recoveryStatus recovery status
*/
public void restore(final RecoveryStatus recoveryStatus) {
RestoreSource restoreSource = indexShard.routingEntry().restoreSource();
if (restoreSource == null) {
throw new IndexShardRestoreFailedException(shardId, "empty restore source");
}
if (logger.isTraceEnabled()) {
logger.trace("[{}] restoring shard [{}]", restoreSource.snapshotId(), shardId);
}
try {
IndexShardRepository indexShardRepository = repositoriesService.indexShardRepository(restoreSource.snapshotId().getRepository());
ShardId snapshotShardId = shardId;
if (!shardId.getIndex().equals(restoreSource.index())) {
snapshotShardId = new ShardId(restoreSource.index(), shardId.id());
}
indexShardRepository.restore(restoreSource.snapshotId(), shardId, snapshotShardId, recoveryStatus);
restoreService.indexShardRestoreCompleted(restoreSource.snapshotId(), shardId);
} catch (Throwable t) {
throw new IndexShardRestoreFailedException(shardId, "restore failed", t);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_snapshots_IndexShardSnapshotAndRestoreService.java
|
429 |
public class ClusterStateResponse extends ActionResponse {
private ClusterName clusterName;
private ClusterState clusterState;
public ClusterStateResponse() {
}
ClusterStateResponse(ClusterName clusterName, ClusterState clusterState) {
this.clusterName = clusterName;
this.clusterState = clusterState;
}
public ClusterState getState() {
return this.clusterState;
}
public ClusterName getClusterName() {
return this.clusterName;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
clusterName = ClusterName.readClusterName(in);
clusterState = ClusterState.Builder.readFrom(in, null);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
clusterName.writeTo(out);
ClusterState.Builder.writeTo(clusterState, out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_state_ClusterStateResponse.java
|
78 |
public class OSharedResourceIterator<T> implements Iterator<T>, OResettable {
protected final OSharedResourceAdaptiveExternal resource;
protected Iterator<?> iterator;
public OSharedResourceIterator(final OSharedResourceAdaptiveExternal iResource, final Iterator<?> iIterator) {
this.resource = iResource;
this.iterator = iIterator;
}
@Override
public boolean hasNext() {
resource.acquireExclusiveLock();
try {
return iterator.hasNext();
} finally {
resource.releaseExclusiveLock();
}
}
@SuppressWarnings("unchecked")
@Override
public T next() {
resource.acquireExclusiveLock();
try {
return (T) iterator.next();
} finally {
resource.releaseExclusiveLock();
}
}
@Override
public void remove() {
resource.acquireExclusiveLock();
try {
iterator.remove();
} finally {
resource.releaseExclusiveLock();
}
}
@Override
public void reset() {
if( !( iterator instanceof OResettable) )
return;
resource.acquireExclusiveLock();
try {
((OResettable) iterator).reset();
} finally {
resource.releaseExclusiveLock();
}
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceIterator.java
|
168 |
static final class EmptyTask extends ForkJoinTask<Void> {
private static final long serialVersionUID = -7721805057305804111L;
EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
public final Void getRawResult() { return null; }
public final void setRawResult(Void x) {}
public final boolean exec() { return true; }
}
| 0true
|
src_main_java_jsr166y_ForkJoinPool.java
|
1,005 |
public class OStreamSerializerOldRIDContainer implements OStreamSerializer, OBinarySerializer<OIndexRIDContainerSBTree> {
public static final String NAME = "ic";
public static final OStreamSerializerOldRIDContainer INSTANCE = new OStreamSerializerOldRIDContainer();
private static final ORecordSerializerSchemaAware2CSV FORMAT = (ORecordSerializerSchemaAware2CSV) ORecordSerializerFactory
.instance().getFormat(ORecordSerializerSchemaAware2CSV.NAME);
public static final byte ID = 20;
public Object fromStream(final byte[] iStream) throws IOException {
if (iStream == null)
return null;
final String s = OBinaryProtocol.bytes2string(iStream);
return FORMAT.embeddedCollectionFromStream(null, OType.EMBEDDEDSET, null, OType.LINK, s);
}
public byte[] toStream(final Object object) throws IOException {
if (object == null)
return null;
return containerToStream((OIndexRIDContainerSBTree) object);
}
public String getName() {
return NAME;
}
@Override
public int getObjectSize(OIndexRIDContainerSBTree object, Object... hints) {
final byte[] serializedSet = containerToStream(object);
return OBinaryTypeSerializer.INSTANCE.getObjectSize(serializedSet);
}
@Override
public int getObjectSize(byte[] stream, int startPosition) {
return OBinaryTypeSerializer.INSTANCE.getObjectSize(stream, startPosition);
}
@Override
public void serialize(OIndexRIDContainerSBTree object, byte[] stream, int startPosition, Object... hints) {
final byte[] serializedSet = containerToStream(object);
OBinaryTypeSerializer.INSTANCE.serialize(serializedSet, stream, startPosition);
}
@Override
public OIndexRIDContainerSBTree deserialize(byte[] stream, int startPosition) {
final byte[] serializedSet = OBinaryTypeSerializer.INSTANCE.deserialize(stream, startPosition);
final String s = OBinaryProtocol.bytes2string(serializedSet);
if (s.startsWith("<#@")) {
return containerFromStream(s);
}
return (OIndexRIDContainerSBTree) FORMAT.embeddedCollectionFromStream(null, OType.EMBEDDEDSET, null, OType.LINK, s);
}
@Override
public byte getId() {
return ID;
}
@Override
public boolean isFixedLength() {
return false;
}
@Override
public int getFixedLength() {
return 0;
}
@Override
public void serializeNative(OIndexRIDContainerSBTree object, byte[] stream, int startPosition, Object... hints) {
final byte[] serializedSet = containerToStream(object);
OBinaryTypeSerializer.INSTANCE.serializeNative(serializedSet, stream, startPosition);
}
@Override
public OIndexRIDContainerSBTree deserializeNative(byte[] stream, int startPosition) {
final byte[] serializedSet = OBinaryTypeSerializer.INSTANCE.deserializeNative(stream, startPosition);
final String s = OBinaryProtocol.bytes2string(serializedSet);
if (s.startsWith("<#@")) {
return containerFromStream(s);
}
return (OIndexRIDContainerSBTree) FORMAT.embeddedCollectionFromStream(null, OType.EMBEDDEDSET, null, OType.LINK, s);
}
@Override
public int getObjectSizeNative(byte[] stream, int startPosition) {
return OBinaryTypeSerializer.INSTANCE.getObjectSizeNative(stream, startPosition);
}
@Override
public void serializeInDirectMemory(OIndexRIDContainerSBTree object, ODirectMemoryPointer pointer, long offset, Object... hints) {
final byte[] serializedSet = containerToStream(object);
OBinaryTypeSerializer.INSTANCE.serializeInDirectMemory(serializedSet, pointer, offset);
}
@Override
public OIndexRIDContainerSBTree deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) {
final byte[] serializedSet = OBinaryTypeSerializer.INSTANCE.deserializeFromDirectMemory(pointer, offset);
final String s = OBinaryProtocol.bytes2string(serializedSet);
if (s.startsWith("<#@")) {
return containerFromStream(s);
}
return (OIndexRIDContainerSBTree) FORMAT.embeddedCollectionFromStream(null, OType.EMBEDDEDSET, null, OType.LINK, s);
}
@Override
public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) {
return OBinaryTypeSerializer.INSTANCE.getObjectSizeInDirectMemory(pointer, offset);
}
@Override
public OIndexRIDContainerSBTree preprocess(OIndexRIDContainerSBTree value, Object... hints) {
return value;
}
private byte[] containerToStream(OIndexRIDContainerSBTree object) {
StringBuilder iOutput = new StringBuilder();
iOutput.append(OStringSerializerHelper.LINKSET_PREFIX);
final ODocument document = new ODocument();
document.field("rootIndex", object.getRootPointer().getPageIndex());
document.field("rootOffset", object.getRootPointer().getPageOffset());
document.field("file", object.getFileName());
iOutput.append(new String(document.toStream()));
iOutput.append(OStringSerializerHelper.SET_END);
return iOutput.toString().getBytes();
}
private OIndexRIDContainerSBTree containerFromStream(String stream) {
stream = stream.substring(OStringSerializerHelper.LINKSET_PREFIX.length(), stream.length() - 1);
final ODocument doc = new ODocument();
doc.fromString(stream);
final OBonsaiBucketPointer rootPointer = new OBonsaiBucketPointer((Long) doc.field("rootIndex"),
(Integer) doc.field("rootOffset"));
final String fileName = doc.field("file");
return new OIndexRIDContainerSBTree(fileName, rootPointer);
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_stream_OStreamSerializerOldRIDContainer.java
|
1,117 |
public class OSQLFunctionSum extends OSQLFunctionMathAbstract {
public static final String NAME = "sum";
private Number sum;
public OSQLFunctionSum() {
super(NAME, 1, -1);
}
public Object execute(final OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters,
OCommandContext iContext) {
if (iParameters.length == 1) {
if (iParameters[0] instanceof Number)
sum((Number) iParameters[0]);
else if (OMultiValue.isMultiValue(iParameters[0]))
for (Object n : OMultiValue.getMultiValueIterable(iParameters[0]))
sum((Number) n);
} else {
sum = null;
for (int i = 0; i < iParameters.length; ++i)
sum((Number) iParameters[i]);
}
return sum;
}
protected void sum(final Number value) {
if (value != null) {
if (sum == null)
// FIRST TIME
sum = value;
else
sum = OType.increment(sum, value);
}
}
@Override
public boolean aggregateResults() {
return configuredParameters.length == 1;
}
public String getSyntax() {
return "Syntax error: sum(<field> [,<field>*])";
}
@Override
public Object getResult() {
return sum;
}
@Override
public Object mergeDistributedResult(List<Object> resultsToMerge) {
Number sum = null;
for (Object iParameter : resultsToMerge) {
final Number value = (Number) iParameter;
if (value != null) {
if (sum == null)
// FIRST TIME
sum = value;
else
sum = OType.increment(sum, value);
}
}
return sum;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_functions_math_OSQLFunctionSum.java
|
231 |
assertTrueEventually(new AssertTask() {
public void run() throws Exception {
assertTrue(map.containsKey(targetUuid));
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceExecuteTest.java
|
267 |
public class FailingCallable implements Callable<String>, DataSerializable {
public String call() throws Exception {
throw new IllegalStateException();
}
public void writeData(ObjectDataOutput out) throws IOException {
}
public void readData(ObjectDataInput in) throws IOException {
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_tasks_FailingCallable.java
|
103 |
public static class Presentation {
public static class Tab {
public static class Name {
public static final String Rules = "PageImpl_Rules_Tab";
}
public static class Order {
public static final int Rules = 1000;
}
}
public static class Group {
public static class Name {
public static final String Basic = "PageImpl_Basic";
public static final String Page = "PageImpl_Page";
public static final String Rules = "PageImpl_Rules";
}
public static class Order {
public static final int Basic = 1000;
public static final int Page = 2000;
public static final int Rules = 1000;
}
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageImpl.java
|
1,303 |
public interface Custom {
interface Factory<T extends Custom> {
String type();
T readFrom(StreamInput in) throws IOException;
void writeTo(T customState, StreamOutput out) throws IOException;
void toXContent(T customState, XContentBuilder builder, ToXContent.Params params);
}
}
| 0true
|
src_main_java_org_elasticsearch_cluster_ClusterState.java
|
343 |
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ClientMapTryLockConcurrentTests {
static HazelcastInstance client;
static HazelcastInstance server;
@BeforeClass
public static void init() {
server = Hazelcast.newHazelcastInstance();
client = HazelcastClient.newHazelcastClient();
}
@AfterClass
public static void destroy() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void concurrent_MapTryLockTest() throws InterruptedException {
concurrent_MapTryLock(false);
}
@Test
public void concurrent_MapTryLockTimeOutTest() throws InterruptedException {
concurrent_MapTryLock(true);
}
private void concurrent_MapTryLock(boolean withTimeOut) throws InterruptedException {
final int maxThreads = 8;
final IMap<String, Integer> map = client.getMap(randomString());
final String upKey = "upKey";
final String downKey = "downKey";
map.put(upKey, 0);
map.put(downKey, 0);
Thread threads[] = new Thread[maxThreads];
for ( int i=0; i< threads.length; i++ ) {
Thread t;
if(withTimeOut){
t = new MapTryLockTimeOutThread(map, upKey, downKey);
}else{
t = new MapTryLockThread(map, upKey, downKey);
}
t.start();
threads[i] = t;
}
assertJoinable(threads);
int upTotal = map.get(upKey);
int downTotal = map.get(downKey);
assertTrue("concurrent access to locked code caused wrong total", upTotal + downTotal == 0);
}
static class MapTryLockThread extends TestHelper {
public MapTryLockThread(IMap map, String upKey, String downKey){
super(map, upKey, downKey);
}
public void doRun() throws Exception{
if(map.tryLock(upKey)){
try{
if(map.tryLock(downKey)){
try {
work();
}finally {
map.unlock(downKey);
}
}
}finally {
map.unlock(upKey);
}
}
}
}
static class MapTryLockTimeOutThread extends TestHelper {
public MapTryLockTimeOutThread(IMap map, String upKey, String downKey){
super(map, upKey, downKey);
}
public void doRun() throws Exception{
if(map.tryLock(upKey, 1, TimeUnit.MILLISECONDS)){
try{
if(map.tryLock(downKey, 1, TimeUnit.MILLISECONDS )){
try {
work();
}finally {
map.unlock(downKey);
}
}
}finally {
map.unlock(upKey);
}
}
}
}
static abstract class TestHelper extends Thread {
protected static final int ITERATIONS = 1000*10;
protected final Random random = new Random();
protected final IMap<String, Integer> map;
protected final String upKey;
protected final String downKey;
public TestHelper(IMap map, String upKey, String downKey){
this.map = map;
this.upKey = upKey;
this.downKey = downKey;
}
public void run() {
try{
for ( int i=0; i < ITERATIONS; i++ ) {
doRun();
}
}catch(Exception e){
throw new RuntimeException("Test Thread crashed with ", e);
}
}
abstract void doRun()throws Exception;
public void work(){
int upTotal = map.get(upKey);
int downTotal = map.get(downKey);
int dif = random.nextInt(1000);
upTotal += dif;
downTotal -= dif;
map.put(upKey, upTotal);
map.put(downKey, downTotal);
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTryLockConcurrentTests.java
|
84 |
@SuppressWarnings("serial")
static final class MapReduceValuesToLongTask<K,V>
extends BulkTask<K,V,Long> {
final ObjectToLong<? super V> transformer;
final LongByLongToLong reducer;
final long basis;
long result;
MapReduceValuesToLongTask<K,V> rights, nextRight;
MapReduceValuesToLongTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceValuesToLongTask<K,V> nextRight,
ObjectToLong<? super V> transformer,
long basis,
LongByLongToLong reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Long getRawResult() { return result; }
public final void compute() {
final ObjectToLong<? super V> transformer;
final LongByLongToLong reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
long r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceValuesToLongTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.apply(r, transformer.apply(p.val));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
t = (MapReduceValuesToLongTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.apply(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
803 |
public class AtomicLongPortableHook implements PortableHook {
static final int F_ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.ATOMIC_LONG_PORTABLE_FACTORY, -17);
static final int ADD_AND_GET = 1;
static final int COMPARE_AND_SET = 2;
static final int GET_AND_ADD = 3;
static final int GET_AND_SET = 4;
static final int SET = 5;
static final int APPLY = 6;
static final int ALTER = 7;
static final int ALTER_AND_GET = 8;
static final int GET_AND_ALTER = 9;
@Override
public int getFactoryId() {
return F_ID;
}
@Override
public PortableFactory createFactory() {
return new PortableFactory() {
@Override
public Portable create(int classId) {
switch (classId) {
case ADD_AND_GET:
return new AddAndGetRequest();
case COMPARE_AND_SET:
return new CompareAndSetRequest();
case GET_AND_ADD:
return new GetAndAddRequest();
case GET_AND_SET:
return new GetAndSetRequest();
case SET:
return new SetRequest();
case APPLY:
return new ApplyRequest();
case ALTER:
return new AlterRequest();
case ALTER_AND_GET:
return new AlterAndGetRequest();
case GET_AND_ALTER:
return new GetAndAlterRequest();
default:
return null;
}
}
};
}
@Override
public Collection<ClassDefinition> getBuiltinDefinitions() {
return null;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_AtomicLongPortableHook.java
|
69 |
{
@Override
public int compare( Record r1, Record r2 )
{
return r1.getSequenceNumber() - r2.getSequenceNumber();
}
} );
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TxLog.java
|
814 |
public static class Item {
private final int slot;
private final PercolateShardResponse response;
private final Text error;
public Item(Integer slot, PercolateShardResponse response) {
this.slot = slot;
this.response = response;
this.error = null;
}
public Item(Integer slot, Text error) {
this.slot = slot;
this.error = error;
this.response = null;
}
public int slot() {
return slot;
}
public PercolateShardResponse response() {
return response;
}
public Text error() {
return error;
}
public boolean failed() {
return error != null;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_percolate_TransportShardMultiPercolateAction.java
|
20 |
public class IllegalLogFormatException extends IOException
{
public IllegalLogFormatException( long expected, long was )
{
super( "Invalid log format version found, expected " + expected + " but was " + was +
". To be able to upgrade from an older log format version there must have " +
"been a clean shutdown of the database" );
}
}
| 1no label
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_IllegalLogFormatException.java
|
589 |
@RunWith(HazelcastSerialClassRunner.class)
@Category(NightlyTest.class)
public class EncryptionTest {
@BeforeClass
@AfterClass
public static void killAllHazelcastInstances() throws IOException {
Hazelcast.shutdownAll();
}
/**
* Simple symmetric encryption test.
*/
@Test
@Category(ProblematicTest.class)
public void testSymmetricEncryption() throws Exception {
Config config = new Config();
SymmetricEncryptionConfig encryptionConfig = new SymmetricEncryptionConfig();
encryptionConfig.setEnabled(true);
config.getNetworkConfig().setSymmetricEncryptionConfig(encryptionConfig);
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
assertEquals(3, h1.getCluster().getMembers().size());
assertEquals(3, h2.getCluster().getMembers().size());
assertEquals(3, h3.getCluster().getMembers().size());
assertEquals(h1.getCluster().getLocalMember(), h2.getCluster().getMembers().iterator().next());
assertEquals(h1.getCluster().getLocalMember(), h3.getCluster().getMembers().iterator().next());
warmUpPartitions(h1, h2, h3);
Member owner1 = h1.getPartitionService().getPartition(0).getOwner();
Member owner2 = h2.getPartitionService().getPartition(0).getOwner();
Member owner3 = h3.getPartitionService().getPartition(0).getOwner();
assertEquals(owner1, owner2);
assertEquals(owner1, owner3);
String name = "encryption-test";
IMap<Integer, byte[]> map1 = h1.getMap(name);
for (int i = 1; i < 100; i++) {
map1.put(i, new byte[1024 * i]);
}
IMap<Integer, byte[]> map2 = h2.getMap(name);
for (int i = 1; i < 100; i++) {
byte[] bytes = map2.get(i);
assertEquals(i * 1024, bytes.length);
}
IMap<Integer, byte[]> map3 = h3.getMap(name);
for (int i = 1; i < 100; i++) {
byte[] bytes = map3.get(i);
assertEquals(i * 1024, bytes.length);
}
}
}
| 0true
|
hazelcast_src_test_java_com_hazelcast_cluster_EncryptionTest.java
|
173 |
public class EideticTransactionMonitor implements TransactionMonitor
{
private int commitCount;
private int injectOnePhaseCommitCount;
private int injectTwoPhaseCommitCount;
@Override
public void transactionCommitted( Xid xid, boolean recovered )
{
commitCount++;
}
@Override
public void injectOnePhaseCommit( Xid xid )
{
injectOnePhaseCommitCount++;
}
@Override
public void injectTwoPhaseCommit( Xid xid )
{
injectTwoPhaseCommitCount++;
}
public int getCommitCount()
{
return commitCount;
}
public int getInjectOnePhaseCommitCount()
{
return injectOnePhaseCommitCount;
}
public int getInjectTwoPhaseCommitCount()
{
return injectTwoPhaseCommitCount;
}
}
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_EideticTransactionMonitor.java
|
2,600 |
new BaseTransportResponseHandler<MasterPingResponseResponse>() {
@Override
public MasterPingResponseResponse newInstance() {
return new MasterPingResponseResponse();
}
@Override
public void handleResponse(MasterPingResponseResponse response) {
if (!running) {
return;
}
// reset the counter, we got a good result
MasterFaultDetection.this.retryCount = 0;
// check if the master node did not get switched on us..., if it did, we simply return with no reschedule
if (masterToPing.equals(MasterFaultDetection.this.masterNode())) {
if (!response.connectedToMaster) {
logger.trace("[master] [{}] does not have us registered with it...", masterToPing);
notifyDisconnectedFromMaster();
}
// we don't stop on disconnection from master, we keep pinging it
threadPool.schedule(pingInterval, ThreadPool.Names.SAME, MasterPinger.this);
}
}
@Override
public void handleException(TransportException exp) {
if (!running) {
return;
}
if (exp instanceof ConnectTransportException) {
// ignore this one, we already handle it by registering a connection listener
return;
}
synchronized (masterNodeMutex) {
// check if the master node did not get switched on us...
if (masterToPing.equals(MasterFaultDetection.this.masterNode())) {
if (exp.getCause() instanceof NoLongerMasterException) {
logger.debug("[master] pinging a master {} that is no longer a master", masterNode);
notifyMasterFailure(masterToPing, "no longer master");
return;
} else if (exp.getCause() instanceof NotMasterException) {
logger.debug("[master] pinging a master {} that is not the master", masterNode);
notifyMasterFailure(masterToPing, "not master");
return;
} else if (exp.getCause() instanceof NodeDoesNotExistOnMasterException) {
logger.debug("[master] pinging a master {} but we do not exists on it, act as if its master failure", masterNode);
notifyMasterFailure(masterToPing, "do not exists on master, act as master failure");
return;
}
int retryCount = ++MasterFaultDetection.this.retryCount;
logger.trace("[master] failed to ping [{}], retry [{}] out of [{}]", exp, masterNode, retryCount, pingRetryCount);
if (retryCount >= pingRetryCount) {
logger.debug("[master] failed to ping [{}], tried [{}] times, each with maximum [{}] timeout", masterNode, pingRetryCount, pingRetryTimeout);
// not good, failure
notifyMasterFailure(masterToPing, "failed to ping, tried [" + pingRetryCount + "] times, each with maximum [" + pingRetryTimeout + "] timeout");
} else {
// resend the request, not reschedule, rely on send timeout
transportService.sendRequest(masterToPing, MasterPingRequestHandler.ACTION, new MasterPingRequest(nodesProvider.nodes().localNode().id(), masterToPing.id()), options().withType(TransportRequestOptions.Type.PING).withTimeout(pingRetryTimeout), this);
}
}
}
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
});
| 1no label
|
src_main_java_org_elasticsearch_discovery_zen_fd_MasterFaultDetection.java
|
506 |
public class TransportCreateIndexAction extends TransportMasterNodeOperationAction<CreateIndexRequest, CreateIndexResponse> {
private final MetaDataCreateIndexService createIndexService;
@Inject
public TransportCreateIndexAction(Settings settings, TransportService transportService, ClusterService clusterService,
ThreadPool threadPool, MetaDataCreateIndexService createIndexService) {
super(settings, transportService, clusterService, threadPool);
this.createIndexService = createIndexService;
}
@Override
protected String executor() {
// we go async right away
return ThreadPool.Names.SAME;
}
@Override
protected String transportAction() {
return CreateIndexAction.NAME;
}
@Override
protected CreateIndexRequest newRequest() {
return new CreateIndexRequest();
}
@Override
protected CreateIndexResponse newResponse() {
return new CreateIndexResponse();
}
@Override
protected ClusterBlockException checkBlock(CreateIndexRequest request, ClusterState state) {
return state.blocks().indexBlockedException(ClusterBlockLevel.METADATA, request.index());
}
@Override
protected void masterOperation(final CreateIndexRequest request, final ClusterState state, final ActionListener<CreateIndexResponse> listener) throws ElasticsearchException {
String cause = request.cause();
if (cause.length() == 0) {
cause = "api";
}
CreateIndexClusterStateUpdateRequest updateRequest = new CreateIndexClusterStateUpdateRequest(cause, request.index())
.ackTimeout(request.timeout()).masterNodeTimeout(request.masterNodeTimeout())
.settings(request.settings()).mappings(request.mappings())
.customs(request.customs());
createIndexService.createIndex(updateRequest, new ClusterStateUpdateListener() {
@Override
public void onResponse(ClusterStateUpdateResponse response) {
listener.onResponse(new CreateIndexResponse(response.isAcknowledged()));
}
@Override
public void onFailure(Throwable t) {
if (t instanceof IndexAlreadyExistsException) {
logger.trace("[{}] failed to create", t, request.index());
} else {
logger.debug("[{}] failed to create", t, request.index());
}
listener.onFailure(t);
}
});
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_admin_indices_create_TransportCreateIndexAction.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.